summaryrefslogtreecommitdiffstats
path: root/kalarm/birthdaydlg.cpp
blob: 97e7bc6f70667c1082cfb2be9167a893dd359609 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
/*
 *  birthdaydlg.cpp  -  dialog to pick birthdays from address book
 *  Program:  kalarm
 *  Copyright © 2002-2008 by David Jarvie <djarvie@kde.org>
 *
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License along
 *  with this program; if not, write to the Free Software Foundation, Inc.,
 *  51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 */

#include "kalarm.h"

#include <tqlayout.h>
#include <tqgroupbox.h>
#include <tqhbox.h>
#include <tqlabel.h>
#include <tqlineedit.h>
#include <tqwhatsthis.h>

#include <klocale.h>
#include <kglobal.h>
#include <kconfig.h>
#include <kmessagebox.h>
#include <kaccel.h>
#include <kabc/addressbook.h>
#include <kabc/stdaddressbook.h>
#include <kdebug.h>

#include "alarmcalendar.h"
#include "checkbox.h"
#include "colourcombo.h"
#include "editdlg.h"
#include "fontcolourbutton.h"
#include "kalarmapp.h"
#include "latecancel.h"
#include "preferences.h"
#include "reminder.h"
#include "repetition.h"
#include "shellprocess.h"
#include "soundpicker.h"
#include "specialactions.h"
#include "birthdaydlg.moc"

using namespace KCal;


class AddresseeItem : public TQListViewItem
{
	public:
		enum columns { NAME = 0, BIRTHDAY = 1 };
		AddresseeItem(TQListView* parent, const TQString& name, const TQDate& birthday);
		TQDate birthday() const   { return mBirthday; }
		virtual TQString key(int column, bool ascending) const;
	private:
		TQDate     mBirthday;
		TQString   mBirthdayOrder;
};


const KABC::AddressBook* BirthdayDlg::mAddressBook = 0;


