summaryrefslogtreecommitdiffstats
path: root/kalarm/mainwindow.cpp
blob: e9445d43acc04b1c30a3e6336ec9b9bb422b24dd (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
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
/*
 *  mainwindow.cpp  -  main application window
 *  Program:  kalarm
 *  Copyright © 2001-2007 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 <tqiconset.h>
#include <tqdragobject.h>
#include <tqheader.h>

#include <kmenubar.h>
#include <ktoolbar.h>
#include <kpopupmenu.h>
#include <kaccel.h>
#include <kaction.h>
#include <kactionclasses.h>
#include <kstdaction.h>
#include <kiconloader.h>
#include <kmessagebox.h>
#include <kurldrag.h>
#include <klocale.h>
#include <kglobalsettings.h>
#include <kconfig.h>
#include <kkeydialog.h>
#include <kedittoolbar.h>
#include <kaboutdata.h>
#include <dcopclient.h>
#include <kdebug.h>

#include <libtdepim/maillistdrag.h>
#include <libkmime/kmime_content.h>
#include <libkcal/calendarlocal.h>
#include <libkcal/icaldrag.h>

#include "alarmcalendar.h"
#include "alarmevent.h"
#include "alarmlistview.h"
#include "alarmtext.h"
#include "birthdaydlg.h"
#include "daemon.h"
#include "editdlg.h"
#include "functions.h"
#include "kalarmapp.h"
#include "kamail.h"
#include "prefdlg.h"
#include "preferences.h"
#include "synchtimer.h"
#include "templatepickdlg.h"
#include "templatedlg.h"
#include "traywindow.h"
#include "mainwindow.moc"

using namespace KCal;

static const char* UI_FILE     = "kalarmui.rc";
static const char* WINDOW_NAME = "MainWindow";

static const TQString VIEW_GROUP         = TQString::fromLatin1("View");
static const TQString SHOW_TIME_KEY      = TQString::fromLatin1("ShowAlarmTime");
static const TQString SHOW_TIME_TO_KEY   = TQString::fromLatin1("ShowTimeToAlarm");
static const TQString SHOW_ARCHIVED_KEY  = TQString::fromLatin1("ShowArchivedAlarms");
static const TQString SHOW_RESOURCES_KEY = TQString::fromLatin1("ShowResources");

static TQString   undoText;
static TQString   undoTextStripped;
static TQString   undoIcon;
static KShortcut undoShortcut;
static TQString   redoText;
static TQString   redoTextStripped;
static TQString   redoIcon;
static KShortcut redoShortcut;


/*=============================================================================
=  Class: MainWindow
=============================================================================*/

MainWindow::WindowList   MainWindow::mWindowList;
TemplateDlg*             MainWindow::mTemplateDlg = 0;

// Collect these widget labels together to ensure consistent wording and
// translations across different modules.
TQString MainWindow::i18n_a_ShowAlarmTimes()    { return i18n("Show &Alarm Times"); }
TQString MainWindow::i18n_m_ShowAlarmTime()     { return i18n("Show alarm ti&me"); }
TQString MainWindow::i18n_o_ShowTimeToAlarms()  { return i18n("Show Time t&o Alarms"); }
TQString MainWindow::i18n_l_ShowTimeToAlarm()   { return i18n("Show time unti&l alarm"); }
TQString MainWindow::i18n_ShowExpiredAlarms()   { return i18n("Show Expired Alarms"); }
TQString MainWindow::i18n_e_ShowExpiredAlarms() { return i18n("Show &Expired Alarms"); }
TQString MainWindow::i18n_HideExpiredAlarms()   { return i18n("Hide Expired Alarms"); }
TQString MainWindow::i18n_e_HideExpiredAlarms() { return i18n("Hide &Expired Alarms"); }


/******************************************************************************
* Construct an instance.
* To avoid resize() events occurring while still opening the calendar (and
* resultant crashes), the calendar is opened before constructing the instance.
*/
MainWindow* MainWindow::create(bool restored)
{
	theApp()->checkCalendarDaemon();    // ensure calendar is open and daemon started
	return new MainWindow(restored);
}

MainWindow::MainWindow(bool restored)
	: MainWindowBase(0, "MainWin", WGroupLeader | WStyle_ContextHelp | WDestructiveClose),
	  mMinuteTimerActive(false),
	  mHiddenTrayParent(false)
{
	kdDebug(5950) << "MainWindow::MainWindow()\n";
	setAutoSaveSettings(TQString::fromLatin1(WINDOW_NAME));    // save window sizes etc.
	setPlainCaption(kapp->aboutData()->programName());
	KConfig* config = KGlobal::config();
	config->setGroup(VIEW_GROUP);
	mShowExpired = config->readBoolEntry(SHOW_ARCHIVED_KEY, false);
	mShowTime    = config->readBoolEntry(SHOW_TIME_KEY, true);
	mShowTimeTo  = config->readBoolEntry(SHOW_TIME_TO_KEY, false);
	if (!restored)
	{
		TQSize s;
		if (KAlarm::readConfigWindowSize(WINDOW_NAME, s))
			resize(s);
	}
	config->setGroup(TQString::fromLatin1(WINDOW_NAME));
	TQValueList<int> order = config->readIntListEntry(TQString::fromLatin1("ColumnOrder"));

	setAcceptDrops(true);         // allow drag-and-drop onto this window
	if (!mShowTimeTo)
		mShowTime = true;     // ensure at least one time column is visible
	mListView = new AlarmListView(order, this, "listView");
	mListView->selectTimeColumns(mShowTime, mShowTimeTo);
	mListView->showExpired(mShowExpired);
	setCentralWidget(mListView);
	mListView->refresh();          // populate the alarm list
	mListView->clearSelection();

	connect(mListView, TQT_SIGNAL(itemDeleted()), TQT_SLOT(slotDeletion()));
	connect(mListView, TQT_SIGNAL(selectionChanged()), TQT_SLOT(slotSelection()));
	connect(mListView, TQT_SIGNAL(contextMenuRequested(TQListViewItem*, const TQPoint&, int)),
	        TQT_SLOT(slotContextMenuRequested(TQListViewItem*, const TQPoint&, int)));
	connect(mListView, TQT_SIGNAL(mouseButtonClicked(int, TQListViewItem*, const TQPoint&, int)),
	        TQT_SLOT(slotMouseClicked(int, TQListViewItem*, const TQPoint&, int)));
	connect(mListView, TQT_SIGNAL(executed(TQListViewItem*)), TQT_SLOT(slotDoubleClicked(TQListViewItem*)));
	connect(mListView->header(), TQT_SIGNAL(indexChange(int, int, int)), TQT_SLOT(columnsReordered()));
	initActions();

	mWindowList.append(this);
	if (mWindowList.count() == 1  &&  Daemon::isDcopHandlerReady())
	{
		// It's the first main window, and the DCOP handler is ready
		if (theApp()->wantRunInSystemTray())
			theApp()->displayTrayIcon(true, this);     // create system tray icon for run-in-system-tray mode
		else if (theApp()->trayWindow())
			theApp()->trayWindow()->setAssocMainWindow(this);    // associate this window with the system tray icon
	}
	setUpdateTimer();
}

MainWindow::~MainWindow()
{
	kdDebug(5950) << "MainWindow::~MainWindow()\n";
	mWindowList.remove(this);
	if (theApp()->trayWindow())
	{
		if (isTrayParent())
			delete theApp()->trayWindow();
		else
			theApp()->trayWindow()->removeWindow(this);
	}
	MinuteTimer::disconnect(TQT_TQOBJECT(this));
	mMinuteTimerActive = false;    // to ensure that setUpdateTimer() works correctly
	setUpdateTimer();
	MainWindow* main = mainMainWindow();
	if (main)
		KAlarm::writeConfigWindowSize(WINDOW_NAME, main->size());
	KToolBar* tb = toolBar();
	if (tb)
		tb->saveSettings(KGlobal::config(), "Toolbars");
	KGlobal::config()->sync();    // save any new window size to disc
	theApp()->quitIf();
}

/******************************************************************************
* Save settings to the session managed config file, for restoration
* when the program is restored.
*/
void MainWindow::saveProperties(KConfig* config)
{
	config->writeEntry(TQString::fromLatin1("HiddenTrayParent"), isTrayParent() && isHidden());
	config->writeEntry(TQString::fromLatin1("ShowExpired"), mShowExpired);
	config->writeEntry(TQString::fromLatin1("ShowTime"), mShowTime);
	config->writeEntry(TQString::fromLatin1("ShowTimeTo"), mShowTimeTo);
}

/******************************************************************************
* Read settings from the session managed config file.
* This function is automatically called whenever the app is being
* restored. Read in whatever was saved in saveProperties().
*/
void MainWindow::readProperties(KConfig* config)
{
	mHiddenTrayParent = config->readBoolEntry(TQString::fromLatin1("HiddenTrayParent"));
	mShowExpired      = config->readBoolEntry(TQString::fromLatin1("ShowExpired"));
	mShowTime         = config->readBoolEntry(TQString::fromLatin1("ShowTime"));
	mShowTimeTo       = config->readBoolEntry(TQString::fromLatin1("ShowTimeTo"));
}

/******************************************************************************
* Get the main main window, i.e. the parent of the system tray icon, or if
* none, the first main window to be created. Visible windows take precedence
* over hidden ones.
*/
MainWindow* MainWindow::mainMainWindow()
{
	MainWindow* tray = theApp()->trayWindow() ? theApp()->trayWindow()->assocMainWindow() : 0;
	if (tray  &&  tray->isVisible())
		return tray;
	for (WindowList::Iterator it = mWindowList.begin();  it != mWindowList.end();  ++it)
		if ((*it)->isVisible())
			return *it;
	if (tray)
		return tray;
	if (mWindowList.isEmpty())
		return 0;
	return mWindowList.first();
}

/******************************************************************************
* Check whether this main window is the parent of the system tray icon.
*/
bool MainWindow::isTrayParent() const
{
	return theApp()->wantRunInSystemTray()  &&  theApp()->trayMainWindow() == this;
}

/******************************************************************************
*  Close all main windows.
*/
void MainWindow::closeAll()
{
	while (!mWindowList.isEmpty())
		delete mWindowList.first();    // N.B. the destructor removes the window from the list
}

/******************************************************************************
*  Called when the window's size has changed (before it is painted).
*  Sets the last column in the list view to extend at least to the right hand
*  edge of the list view.
*  Records the new size in the config file.
*/
void MainWindow::resizeEvent(TQResizeEvent* re)
{
	// Save the window's new size only if it's the first main window
	if (mainMainWindow() == this)
		KAlarm::writeConfigWindowSize(WINDOW_NAME, re->size());
	MainWindowBase::resizeEvent(re);
}

/******************************************************************************
*  Called when the window is first displayed.
*  Sets the last column in the list view to extend at least to the right hand
*  edge of the list view.
*/
void MainWindow::showEvent(TQShowEvent* se)
{
	setUpdateTimer();
	slotUpdateTimeTo();
	MainWindowBase::showEvent(se);
}

/******************************************************************************
*  Display the window.
*/
void MainWindow::show()
{
	MainWindowBase::show();
	if (mMenuError)
	{
		// Show error message now that the main window has been displayed.
		// Waiting until now lets the user easily associate the message with
		// the main window which is faulty.
		KMessageBox::error(this, i18n("Failure to create menus\n(perhaps %1 missing or corrupted)").arg(TQString::fromLatin1(UI_FILE)));
		mMenuError = false;
	}
}

/******************************************************************************
*  Called after the window is hidden.
*/
void MainWindow::hideEvent(TQHideEvent* he)
{
	setUpdateTimer();
	MainWindowBase::hideEvent(he);
}

/******************************************************************************
*  Called when the list's column order is changed.
*  Save the new column order as the default the next time the program is run.
*/
void MainWindow::columnsReordered()
{
	KConfig* config = KGlobal::config();
	config->setGroup(TQString::fromLatin1(WINDOW_NAME));
	config->writeEntry(TQString::fromLatin1("ColumnOrder"), mListView->columnOrder());
	config->sync();
}

/******************************************************************************
*  Initialise the menu, toolbar and main window actions.
*/
void MainWindow::initActions()
{
	KActionCollection* actions = actionCollection();
	mActionTemplates       = new KAction(i18n("&Templates..."), 0, TQT_TQOBJECT(this), TQT_SLOT(slotTemplates()), actions, "templates");
	mActionNew             = KAlarm::createNewAlarmAction(i18n("&New..."), TQT_TQOBJECT(this), TQT_SLOT(slotNew()), actions, "new");
	mActionNewFromTemplate = KAlarm::createNewFromTemplateAction(i18n("New &From Template"), TQT_TQOBJECT(this), TQT_SLOT(slotNewFromTemplate(const KAEvent&)), actions, "newFromTempl");
	mActionCreateTemplate  = new KAction(i18n("Create Tem&plate..."), 0, TQT_TQOBJECT(this), TQT_SLOT(slotNewTemplate()), actions, "createTemplate");
	mActionCopy            = new KAction(i18n("&Copy..."), "editcopy", TQt::SHIFT+TQt::Key_Insert, TQT_TQOBJECT(this), TQT_SLOT(slotCopy()), actions, "copy");
	mActionModify          = new KAction(i18n("&Edit..."), "edit", TQt::CTRL+TQt::Key_E, TQT_TQOBJECT(this), TQT_SLOT(slotModify()), actions, "modify");
	mActionDelete          = new KAction(i18n("&Delete"), "editdelete", TQt::Key_Delete, TQT_TQOBJECT(this), TQT_SLOT(slotDelete()), actions, "delete");
	mActionReactivate      = new KAction(i18n("Reac&tivate"), 0, TQt::CTRL+TQt::Key_R, TQT_TQOBJECT(this), TQT_SLOT(slotReactivate()), actions, "undelete");
	mActionEnable          = new KAction(TQString(), 0, TQt::CTRL+TQt::Key_B, TQT_TQOBJECT(this), TQT_SLOT(slotEnable()), actions, "disable");
	mActionView            = new KAction(i18n("&View"), "viewmag", TQt::CTRL+TQt::Key_W, TQT_TQOBJECT(this), TQT_SLOT(slotView()), actions, "view");
	mActionShowTime        = new KToggleAction(i18n_a_ShowAlarmTimes(), TQt::CTRL+TQt::Key_M, TQT_TQOBJECT(this), TQT_SLOT(slotShowTime()), actions, "showAlarmTimes");
	mActionShowTime->setCheckedState(i18n("Hide &Alarm Times"));
	mActionShowTimeTo      = new KToggleAction(i18n_o_ShowTimeToAlarms(), TQt::CTRL+TQt::Key_I, TQT_TQOBJECT(this), TQT_SLOT(slotShowTimeTo()), actions, "showTimeToAlarms");
	mActionShowTimeTo->setCheckedState(i18n("Hide Time t&o Alarms"));
	mActionShowExpired     = new KToggleAction(i18n_e_ShowExpiredAlarms(), "history", TQt::CTRL+TQt::Key_P, TQT_TQOBJECT(this), TQT_SLOT(slotShowExpired()), actions, "showExpiredAlarms");
	mActionShowExpired->setCheckedState(i18n_e_HideExpiredAlarms());
	mActionToggleTrayIcon  = new KToggleAction(i18n("Show in System &Tray"), 0, TQT_TQOBJECT(this), TQT_SLOT(slotToggleTrayIcon()), actions, "showInSystemTray");
	mActionToggleTrayIcon->setCheckedState(i18n("Hide From System &Tray"));
	new KAction(i18n("Import &Alarms..."), 0, TQT_TQOBJECT(this), TQT_SLOT(slotImportAlarms()), actions, "importAlarms");
	new KAction(i18n("Import &Birthdays..."), 0, TQT_TQOBJECT(this), TQT_SLOT(slotBirthdays()), actions, "importBirthdays");
	new KAction(i18n("&Refresh Alarms"), "reload", 0, TQT_TQOBJECT(this), TQT_SLOT(slotResetDaemon()), actions, "refreshAlarms");
	Daemon::createAlarmEnableAction(actions, "alarmEnable");
	if (undoText.isNull())
	{
		// Get standard texts, etc., for Undo and Redo actions
		KAction* act = KStdAction::undo(TQT_TQOBJECT(this), 0, actions);
		undoIcon         = act->icon();
		undoShortcut     = act->shortcut();
		undoText         = act->text();
		undoTextStripped = KAlarm::stripAccel(undoText);
		delete act;
		act = KStdAction::redo(TQT_TQOBJECT(this), 0, actions);
		redoIcon         = act->icon();
		redoShortcut     = act->shortcut();
		redoText         = act->text();
		redoTextStripped = KAlarm::stripAccel(redoText);
		delete act;
	}
	mActionUndo = new KToolBarPopupAction(undoText, undoIcon, undoShortcut, TQT_TQOBJECT(this), TQT_SLOT(slotUndo()), actions, "edit_undo");
	mActionRedo = new KToolBarPopupAction(redoText, redoIcon, redoShortcut, TQT_TQOBJECT(this), TQT_SLOT(slotRedo()), actions, "edit_redo");
	KStdAction::find(TQT_TQOBJECT(mListView), TQT_SLOT(slotFind()), actions);
	mActionFindNext = KStdAction::findNext(TQT_TQOBJECT(mListView), TQT_SLOT(slotFindNext()), actions);
	mActionFindPrev = KStdAction::findPrev(TQT_TQOBJECT(mListView), TQT_SLOT(slotFindPrev()), actions);
	KStdAction::selectAll(TQT_TQOBJECT(mListView), TQT_SLOT(slotSelectAll()), actions);
	KStdAction::deselect(TQT_TQOBJECT(mListView), TQT_SLOT(slotDeselect()), actions);
	KStdAction::quit(TQT_TQOBJECT(this), TQT_SLOT(slotQuit()), actions);
	KStdAction::keyBindings(TQT_TQOBJECT(this), TQT_SLOT(slotConfigureKeys()), actions);
	KStdAction::configureToolbars(TQT_TQOBJECT(this), TQT_SLOT(slotConfigureToolbar()), actions);
	KStdAction::preferences(TQT_TQOBJECT(this), TQT_SLOT(slotPreferences()), actions);
	setStandardToolBarMenuEnabled(true);
	createGUI(UI_FILE);

	mContextMenu = static_cast<KPopupMenu*>(factory()->container("listContext", this));
	mActionsMenu = static_cast<KPopupMenu*>(factory()->container("actions", this));
	mMenuError = (!mContextMenu  ||  !mActionsMenu);
	connect(mActionsMenu, TQT_SIGNAL(aboutToShow()), TQT_SLOT(updateActionsMenu()));
	connect(mActionUndo->popupMenu(), TQT_SIGNAL(aboutToShow()), TQT_SLOT(slotInitUndoMenu()));
	connect(mActionUndo->popupMenu(), TQT_SIGNAL(activated(int)), TQT_SLOT(slotUndoItem(int)));
	connect(mActionRedo->popupMenu(), TQT_SIGNAL(aboutToShow()), TQT_SLOT(slotInitRedoMenu()));
	connect(mActionRedo->popupMenu(), TQT_SIGNAL(activated(int)), TQT_SLOT(slotRedoItem(int)));
	connect(Undo::instance(), TQT_SIGNAL(changed(const TQString&, const TQString&)), TQT_SLOT(slotUndoStatus(const TQString&, const TQString&)));
	connect(mListView, TQT_SIGNAL(findActive(bool)), TQT_SLOT(slotFindActive(bool)));
	Preferences::connect(TQT_SIGNAL(preferencesChanged()), TQT_TQOBJECT(this), TQT_SLOT(slotPrefsChanged()));
	connect(theApp(), TQT_SIGNAL(trayIconToggled()), TQT_SLOT(updateTrayIconAction()));

	// Set menu item states
	setEnableText(true);
	mActionShowTime->setChecked(mShowTime);
	mActionShowTimeTo->setChecked(mShowTimeTo);
	mActionShowExpired->setChecked(mShowExpired);
	slotPrefsChanged();         // set the correct text for this action
	mActionUndo->setEnabled(Undo::haveUndo());
	mActionRedo->setEnabled(Undo::haveRedo());
	mActionFindNext->setEnabled(false);
	mActionFindPrev->setEnabled(false);

	mActionCopy->setEnabled(false);
	mActionModify->setEnabled(false);
	mActionDelete->setEnabled(false);
	mActionReactivate->setEnabled(false);
	mActionView->setEnabled(false);
	mActionEnable->setEnabled(false);
	mActionCreateTemplate->setEnabled(false);

	KToolBar* tb = toolBar();
	if (tb)
		tb->applySettings(KGlobal::config(), "Toolbars");

	Undo::emitChanged();     // set the Undo/Redo menu texts
	Daemon::checkStatus();
	Daemon::monitoringAlarms();
}

/******************************************************************************
* Enable or disable the Templates menu item in every main window instance.
*/
void MainWindow::enableTemplateMenuItem(bool enable)
{
	for (WindowList::Iterator it = mWindowList.begin();  it != mWindowList.end();  ++it)
		(*it)->mActionTemplates->setEnabled(enable);
}

/******************************************************************************
* Refresh the alarm list in every main window instance.
*/
void MainWindow::refresh()
{
	kdDebug(5950) << "MainWindow::refresh()\n";
	for (WindowList::Iterator it = mWindowList.begin();  it != mWindowList.end();  ++it)
		(*it)->mListView->refresh();
}

/******************************************************************************
* Refresh the alarm list in every main window instance which is displaying
* expired alarms.
* Called when an expired alarm setting changes in the user preferences.
*/
void MainWindow::updateExpired()
{
	kdDebug(5950) << "MainWindow::updateExpired()\n";
	bool enableShowExpired = Preferences::expiredKeepDays();
	for (WindowList::Iterator it = mWindowList.begin();  it != mWindowList.end();  ++it)
	{
		MainWindow* w = *it;
		if (w->mShowExpired)
		{
			if (!enableShowExpired)
				w->slotShowExpired();
			else
				w->mListView->refresh();
		}
		w->mActionShowExpired->setEnabled(enableShowExpired);
	}
}

/******************************************************************************
* Start or stop the timer which updates the time-to-alarm values every minute.
* Should be called whenever a main window is created or destroyed, or shown or
* hidden.
*/
void MainWindow::setUpdateTimer()
{
	// Check whether any windows need to be updated
	MainWindow* needTimer = 0;
	MainWindow* timerWindow = 0;
	for (WindowList::Iterator it = mWindowList.begin();  it != mWindowList.end();  ++it)
	{
		MainWindow* w = *it;
		if (w->isVisible()  &&  w->mListView->showingTimeTo())
			needTimer = w;
		if (w->mMinuteTimerActive)
			timerWindow = w;
	}

	// Start or stop the update timer if necessary
	if (needTimer  &&  !timerWindow)
	{
		// Timeout every minute.
		needTimer->mMinuteTimerActive = true;
		MinuteTimer::connect(TQT_TQOBJECT(needTimer), TQT_SLOT(slotUpdateTimeTo()));
		kdDebug(5950) << "MainWindow::setUpdateTimer(): started timer" << endl;
	}
	else if (!needTimer  &&  timerWindow)
	{
		timerWindow->mMinuteTimerActive = false;
		MinuteTimer::disconnect(TQT_TQOBJECT(timerWindow));
		kdDebug(5950) << "MainWindow::setUpdateTimer(): stopped timer" << endl;
	}
}
/******************************************************************************
* Update the time-to-alarm values for each main window which is displaying them.
*/
void MainWindow::slotUpdateTimeTo()
{
	kdDebug(5950) << "MainWindow::slotUpdateTimeTo()" << endl;
	for (WindowList::Iterator it = mWindowList.begin();  it != mWindowList.end();  ++it)
	{
		MainWindow* w = *it;
		if (w->isVisible()  &&  w->mListView->showingTimeTo())
			w->mListView->updateTimeToAlarms();
	}
}

/******************************************************************************
* Select an alarm in the displayed list.
*/
void MainWindow::selectEvent(const TQString& eventID)
{
	mListView->clearSelection();
	AlarmListViewItem* item = mListView->getEntry(eventID);
	if (item)
	{
		mListView->setSelected(item, true);
		mListView->setCurrentItem(item);
		mListView->ensureItemVisible(item);
	}
}

/******************************************************************************
*  Called when the New button is clicked to edit a new alarm to add to the list.
*/
void MainWindow::slotNew()
{
	executeNew(this);
}

/******************************************************************************
*  Execute a New Alarm dialog, optionally either presetting it to the supplied
*  event, or setting the action and text.
*/
void MainWindow::executeNew(MainWindow* win, const KAEvent* evnt, KAEvent::Action action, const AlarmText& text)
{
	EditAlarmDlg editDlg(false, i18n("New Alarm"), win, 0, evnt);
	if (!text.isEmpty())
		editDlg.setAction(action, text);
	if (editDlg.exec() == TQDialog::Accepted)
	{
		KAEvent event;
		editDlg.getEvent(event);

		// Add the alarm to the displayed lists and to the calendar file
		if (KAlarm::addEvent(event, (win ? win->mListView : 0), &editDlg) == KAlarm::UPDATE_KORG_ERR)
			KAlarm::displayKOrgUpdateError(&editDlg, KAlarm::KORG_ERR_ADD, 1);
		Undo::saveAdd(event);

		KAlarm::outputAlarmWarnings(&editDlg, &event);
	}
}

/******************************************************************************
*  Called when a template is selected from the New From Template popup menu.
*  Executes a New Alarm dialog, preset from the selected template.
*/
void MainWindow::slotNewFromTemplate(const KAEvent& tmplate)
{
	executeNew(this, &tmplate);
}

/******************************************************************************
*  Called when the New Template button is clicked to create a new template
*  based on the currently selected alarm.
*/
void MainWindow::slotNewTemplate()
{
	AlarmListViewItem* item = mListView->selectedItem();
	if (item)
	{
		KAEvent event = item->event();
		TemplateDlg::createTemplate(&event, this);
	}
}

/******************************************************************************
*  Called when the Copy button is clicked to edit a copy of an existing alarm,
*  to add to the list.
*/
void MainWindow::slotCopy()
{
	AlarmListViewItem* item = mListView->selectedItem();
	if (item)
		executeNew(this, &item->event());
}

/******************************************************************************
*  Called when the Modify button is clicked to edit the currently highlighted
*  alarm in the list.
*/
void MainWindow::slotModify()
{
	AlarmListViewItem* item = mListView->selectedItem();
	if (item)
	{
		KAEvent event = item->event();
		executeEdit(event, this);
	}
}

/******************************************************************************
*  Open the Edit Alarm dialogue to edit the specified alarm.
*/
void MainWindow::executeEdit(KAEvent& event, MainWindow* win)
{
	EditAlarmDlg editDlg(false, i18n("Edit Alarm"), win, 0, &event);
	if (editDlg.exec() == TQDialog::Accepted)
	{
		KAEvent newEvent;
		bool changeDeferral = !editDlg.getEvent(newEvent);

		// Update the event in the displays and in the calendar file
		AlarmListView* view = win ? win->mListView : 0;
		if (changeDeferral)
		{
			// The only change has been to an existing deferral
			if (KAlarm::updateEvent(newEvent, view, &editDlg, true, false) != KAlarm::UPDATE_OK)   // keep the same event ID
				return;   // failed to save event
		}
		else
		{
			if (KAlarm::modifyEvent(event, newEvent, view, &editDlg) == KAlarm::UPDATE_KORG_ERR)
				KAlarm::displayKOrgUpdateError(&editDlg, KAlarm::KORG_ERR_MODIFY, 1);
		}
		Undo::saveEdit(event, newEvent);

		KAlarm::outputAlarmWarnings(&editDlg, &newEvent);
	}
}

/******************************************************************************
*  Called when the View button is clicked to view the currently highlighted
*  alarm in the list.
*/
void MainWindow::slotView()
{
	AlarmListViewItem* item = mListView->selectedItem();
	if (item)
	{
		KAEvent event = item->event();
		EditAlarmDlg editDlg(false, (event.expired() ? i18n("Expired Alarm") + " [" + i18n("read-only") + ']'
		                                             : i18n("View Alarm")),
		                     this, 0, &event, true);
		editDlg.exec();
	}
}

/******************************************************************************
*  Called when the Delete button is clicked to delete the currently highlighted
*  alarms in the list.
*/
void MainWindow::slotDelete()
{
	TQValueList<EventListViewItemBase*> items = mListView->selectedItems();
	// Copy the events to be deleted, in case any are deleted by being
	// triggered while the confirmation prompt is displayed.
	TQValueList<KAEvent> events;
	TQValueList<KAEvent> origEvents;
	for (TQValueList<EventListViewItemBase*>::Iterator iit = items.begin();  iit != items.end();  ++iit)
	{
		AlarmListViewItem* item = (AlarmListViewItem*)(*iit);
		events.append(item->event());
		origEvents.append(item->event());
	}
	if (Preferences::confirmAlarmDeletion())
	{
		int n = items.count();
		if (KMessageBox::warningContinueCancel(this, i18n("Do you really want to delete the selected alarm?",
		                                                  "Do you really want to delete the %n selected alarms?", n),
		                                       i18n("Delete Alarm", "Delete Alarms", n),
		                                       KGuiItem(i18n("&Delete"), "editdelete"),
		                                       Preferences::CONFIRM_ALARM_DELETION)
		    != KMessageBox::Continue)
			return;
	}

	int warnErr = 0;
	int warnKOrg = 0;
	AlarmCalendar::activeCalendar()->startUpdate();    // prevent multiple saves of the calendars until we're finished
	AlarmCalendar::expiredCalendar()->startUpdate();
	for (TQValueList<KAEvent>::Iterator it = events.begin();  it != events.end();  ++it)
	{
		// Delete the event from the calendar and displays
		switch (KAlarm::deleteEvent(*it))
		{
			case KAlarm::UPDATE_ERROR:
			case KAlarm::UPDATE_FAILED:
			case KAlarm::SAVE_FAILED:
				++warnErr;
				break;
			case KAlarm::UPDATE_KORG_ERR:
				++warnKOrg;
				break;
			default:
				break;
		}
	}
	if (!AlarmCalendar::activeCalendar()->endUpdate())      // save the calendars now
		warnErr = events.count();
	AlarmCalendar::expiredCalendar()->endUpdate();
	Undo::saveDeletes(origEvents);

	if (warnErr)
		KAlarm::displayUpdateError(this, KAlarm::UPDATE_FAILED, KAlarm::ERR_DELETE, warnErr);
	else if (warnKOrg)
		KAlarm::displayKOrgUpdateError(this, KAlarm::KORG_ERR_DELETE, warnKOrg);
}

/******************************************************************************
*  Called when the Reactivate button is clicked to reinstate the currently
*  highlighted expired alarms in the list.
*/
void MainWindow::slotReactivate()
{
	int warnErr = 0;
	int warnKOrg = 0;
	TQValueList<KAEvent> events;
	TQValueList<EventListViewItemBase*> items = mListView->selectedItems();
	mListView->clearSelection();
	AlarmCalendar::activeCalendar()->startUpdate();    // prevent multiple saves of the calendars until we're finished
	AlarmCalendar::expiredCalendar()->startUpdate();
	for (TQValueList<EventListViewItemBase*>::Iterator it = items.begin();  it != items.end();  ++it)
	{
		// Add the alarm to the displayed lists and to the calendar file
		AlarmListViewItem* item = (AlarmListViewItem*)(*it);
		KAEvent event = item->event();
		events.append(event);
		switch (KAlarm::reactivateEvent(event, mListView, true))
		{
			case KAlarm::UPDATE_ERROR:
			case KAlarm::UPDATE_FAILED:
			case KAlarm::SAVE_FAILED:
				++warnErr;
				break;
			case KAlarm::UPDATE_KORG_ERR:
				++warnKOrg;
				break;
			default:
				break;
		}
	}
	if (!AlarmCalendar::activeCalendar()->endUpdate())      // save the calendars now
		warnErr = items.count();
	AlarmCalendar::expiredCalendar()->endUpdate();
	Undo::saveReactivates(events);

	if (warnErr)
		KAlarm::displayUpdateError(this, KAlarm::UPDATE_FAILED, KAlarm::ERR_REACTIVATE, warnErr);
	else if (warnKOrg)
		KAlarm::displayKOrgUpdateError(this, KAlarm::KORG_ERR_ADD, warnKOrg);
}

/******************************************************************************
*  Called when the Enable/Disable button is clicked to enable or disable the
*  currently highlighted alarms in the list.
*/
void MainWindow::slotEnable()
{
	bool enable = mActionEnableEnable;    // save since changed in response to KAlarm::enableEvent()
	int warnErr = 0;
	TQValueList<EventListViewItemBase*> items = mListView->selectedItems();
	AlarmCalendar::activeCalendar()->startUpdate();    // prevent multiple saves of the calendars until we're finished
	for (TQValueList<EventListViewItemBase*>::Iterator it = items.begin();  it != items.end();  ++it)
	{
		AlarmListViewItem* item = (AlarmListViewItem*)(*it);
		KAEvent event = item->event();

		// Enable the alarm in the displayed lists and in the calendar file
		if (KAlarm::enableEvent(event, mListView, enable) != KAlarm::UPDATE_OK)
			++warnErr;
	}
	if (!AlarmCalendar::activeCalendar()->endUpdate())      // save the calendars now
		warnErr = items.count();
	if (warnErr)
		KAlarm::displayUpdateError(this, KAlarm::UPDATE_FAILED, KAlarm::ERR_ADD, warnErr);
}

/******************************************************************************
*  Called when the Show Alarm Times menu item is selected or deselected.
*/
void MainWindow::slotShowTime()
{
	mShowTime = !mShowTime;
	mActionShowTime->setChecked(mShowTime);
	if (!mShowTime  &&  !mShowTimeTo)
		slotShowTimeTo();    // at least one time column must be displayed
	else
	{
		mListView->selectTimeColumns(mShowTime, mShowTimeTo);
		KConfig* config = KGlobal::config();
		config->setGroup(VIEW_GROUP);
		config->writeEntry(SHOW_TIME_KEY, mShowTime);
		config->writeEntry(SHOW_TIME_TO_KEY, mShowTimeTo);
	}
}

/******************************************************************************
*  Called when the Show Time To Alarms menu item is selected or deselected.
*/
void MainWindow::slotShowTimeTo()
{
	mShowTimeTo = !mShowTimeTo;
	mActionShowTimeTo->setChecked(mShowTimeTo);
	if (!mShowTimeTo  &&  !mShowTime)
		slotShowTime();    // at least one time column must be displayed
	else
	{
		mListView->selectTimeColumns(mShowTime, mShowTimeTo);
		KConfig* config = KGlobal::config();
		config->setGroup(VIEW_GROUP);
		config->writeEntry(SHOW_TIME_KEY, mShowTime);
		config->writeEntry(SHOW_TIME_TO_KEY, mShowTimeTo);
	}
	setUpdateTimer();
}

/******************************************************************************
*  Called when the Show Expired Alarms menu item is selected or deselected.
*/
void MainWindow::slotShowExpired()
{
	mShowExpired = !mShowExpired;
	mActionShowExpired->setChecked(mShowExpired);
	mActionShowExpired->setToolTip(mShowExpired ? i18n_HideExpiredAlarms() : i18n_ShowExpiredAlarms());
	mListView->showExpired(mShowExpired);
	mListView->refresh();
	KConfig* config = KGlobal::config();
	config->setGroup(VIEW_GROUP);
	config->writeEntry(SHOW_ARCHIVED_KEY, mShowExpired);
}

/******************************************************************************
*  Called when the Import Alarms menu item is selected, to merge alarms from an
*  external calendar into the current calendars.
*/
void MainWindow::slotImportAlarms()
{
	if (AlarmCalendar::importAlarms(this))
		mListView->refresh();
}

/******************************************************************************
*  Called when the Import Birthdays menu item is selected, to display birthdays
*  from the address book for selection as alarms.
*/
void MainWindow::slotBirthdays()
{
	BirthdayDlg dlg(this);
	if (dlg.exec() == TQDialog::Accepted)
	{
		TQValueList<KAEvent> events = dlg.events();
		if (events.count())
		{
			mListView->clearSelection();
			int warnErr = 0;
			int warnKOrg = 0;
			for (TQValueList<KAEvent>::Iterator ev = events.begin();  ev != events.end();  ++ev)
			{
				// Add alarm to the displayed lists and to the calendar file
				switch (KAlarm::addEvent(*ev, mListView))
				{
					case KAlarm::UPDATE_ERROR:
					case KAlarm::UPDATE_FAILED:
					case KAlarm::SAVE_FAILED:
						++warnErr;
						break;
					case KAlarm::UPDATE_KORG_ERR:
						++warnKOrg;
						break;
					default:
						break;
				}
			}
			if (warnErr)
				KAlarm::displayUpdateError(this, KAlarm::UPDATE_FAILED, KAlarm::ERR_ADD, warnErr);
			else if (warnKOrg)
				KAlarm::displayKOrgUpdateError(this, KAlarm::KORG_ERR_ADD, warnKOrg);
			KAlarm::outputAlarmWarnings(&dlg);
		}
	}
}

/******************************************************************************
*  Called when the Templates menu item is selected, to display the alarm
*  template editing dialogue.
*/
void MainWindow::slotTemplates()
{
	if (!mTemplateDlg)
	{
		mTemplateDlg = TemplateDlg::create(this);
		enableTemplateMenuItem(false);     // disable menu item in all windows
		connect(mTemplateDlg, TQT_SIGNAL(finished()), TQT_SLOT(slotTemplatesEnd()));
		mTemplateDlg->show();
	}
}

/******************************************************************************
*  Called when the alarm template editing dialogue has exited.
*/
void MainWindow::slotTemplatesEnd()
{
	if (mTemplateDlg)
	{
		mTemplateDlg->delayedDestruct();   // this deletes the dialogue once it is safe to do so
		mTemplateDlg = 0;
		enableTemplateMenuItem(true);      // re-enable menu item in all windows
	}
}

/******************************************************************************
*  Called when the Display System Tray Icon menu item is selected.
*/
void MainWindow::slotToggleTrayIcon()
{
	theApp()->displayTrayIcon(!theApp()->trayIconDisplayed(), this);
}

/******************************************************************************
* Called when the user preferences have changed.
*/
void MainWindow::slotPrefsChanged()
{
	mActionShowExpired->setEnabled(Preferences::expiredKeepDays());
	updateTrayIconAction();
}

/******************************************************************************
* Called when the system tray icon is created or destroyed.
* Set the system tray icon menu text according to whether or not the system
* tray icon is currently visible.
*/
void MainWindow::updateTrayIconAction()
{
	mActionToggleTrayIcon->setEnabled(theApp()->haveSystemTray() && !theApp()->wantRunInSystemTray());
	mActionToggleTrayIcon->setChecked(theApp()->trayIconDisplayed());
}

/******************************************************************************
* Called when the Actions menu is about to be displayed.
* Update the status of the Alarms Enabled menu item.
*/
void MainWindow::updateActionsMenu()
{
	Daemon::checkStatus();   // update the Alarms Enabled item status
}

/******************************************************************************
*  Called when the active status of Find changes.
*/
void MainWindow::slotFindActive(bool active)
{
	mActionFindNext->setEnabled(active);
	mActionFindPrev->setEnabled(active);
}

/******************************************************************************
*  Called when the Undo action is selected.
*/
void MainWindow::slotUndo()
{
	Undo::undo(this, KAlarm::stripAccel(mActionUndo->text()));
}

/******************************************************************************
*  Called when the Redo action is selected.
*/
void MainWindow::slotRedo()
{
	Undo::redo(this, KAlarm::stripAccel(mActionRedo->text()));
}

/******************************************************************************
*  Called when an Undo item is selected.
*/
void MainWindow::slotUndoItem(int id)
{
	Undo::undo(id, this, Undo::actionText(Undo::UNDO, id));
}

/******************************************************************************
*  Called when a Redo item is selected.
*/
void MainWindow::slotRedoItem(int id)
{
	Undo::redo(id, this, Undo::actionText(Undo::REDO, id));
}

/******************************************************************************
*  Called when the Undo menu is about to show.
*  Populates the menu.
*/
void MainWindow::slotInitUndoMenu()
{
	initUndoMenu(mActionUndo->popupMenu(), Undo::UNDO);
}

/******************************************************************************
*  Called when the Redo menu is about to show.
*  Populates the menu.
*/
void MainWindow::slotInitRedoMenu()
{
	initUndoMenu(mActionRedo->popupMenu(), Undo::REDO);
}

/******************************************************************************
*  Populate the undo or redo menu.
*/
void MainWindow::initUndoMenu(KPopupMenu* menu, Undo::Type type)
{
	menu->clear();
	const TQString& action = (type == Undo::UNDO) ? undoTextStripped : redoTextStripped;
	TQValueList<int> ids = Undo::ids(type);
	for (TQValueList<int>::ConstIterator it = ids.begin();  it != ids.end();  ++it)
	{
		int id = *it;
		TQString actText = Undo::actionText(type, id);
		TQString descrip = Undo::description(type, id);
		TQString text = descrip.isEmpty()
		             ? i18n("Undo/Redo [action]", "%1 %2").arg(action).arg(actText)
		             : i18n("Undo [action]: message", "%1 %2: %3").arg(action).arg(actText).arg(descrip);
		menu->insertItem(text, id);
	}
}

/******************************************************************************
*  Called when the status of the Undo or Redo list changes.
*  Change the Undo or Redo text to include the action which would be undone/redone.
*/
void MainWindow::slotUndoStatus(const TQString& undo, const TQString& redo)
{
	if (undo.isNull())
	{
		mActionUndo->setEnabled(false);
		mActionUndo->setText(undoText);
	}
	else
	{
		mActionUndo->setEnabled(true);
		mActionUndo->setText(TQString("%1 %2").arg(undoText).arg(undo));
	}
	if (redo.isNull())
	{
		mActionRedo->setEnabled(false);
		mActionRedo->setText(redoText);
	}
	else
	{
		mActionRedo->setEnabled(true);
		mActionRedo->setText(TQString("%1 %2").arg(redoText).arg(redo));
	}
}

/******************************************************************************
*  Called when the Reset Daemon menu item is selected.
*/
void MainWindow::slotResetDaemon()
{
	KAlarm::resetDaemon();
}

/******************************************************************************
*  Called when the "Configure KAlarm" menu item is selected.
*/
void MainWindow::slotPreferences()
{
	KAlarmPrefDlg::display();
}

/******************************************************************************
*  Called when the Configure Keys menu item is selected.
*/
void MainWindow::slotConfigureKeys()
{
	KKeyDialog::configure(actionCollection(), this);
}

/******************************************************************************
*  Called when the Configure Toolbars menu item is selected.
*/
void MainWindow::slotConfigureToolbar()
{
	saveMainWindowSettings(KGlobal::config(), WINDOW_NAME);
	KEditToolbar dlg(factory());
	connect(&dlg, TQT_SIGNAL(newToolbarConfig()), TQT_TQOBJECT(this), TQT_SLOT(slotNewToolbarConfig()));
	dlg.exec();
}

/******************************************************************************
*  Called when OK or Apply is clicked in the Configure Toolbars dialog, to save
*  the new configuration.
*/
void MainWindow::slotNewToolbarConfig()
{
	createGUI(UI_FILE);
	applyMainWindowSettings(KGlobal::config(), WINDOW_NAME);
}

/******************************************************************************
*  Called when the Quit menu item is selected.
*/
void MainWindow::slotQuit()
{
	theApp()->doQuit(this);
}

/******************************************************************************
*  Called when the user or the session manager attempts to close the window.
*/
void MainWindow::closeEvent(TQCloseEvent* ce)
{
	if (!theApp()->sessionClosingDown()  &&  isTrayParent())
	{
		// The user (not the session manager) wants to close the window.
		// It's the parent window of the system tray icon, so just hide
		// it to prevent the system tray icon closing.
		hide();
		theApp()->quitIf();
		ce->ignore();
	}
	else
		ce->accept();
}

/******************************************************************************
*  Called when an item is deleted from the ListView.
*  Disables the actions if no item is still selected.
*/
void MainWindow::slotDeletion()
{
	if (!mListView->selectedCount())
	{
		kdDebug(5950) << "MainWindow::slotDeletion(true)\n";
		mActionCreateTemplate->setEnabled(false);
		mActionCopy->setEnabled(false);
		mActionModify->setEnabled(false);
		mActionView->setEnabled(false);
		mActionDelete->setEnabled(false);
		mActionReactivate->setEnabled(false);
		mActionEnable->setEnabled(false);
	}
}

/******************************************************************************
*  Called when the drag cursor enters the window.
*/
void MainWindow::dragEnterEvent(TQDragEnterEvent* e)
{
	executeDragEnterEvent(e);
}

/******************************************************************************
*  Called when the drag cursor enters a main or system tray window, to accept
*  or reject the dragged object.
*/
void MainWindow::executeDragEnterEvent(TQDragEnterEvent* e)
{
	if (KCal::ICalDrag::canDecode(e))
		e->accept(!AlarmListView::dragging());   // don't accept "text/calendar" objects from KAlarm
	else
		e->accept(TQTextDrag::canDecode(e)
		       || KURLDrag::canDecode(e)
		       || KPIM::MailListDrag::canDecode(e));
}

/******************************************************************************
*  Called when an object is dropped on the window.
*  If the object is recognised, the edit alarm dialog is opened appropriately.
*/
void MainWindow::dropEvent(TQDropEvent* e)
{
	executeDropEvent(this, e);
}

static TQString getMailHeader(const char* header, KMime::Content& content)
{
	KMime::Headers::Base* hd = content.getHeaderByType(header);
	return hd ? hd->asUnicodeString() : TQString();
}

/******************************************************************************
*  Called when an object is dropped on a main or system tray window, to
*  evaluate the action required and extract the text.
*/
void MainWindow::executeDropEvent(MainWindow* win, TQDropEvent* e)
{
	KAEvent::Action action = KAEvent::MESSAGE;
	TQString        text;
	TQByteArray     bytes;
	AlarmText      alarmText;
	KPIM::MailList mailList;
	KURL::List     files;
	KCal::CalendarLocal calendar(TQString::fromLatin1("UTC"));
	calendar.setLocalTime();    // default to local time (i.e. no time zone)
#ifndef NDEBUG
	TQCString fmts;
	for (int idbg = 0;  e->format(idbg);  ++idbg)
	{
		if (idbg) fmts += ", ";
		fmts += e->format(idbg);
	}
	kdDebug(5950) << "MainWindow::executeDropEvent(): " << fmts << endl;
#endif

	/* The order of the tests below matters, since some dropped objects
	 * provide more than one mime type.
	 * Don't change them without careful thought !!
	 */
	if (e->provides("message/rfc822")
	&&  !(bytes = e->encodedData("message/rfc822")).isEmpty())
	{
		// Email message(s). Ignore all but the first.
		kdDebug(5950) << "MainWindow::executeDropEvent(email)" << endl;
		TQCString mails(bytes.data(), bytes.size());
		KMime::Content content;
		content.setContent(mails);
		content.parse();
		TQString body;
		if (content.textContent())
			content.textContent()->decodedText(body, true, true);    // strip trailing newlines & spaces
		unsigned long sernum = 0;
		if (e->provides(KPIM::MailListDrag::format())
		&&  KPIM::MailListDrag::decode(e, mailList)
		&&  mailList.count())
		{
			// Get its KMail serial number to allow the KMail message
			// to be called up from the alarm message window.
			sernum = mailList.first().serialNumber();
		}
		alarmText.setEmail(getMailHeader("To", content),
		                   getMailHeader("From", content),
		                   getMailHeader("Cc", content),
		                   getMailHeader("Date", content),
		                   getMailHeader("Subject", content),
				   body, sernum);
	}
	else if (KURLDrag::decode(e, files)  &&  files.count())
	{
		kdDebug(5950) << "MainWindow::executeDropEvent(URL)" << endl;
		action = KAEvent::FILE;
		alarmText.setText(files.first().prettyURL());
	}
	else if (e->provides(KPIM::MailListDrag::format())
	&&       KPIM::MailListDrag::decode(e, mailList))
	{
		// KMail message(s). Ignore all but the first.
		kdDebug(5950) << "MainWindow::executeDropEvent(KMail_list)" << endl;
		if (!mailList.count())
			return;
		KPIM::MailSummary& summary = mailList.first();
		TQDateTime dt;
		dt.setTime_t(summary.date());
		TQString body = KAMail::getMailBody(summary.serialNumber());
		alarmText.setEmail(summary.to(), summary.from(), TQString(),
		                   KGlobal::locale()->formatDateTime(dt), summary.subject(),
		                   body, summary.serialNumber());
	}
	else if (KCal::ICalDrag::decode(e, &calendar))
	{
		// iCalendar - ignore all but the first event
		kdDebug(5950) << "MainWindow::executeDropEvent(iCalendar)" << endl;
		KCal::Event::List events = calendar.rawEvents();
		if (!events.isEmpty())
		{
			KAEvent ev(*events.first());
			executeNew(win, &ev);
		}
		return;
	}
	else if (TQTextDrag::decode(e, text))
	{
		kdDebug(5950) << "MainWindow::executeDropEvent(text)" << endl;
		alarmText.setText(text);
	}
	else
		return;

	if (!alarmText.isEmpty())
		executeNew(win, 0, action, alarmText);
}

/******************************************************************************
*  Called when the selected items in the ListView changes.
*  Selects the new current item, and enables the actions appropriately.
*/
void MainWindow::slotSelection()
{
	// Find which item has been selected, and whether more than one is selected
	TQValueList<EventListViewItemBase*> items = mListView->selectedItems();
	int count = items.count();
	AlarmListViewItem* item = (AlarmListViewItem*)((count == 1) ? items.first() : 0);
	bool enableReactivate = true;
	bool enableEnableDisable = true;
	bool enableEnable = false;
	bool enableDisable = false;
	TQDateTime now = TQDateTime::currentDateTime();
	for (TQValueList<EventListViewItemBase*>::Iterator it = items.begin();  it != items.end();  ++it)
	{
		const KAEvent& event = ((AlarmListViewItem*)(*it))->event();
		if (enableReactivate
		&&  (!event.expired()  ||  !event.occursAfter(now, true)))
			enableReactivate = false;
		if (enableEnableDisable)
		{
			if (event.expired())
				enableEnableDisable = enableEnable = enableDisable = false;
			else
			{
				if (!enableEnable  &&  !event.enabled())
					enableEnable = true;
				if (!enableDisable  &&  event.enabled())
					enableDisable = true;
			}
		}
	}

	kdDebug(5950) << "MainWindow::slotSelection(true)\n";
	mActionCreateTemplate->setEnabled(count == 1);
	mActionCopy->setEnabled(count == 1);
	mActionModify->setEnabled(item && !mListView->expired(item));
	mActionView->setEnabled(count == 1);
	mActionDelete->setEnabled(count);
	mActionReactivate->setEnabled(count && enableReactivate);
	mActionEnable->setEnabled(enableEnable || enableDisable);
	if (enableEnable || enableDisable)
		setEnableText(enableEnable);
}

/******************************************************************************
* Called when a context menu is requested either by a mouse click or by a
* key press.
*/
void MainWindow::slotContextMenuRequested(TQListViewItem* item, const TQPoint& pt, int)
{
	kdDebug(5950) << "MainWindow::slotContextMenuRequested()" << endl;
	if (mContextMenu)
		mContextMenu->popup(pt);
}

/******************************************************************************
* Called when the mouse is clicked on the ListView.
* Deselects the current item and disables the actions if appropriate.
* Note that if a right button click is handled by slotContextMenuRequested().
*/
void MainWindow::slotMouseClicked(int button, TQListViewItem* item, const TQPoint& pt, int)
{
	if (button != Qt::RightButton  &&  !item)
	{
		kdDebug(5950) << "MainWindow::slotMouseClicked(left)" << endl;
		mListView->clearSelection();
		mActionCreateTemplate->setEnabled(false);
		mActionCopy->setEnabled(false);
		mActionModify->setEnabled(false);
		mActionView->setEnabled(false);
		mActionDelete->setEnabled(false);
		mActionReactivate->setEnabled(false);
		mActionEnable->setEnabled(false);
	}
}

/******************************************************************************
*  Called when the mouse is double clicked on the ListView.
*  Displays the Edit Alarm dialog, for the clicked item if applicable.
*/
void MainWindow::slotDoubleClicked(TQListViewItem* item)
{
	kdDebug(5950) << "MainWindow::slotDoubleClicked()\n";
	if (item)
	{
		if (mListView->expired((AlarmListViewItem*)item))
			slotView();
		else
			slotModify();
	}
	else
		slotNew();
}

/******************************************************************************
*  Set the text of the Enable/Disable menu action.
*/
void MainWindow::setEnableText(bool enable)
{
	mActionEnableEnable = enable;
	mActionEnable->setText(enable ? i18n("Ena&ble") : i18n("Disa&ble"));
}

/******************************************************************************
*  Display or hide the specified main window.
*  This should only be called when the application doesn't run in the system tray.
*/
MainWindow* MainWindow::toggleWindow(MainWindow* win)
{
	if (win  &&  mWindowList.find(win) != mWindowList.end())
	{
		// A window is specified (and it exists)
		if (win->isVisible())
		{
			// The window is visible, so close it
			win->close();
			return 0;
		}
		else
		{
			// The window is hidden, so display it
			win->hide();        // in case it's on a different desktop
			win->showNormal();
			win->raise();
			win->setActiveWindow();
			return win;
		}
	}

	// No window is specified, or the window doesn't exist. Open a new one.
	win = create();
	win->show();
	return win;
}