BirthdayDlg::BirthdayDlg(TQWidget* parent)
	: KDialogBase(KDialogBase::Plain, i18n("Import Birthdays From KAddressBook"), Ok|Cancel, Ok, parent, "BirthdayDlg"),
	  mSpecialActionsButton(0)
{
	TQWidget* topWidget = plainPage();
	TQBoxLayout* topLayout = new TQVBoxLayout(topWidget);
	topLayout->setSpacing(spacingHint());

	// Prefix and suffix to the name in the alarm text
	// Get default prefix and suffix texts from config file
	KConfig* config = kapp->config();
	config->setGroup(TQString::tqfromLatin1("General"));
	mPrefixText = config->readEntry(TQString::tqfromLatin1("BirthdayPrefix"), i18n("Birthday: "));
	mSuffixText = config->readEntry(TQString::tqfromLatin1("BirthdaySuffix"));

	TQGroupBox* textGroup = new TQGroupBox(2, Qt::Horizontal, i18n("Alarm Text"), topWidget);
	topLayout->addWidget(textGroup);
	TQLabel* label = new TQLabel(i18n("Pre&fix:"), textGroup);
	mPrefix = new BLineEdit(mPrefixText, textGroup);
	mPrefix->setMinimumSize(mPrefix->tqsizeHint());
	label->setBuddy(mPrefix);
	connect(mPrefix, TQT_SIGNAL(focusLost()), TQT_SLOT(slotTextLostFocus()));
	TQWhatsThis::add(mPrefix,
	      i18n("Enter text to appear before the person's name in the alarm message, "
	           "including any necessary trailing spaces."));

	label = new TQLabel(i18n("S&uffix:"), textGroup);
	mSuffix = new BLineEdit(mSuffixText, textGroup);
	mSuffix->setMinimumSize(mSuffix->tqsizeHint());
	label->setBuddy(mSuffix);
	connect(mSuffix, TQT_SIGNAL(focusLost()), TQT_SLOT(slotTextLostFocus()));
	TQWhatsThis::add(mSuffix,
	      i18n("Enter text to appear after the person's name in the alarm message, "
	           "including any necessary leading spaces."));

	TQGroupBox* group = new TQGroupBox(1, Qt::Horizontal, i18n("Select Birthdays"), topWidget);
	topLayout->addWidget(group);
	mAddresseeList = new BListView(group);
	mAddresseeList->setMultiSelection(true);
	mAddresseeList->setSelectionMode(TQListView::Extended);
	mAddresseeList->setAllColumnsShowFocus(true);
	mAddresseeList->setFullWidth(true);
	mAddresseeList->addColumn(i18n("Name"));
	mAddresseeList->addColumn(i18n("Birthday"));
	connect(mAddresseeList, TQT_SIGNAL(selectionChanged()), TQT_SLOT(slotSelectionChanged()));
	TQWhatsThis::add(mAddresseeList,
	      i18n("Select birthdays to set alarms for.\n"
	           "This list shows all birthdays in KAddressBook except those for which alarms already exist.\n\n"
	           "You can select multiple birthdays at one time by dragging the mouse over the list, "
	           "or by clicking the mouse while pressing Ctrl or Shift."));

	group = new TQGroupBox(i18n("Alarm Configuration"), topWidget);
	topLayout->addWidget(group);
	TQBoxLayout* groupLayout = new TQVBoxLayout(group, marginHint(), spacingHint());
	groupLayout->addSpacing(fontMetrics().lineSpacing()/2);

	// Font and colour choice button and sample text
	mFontColourButton = new FontColourButton(group);
	mFontColourButton->setMaximumHeight(mFontColourButton->tqsizeHint().height() * 3/2);
	groupLayout->addWidget(mFontColourButton);

	// Sound checkbox and file selector
	mSoundPicker = new SoundPicker(group);
	mSoundPicker->setFixedSize(mSoundPicker->tqsizeHint());
	groupLayout->addWidget(mSoundPicker, 0, TQt::AlignAuto);

	// How much to advance warning to give
	mReminder = new Reminder(i18n("&Reminder"),
	                         i18n("Check to display a reminder in advance of the birthday."),
	                         i18n("Enter the number of days before each birthday to display a reminder. "
	                              "This is in addition to the alarm which is displayed on the birthday."),
	                         false, false, group);
	mReminder->setFixedSize(mReminder->tqsizeHint());
	mReminder->setMaximum(0, 364);
	mReminder->setMinutes(0, true);
	groupLayout->addWidget(mReminder, 0, TQt::AlignAuto);

	// Acknowledgement confirmation required - default = no confirmation
	TQHBoxLayout* tqlayout = new TQHBoxLayout(groupLayout, 2*spacingHint());
	mConfirmAck = EditAlarmDlg::createConfirmAckCheckbox(group);
	tqlayout->addWidget(mConfirmAck);
	tqlayout->addSpacing(2*spacingHint());
	tqlayout->addStretch();

	if (ShellProcess::authorised())    // don't display if shell commands not allowed (e.g. kiosk mode)
	{
		// Special actions button
		mSpecialActionsButton = new SpecialActionsButton(i18n("Special Actions..."), group);
		tqlayout->addWidget(mSpecialActionsButton);
	}

	// Late display checkbox - default = allow late display
	tqlayout = new TQHBoxLayout(groupLayout, 2*spacingHint());
	mLateCancel = new LateCancelSelector(false, group);
	tqlayout->addWidget(mLateCancel);
	tqlayout->addStretch();

	// Sub-repetition button
	mSubRepetition = new RepetitionButton(i18n("Sub-Repetition"), false, group);
	mSubRepetition->set(0, 0, true, 364*24*60);
	TQWhatsThis::add(mSubRepetition, i18n("Set up an additional alarm repetition"));
	tqlayout->addWidget(mSubRepetition);

	// Set the values to their defaults
	mFontColourButton->setDefaultFont();
	mFontColourButton->setBgColour(Preferences::defaultBgColour());
	mFontColourButton->setFgColour(Preferences::defaultFgColour());     // set colour before setting alarm type buttons
	mLateCancel->setMinutes(Preferences::defaultLateCancel(), true, TimePeriod::DAYS);
	mConfirmAck->setChecked(Preferences::defaultConfirmAck());
	mSoundPicker->set(Preferences::defaultSoundType(), Preferences::defaultSoundFile(),
	                  Preferences::defaultSoundVolume(), -1, 0, Preferences::defaultSoundRepeat());
	if (mSpecialActionsButton)
		mSpecialActionsButton->setActions(Preferences::defaultPreAction(), Preferences::defaultPostAction());

	// Initialise the birthday selection list and disable the OK button
	loadAddressBook();
}

/******************************************************************************
* Load the address book in preparation for displaying the birthday selection list.
*/
void BirthdayDlg::loadAddressBook()
{
	if (!mAddressBook)
	{
#if KDE_IS_VERSION(3,1,90)
        	mAddressBook = KABC::StdAddressBook::self(true);
		if (mAddressBook)
                	connect(mAddressBook, TQT_SIGNAL(addressBookChanged(AddressBook*)), TQT_SLOT(updateSelectionList()));
#else
		mAddressBook = KABC::StdAddressBook::self();
		if (mAddressBook)
			updateSelectionList();
#endif
	}
	else
		updateSelectionList();
        if (!mAddressBook)
                KMessageBox::error(this, i18n("Error reading address book"));
}

/******************************************************************************
* Close the address book.This is called at program termination.
*/
void BirthdayDlg::close()
{
	if (mAddressBook)
	{
		KABC::StdAddressBook::close();
		mAddressBook = 0;
	}
}

/******************************************************************************
* Initialise or update the birthday selection list by fetching all birthdays
* from the address book and displaying those which do not already have alarms.
*/
void BirthdayDlg::updateSelectionList()
{
	// Compile a list of all pending alarm messages which look like birthdays
	TQStringList messageList;
	KAEvent event;
	Event::List events = AlarmCalendar::activeCalendar()->events();
	for (Event::List::ConstIterator it = events.begin();  it != events.end();  ++it)
	{
		Event* kcalEvent = *it;
		event.set(*kcalEvent);
		if (event.action() == KAEvent::MESSAGE
		&&  event.recurType() == KARecurrence::ANNUAL_DATE
		&&  (mPrefixText.isEmpty()  ||  event.message().startsWith(mPrefixText)))
			messageList.append(event.message());
	}

	// Fetch all birthdays from the address book
	for (KABC::AddressBook::ConstIterator abit = mAddressBook->begin();  abit != mAddressBook->end();  ++abit)
	{
		const KABC::Addressee& addressee = *abit;
		if (addressee.birthday().isValid())
		{
			// Create a list entry for this birthday
			TQDate birthday = addressee.birthday().date();
			TQString name = addressee.nickName();
			if (name.isEmpty())
				name = addressee.realName();
			// Check if the birthday already has an alarm
			TQString text = mPrefixText + name + mSuffixText;
			bool alarmExists = (messageList.find(text) != messageList.end());
			// Check if the birthday is already in the selection list
			bool inSelectionList = false;
			AddresseeItem* item = 0;
			for (TQListViewItem* qitem = mAddresseeList->firstChild();  qitem;  qitem = qitem->nextSibling())
			{
				item = dynamic_cast<AddresseeItem*>(qitem);
				if (item  &&  item->text(AddresseeItem::NAME) == name  &&  item->birthday() == birthday)
				{
					inSelectionList = true;
					break;
				}
			}

			if (alarmExists  &&  inSelectionList)
				delete item;     // alarm exists, so remove from selection list
			else if (!alarmExists  &&  !inSelectionList)
				new AddresseeItem(mAddresseeList, name, birthday);   // add to list
		}
	}
//	mAddresseeList->setUpdatesEnabled(true);

	// Enable/disable OK button according to whether anything is currently selected
	bool selection = false;
	for (TQListViewItem* item = mAddresseeList->firstChild();  item;  item = item->nextSibling())
		if (mAddresseeList->isSelected(item))
		{
			selection = true;
			break;
		}
	enableButtonOK(selection);
}

/******************************************************************************
* Return a list of events for birthdays chosen.
*/
TQValueList<KAEvent> BirthdayDlg::events() const
{
	TQValueList<KAEvent> list;
	TQDate today = TQDate::tqcurrentDate();
	TQDateTime todayNoon(today, TQTime(12, 0, 0));
	int thisYear = today.year();
	int reminder = mReminder->minutes();

	for (TQListViewItem* item = mAddresseeList->firstChild();  item;  item = item->nextSibling())
	{
		if (mAddresseeList->isSelected(item))
		{
			AddresseeItem* aItem = dynamic_cast<AddresseeItem*>(item);
			if (aItem)
			{
				TQDate date = aItem->birthday();
				date.setYMD(thisYear, date.month(), date.day());
				if (date <= today)
					date.setYMD(thisYear + 1, date.month(), date.day());
				KAEvent event(date,
				              mPrefix->text() + aItem->text(AddresseeItem::NAME) + mSuffix->text(),
				              mFontColourButton->bgColour(), mFontColourButton->fgColour(),
				              mFontColourButton->font(), KAEvent::MESSAGE, mLateCancel->minutes(),
				              mFlags);
				float fadeVolume;
				int   fadeSecs;
				float volume = mSoundPicker->volume(fadeVolume, fadeSecs);
				event.setAudioFile(mSoundPicker->file(), volume, fadeVolume, fadeSecs);
				TQValueList<int> months;
				months.append(date.month());
				event.setRecurAnnualByDate(1, months, 0, Preferences::defaultFeb29Type(), -1, TQDate());
				event.setRepetition(mSubRepetition->interval(), mSubRepetition->count());
				event.setNextOccurrence(todayNoon);
				if (reminder)
					event.setReminder(reminder, false);
				if (mSpecialActionsButton)
					event.setActions(mSpecialActionsButton->preAction(),
					                 mSpecialActionsButton->postAction());
				list.append(event);
			}
		}
	}
	return list;
}

/******************************************************************************
* Called when the OK button is selected to import the selected birthdays.
*/
void BirthdayDlg::slotOk()
{
	// Save prefix and suffix texts to use as future defaults
	KConfig* config = kapp->config();
	config->setGroup(TQString::tqfromLatin1("General"));
	config->writeEntry(TQString::tqfromLatin1("BirthdayPrefix"), mPrefix->text());
	config->writeEntry(TQString::tqfromLatin1("BirthdaySuffix"), mSuffix->text());
	config->sync();

	mFlags = (mSoundPicker->sound() == SoundPicker::BEEP ? KAEvent::BEEP : 0)
	       | (mSoundPicker->repeat()                     ? KAEvent::REPEAT_SOUND : 0)
	       | (mConfirmAck->isChecked()                   ? KAEvent::CONFIRM_ACK : 0)
	       | (mFontColourButton->defaultFont()           ? KAEvent::DEFAULT_FONT : 0)
	       |                                               KAEvent::ANY_TIME;
	KDialogBase::slotOk();
}

/******************************************************************************
* Called when the group of items selected changes.
* Enable/disable the OK button depending on whether anything is selected.
*/
void BirthdayDlg::slotSelectionChanged()
{
	for (TQListViewItem* item = mAddresseeList->firstChild();  item;  item = item->nextSibling())
		if (mAddresseeList->isSelected(item))
		{
			enableButtonOK(true);
			return;
		}
	enableButtonOK(false);

}

/******************************************************************************
* Called when the prefix or suffix text has lost keyboard focus.
* If the text has changed, re-evaluates the selection list according to the new
* birthday alarm text format.
*/
void BirthdayDlg::slotTextLostFocus()
{
	TQString prefix = mPrefix->text();
	TQString suffix = mSuffix->text();
	if (prefix != mPrefixText  ||  suffix != mSuffixText)
	{
		// Text has changed - re-evaluate the selection list
		mPrefixText = prefix;
		mSuffixText = suffix;
		loadAddressBook();
	}
}


/*=============================================================================
= Class: AddresseeItem
=============================================================================*/

AddresseeItem::AddresseeItem(TQListView* parent, const TQString& name, const TQDate& birthday)
	: TQListViewItem(parent),
	  mBirthday(birthday)
{
	setText(NAME, name);
	setText(BIRTHDAY, KGlobal::locale()->formatDate(mBirthday, true));
	mBirthdayOrder.sprintf("%04d%03d", mBirthday.year(), mBirthday.dayOfYear());
}

TQString AddresseeItem::key(int column, bool) const
{
	if (column == BIRTHDAY)
		return mBirthdayOrder;
	return text(column).lower();
}


/*=============================================================================
= Class: BListView
=============================================================================*/

BListView::BListView(TQWidget* parent, const char* name)
	: KListView(parent, name)
{
	KAccel* accel = new KAccel(this);
	accel->insert(KStdAccel::SelectAll, TQT_TQOBJECT(this), TQT_SLOT(slotSelectAll()));
	accel->insert(KStdAccel::Deselect, TQT_TQOBJECT(this), TQT_SLOT(slotDeselect()));
	accel->readSettings();
}