summaryrefslogtreecommitdiffstats
path: root/kalarm/functions.cpp
blob: 2c44e161fbebaa33bdf4d16e4fa27fa8d73b81aa (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
/*
 *  functions.cpp  -  miscellaneous functions
 *  Program:  kalarm
 *  Copyright © 2001-2009 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 "functions.h"

#include "alarmcalendar.h"
#include "alarmevent.h"
#include "alarmlistview.h"
#include "daemon.h"
#include "kalarmapp.h"
#include "kamail.h"
#include "mainwindow.h"
#include "messagewin.h"
#include "preferences.h"
#include "shellprocess.h"
#include "templatelistview.h"
#include "templatemenuaction.h"

#include <tqdeepcopy.h>
#include <tqdir.h>
#include <tqregexp.h>

#include <kconfig.h>
#include <kaction.h>
#include <kglobal.h>
#include <klocale.h>
#include <kstdguiitem.h>
#include <kstdaccel.h>
#include <kmessagebox.h>
#include <kfiledialog.h>
#include <dcopclient.h>
#include <dcopref.h>
#include <kdcopservicestarter.h>
#include <kdebug.h>

#include <libkcal/event.h>
#include <libkcal/icalformat.h>
#include <libkpimidentities/identitymanager.h>
#include <libkpimidentities/identity.h>
#include <libkcal/person.h>


namespace
{
bool        resetDaemonQueued = false;
TQCString    korganizerName = "korganizer";
TQString     korgStartError;
#define     KORG_DCOP_OBJECT    "KOrganizerIface"
const char* KORG_DCOP_WINDOW  = "KOrganizer MainWindow";
const char* KMAIL_DCOP_WINDOW = "kmail-mainwindow#1";

bool sendToKOrganizer(const KAEvent&);
bool deleteFromKOrganizer(const TQString& eventID);
bool runKOrganizer();
}


namespace KAlarm
{

/******************************************************************************
*  Display a main window with the specified event selected.
*/
MainWindow* displayMainWindowSelected(const TQString& eventID)
{
	MainWindow* win = MainWindow::firstWindow();
	if (!win)
	{
		if (theApp()->checkCalendarDaemon())    // ensure calendar is open and daemon started
		{
			win = MainWindow::create();
			win->show();
		}
	}
	else
	{
		// There is already a main window, so make it the active window
		bool visible = win->isVisible();
		if (visible)
			win->hide();        // in case it's on a different desktop
		if (!visible  ||  win->isMinimized())
			win->showNormal();
		win->raise();
		win->setActiveWindow();
	}
	if (win  &&  !eventID.isEmpty())
		win->selectEvent(eventID);
	return win;
}

/******************************************************************************
* Create a New Alarm KAction.
*/
KAction* createNewAlarmAction(const TQString& label, TQObject* receiver, const char* slot, KActionCollection* actions, const char* name)
{
	return new KAction(label, "filenew", KStdAccel::openNew(), receiver, slot, actions, name);
}

/******************************************************************************
* Create a New From Template KAction.
*/
TemplateMenuAction* createNewFromTemplateAction(const TQString& label, TQObject* receiver, const char* slot, KActionCollection* actions, const char* name)
{
	return new TemplateMenuAction(label, "new_from_template", receiver, slot, actions, name);
}

/******************************************************************************
* Add a new active (non-expired) alarm.
* Save it in the calendar file and add it to every main window instance.
* If 'selectionView' is non-null, the selection highlight is moved to the new
* event in that listView instance.
* 'event' is updated with the actual event ID.
*/
UpdatetqStatus addEvent(KAEvent& event, AlarmListView* selectionView, TQWidget* errmsgParent, bool useEventID, bool allowKOrgUpdate)
{
	kdDebug(5950) << "KAlarm::addEvent(): " << event.id() << endl;
	UpdatetqStatus status = UPDATE_OK;
	if (!theApp()->checkCalendarDaemon())    // ensure calendar is open and daemon started
		return UPDATE_FAILED;
	else
	{
		// Save the event details in the calendar file, and get the new event ID
		AlarmCalendar* cal = AlarmCalendar::activeCalendar();
		if (!cal->addEvent(event, useEventID))
			status = UPDATE_FAILED;
		else if (!cal->save())
			status = SAVE_FAILED;
	}
	if (status == UPDATE_OK)
	{
		if (allowKOrgUpdate  &&  event.copyToKOrganizer())
		{
			if (!sendToKOrganizer(event))    // tell KOrganizer to show the event
				status = UPDATE_KORG_ERR;
		}

		// Update the window lists
		AlarmListView::addEvent(event, selectionView);
		return status;
	}

	if (errmsgParent)
		displayUpdateError(errmsgParent, status, ERR_ADD, 1);
	return status;
}

/******************************************************************************
* Save the event in the expired calendar file and adjust every main window instance.
* The event's ID is changed to an expired ID if necessary.
*/
bool addExpiredEvent(KAEvent& event)
{
	kdDebug(5950) << "KAlarm::addExpiredEvent(" << event.id() << ")\n";
	AlarmCalendar* cal = AlarmCalendar::expiredCalendarOpen();
	if (!cal)
		return false;
	bool archiving = (KAEvent::uidtqStatus(event.id()) == KAEvent::ACTIVE);
	if (archiving)
		event.setSaveDateTime(TQDateTime::tqcurrentDateTime());   // time stamp to control purging
	KCal::Event* kcalEvent = cal->addEvent(event);
	cal->save();

	// Update window lists
	if (!archiving)
		AlarmListView::addEvent(event, 0);
	else if (kcalEvent)
		AlarmListView::modifyEvent(KAEvent(*kcalEvent), 0);
	return true;
}

/******************************************************************************
* Add a new template.
* Save it in the calendar file and add it to every template list view.
* If 'selectionView' is non-null, the selection highlight is moved to the new
* event in that listView instance.
* 'event' is updated with the actual event ID.
*/
UpdatetqStatus addTemplate(KAEvent& event, TemplateListView* selectionView, TQWidget* errmsgParent)
{
	kdDebug(5950) << "KAlarm::addTemplate(): " << event.id() << endl;
	UpdatetqStatus status = UPDATE_OK;

	// Add the template to the calendar file
	AlarmCalendar* cal = AlarmCalendar::templateCalendarOpen();
	if (!cal  ||  !cal->addEvent(event))
		status = UPDATE_FAILED;
	else if (!cal->save())
		status = SAVE_FAILED;
	else
	{
		cal->emitEmptytqStatus();

		// Update the window lists
		TemplateListView::addEvent(event, selectionView);
		return UPDATE_OK;
	}

	if (errmsgParent)
		displayUpdateError(errmsgParent, status, ERR_TEMPLATE, 1);
	return status;
}

/******************************************************************************
* Modify an active (non-expired) alarm in the calendar file and in every main
* window instance.
* The new event will have a different event ID from the old one.
* If 'selectionView' is non-null, the selection highlight is moved to the
* modified event in that listView instance.
*/
UpdatetqStatus modifyEvent(KAEvent& oldEvent, const KAEvent& newEvent, AlarmListView* selectionView, TQWidget* errmsgParent)
{
	kdDebug(5950) << "KAlarm::modifyEvent(): '" << oldEvent.id() << endl;

	UpdatetqStatus status = UPDATE_OK;
	if (!newEvent.valid())
	{
		deleteEvent(oldEvent, true);
		status = UPDATE_FAILED;
	}
	else
	{
		if (oldEvent.copyToKOrganizer())
		{
			// Tell KOrganizer to delete its old event.
			// But ignore errors, because the user could have manually
			// deleted it since KAlarm asked KOrganizer to set it up.
			deleteFromKOrganizer(oldEvent.id());
		}

		// Update the event in the calendar file, and get the new event ID
		AlarmCalendar* cal = AlarmCalendar::activeCalendar();
		if (!cal->deleteEvent(oldEvent.id())
		||  !cal->addEvent(const_cast<KAEvent&>(newEvent), true))
			status = UPDATE_FAILED;
		else if (!cal->save())
			status = SAVE_FAILED;
		if (status == UPDATE_OK)
		{
			if (newEvent.copyToKOrganizer())
			{
				if (!sendToKOrganizer(newEvent))    // tell KOrganizer to show the new event
					status = UPDATE_KORG_ERR;
			}

			// Update the window lists
			AlarmListView::modifyEvent(oldEvent.id(), newEvent, selectionView);
			return status;
		}
	}

	if (errmsgParent)
		displayUpdateError(errmsgParent, status, ERR_ADD, 1);
	return status;
}

/******************************************************************************
* Update an active (non-expired) alarm from the calendar file and from every
* main window instance.
* The new event will have the same event ID as the old one.
* If 'selectionView' is non-null, the selection highlight is moved to the
* updated event in that listView instance.
* The event is not updated in KOrganizer, since this function is called when an
* existing alarm is rescheduled (due to recurrence or deferral).
*/
UpdatetqStatus updateEvent(KAEvent& event, AlarmListView* selectionView, TQWidget* errmsgParent, bool archiveOnDelete, bool incRevision)
{
	kdDebug(5950) << "KAlarm::updateEvent(): " << event.id() << endl;

	if (!event.valid())
		deleteEvent(event, archiveOnDelete);
	else
	{
		// Update the event in the calendar file.
		if (incRevision)
			event.incrementRevision();    // ensure alarm daemon sees the event has changed
		AlarmCalendar* cal = AlarmCalendar::activeCalendar();
		cal->updateEvent(event);
		if (!cal->save())
		{
			if (errmsgParent)
				displayUpdateError(errmsgParent, SAVE_FAILED, ERR_ADD, 1);
			return SAVE_FAILED;
		}

		// Update the window lists
		AlarmListView::modifyEvent(event, selectionView);
	}
	return UPDATE_OK;
}

/******************************************************************************
* Update a template in the calendar file and in every template list view.
* If 'selectionView' is non-null, the selection highlight is moved to the
* updated event in that listView instance.
*/
UpdatetqStatus updateTemplate(const KAEvent& event, TemplateListView* selectionView, TQWidget* errmsgParent)
{
	UpdatetqStatus status = UPDATE_OK;
	AlarmCalendar* cal = AlarmCalendar::templateCalendarOpen();
	if (!cal)
		status = UPDATE_FAILED;
	else
	{
		cal->updateEvent(event);
		if (!cal->save())
			status = SAVE_FAILED;
		else
		{
			TemplateListView::modifyEvent(event.id(), event, selectionView);
			return UPDATE_OK;
		}
	}

	if (errmsgParent)
		displayUpdateError(errmsgParent, SAVE_FAILED, ERR_TEMPLATE, 1);
	return status;
}

/******************************************************************************
* Delete an alarm from the calendar file and from every main window instance.
* If the event is archived, the event's ID is changed to an expired ID if necessary.
*/
UpdatetqStatus deleteEvent(KAEvent& event, bool archive, TQWidget* errmsgParent)
{
	TQString id = event.id();
	kdDebug(5950) << "KAlarm::deleteEvent(): " << id << endl;

	// Update the window lists
	AlarmListView::deleteEvent(id);

	UpdatetqStatus status = UPDATE_OK;
	AlarmCalendar* cal;

	// Delete the event from the calendar file
	if (KAEvent::uidtqStatus(id) == KAEvent::EXPIRED)
	{
		cal = AlarmCalendar::expiredCalendarOpen();
		if (!cal)
			status = UPDATE_FAILED;
	}
	else
	{
		if (event.copyToKOrganizer())
		{
			// The event was shown in KOrganizer, so tell KOrganizer to
			// delete it. Note that an error could occur if the user
			// manually deleted it from KOrganizer since it was set up.
			if (!deleteFromKOrganizer(event.id()))
				status = UPDATE_KORG_ERR;
		}
		if (archive  &&  event.toBeArchived())
			addExpiredEvent(event);     // this changes the event ID to an expired ID
		cal = AlarmCalendar::activeCalendar();
	}
	if (status != UPDATE_FAILED)
	{
		if (!cal->deleteEvent(id, true))   // save calendar after deleting
			status = SAVE_FAILED;
	}
	if (status > UPDATE_KORG_ERR  &&  errmsgParent)
		displayUpdateError(errmsgParent, SAVE_FAILED, ERR_DELETE, 1);
	return status;
}

/******************************************************************************
* Delete a template from the calendar file and from every template list view.
*/
UpdatetqStatus deleteTemplate(const KAEvent& event)
{
	TQString id = event.id();

	// Delete the template from the calendar file
	AlarmCalendar* cal = AlarmCalendar::templateCalendarOpen();
	if (!cal)
		return UPDATE_FAILED;
	if (!cal->deleteEvent(id, true))    // save calendar after deleting
		return SAVE_FAILED;
	cal->emitEmptytqStatus();

	// Update the window lists
	TemplateListView::deleteEvent(id);
	return UPDATE_OK;
}

/******************************************************************************
* Delete an alarm from the display calendar.
*/
void deleteDisplayEvent(const TQString& eventID)
{
	kdDebug(5950) << "KAlarm::deleteDisplayEvent(" << eventID << ")\n";

	if (KAEvent::uidtqStatus(eventID) == KAEvent::DISPLAYING)
	{
		AlarmCalendar* cal = AlarmCalendar::displayCalendarOpen();
		if (cal)
			cal->deleteEvent(eventID, true);   // save calendar after deleting
	}
}

/******************************************************************************
* Undelete an expired alarm, and update every main window instance.
* The archive bit is set to ensure that it gets re-archived if it is deleted again.
* If 'selectionView' is non-null, the selection highlight is moved to the
* restored event in that listView instance.
*/
UpdatetqStatus reactivateEvent(KAEvent& event, AlarmListView* selectionView, bool useEventID)
{
	TQString id = event.id();
	kdDebug(5950) << "KAlarm::reactivateEvent(): " << id << endl;

	// Delete the event from the expired calendar file
	if (KAEvent::uidtqStatus(id) == KAEvent::EXPIRED)
	{
		TQDateTime now = TQDateTime::tqcurrentDateTime();
		if (event.occursAfter(now, true))
		{
			if (event.recurs()  ||  event.repeatCount())
				event.setNextOccurrence(now);   // skip any recurrences in the past
			event.setArchive();    // ensure that it gets re-archived if it is deleted

			// Save the event details in the calendar file, and get the new event ID
			AlarmCalendar* cal = AlarmCalendar::activeCalendar();
			if (!cal->addEvent(event, useEventID))
				return UPDATE_FAILED;
			if (!cal->save())
				return SAVE_FAILED;

			UpdatetqStatus status = UPDATE_OK;
			if (event.copyToKOrganizer())
			{
				if (!sendToKOrganizer(event))    // tell KOrganizer to show the event
					status = UPDATE_KORG_ERR;
			}

			// Update the window lists
			AlarmListView::undeleteEvent(id, event, selectionView);

			cal = AlarmCalendar::expiredCalendarOpen();
			if (cal)
				cal->deleteEvent(id, true);   // save calendar after deleting
			return status;
		}
	}
	return UPDATE_FAILED;
}

/******************************************************************************
* Enable or disable an alarm in the calendar file and in every main window instance.
* The new event will have the same event ID as the old one.
* If 'selectionView' is non-null, the selection highlight is moved to the
* updated event in that listView instance.
*/
UpdatetqStatus enableEvent(KAEvent& event, AlarmListView* selectionView, bool enable)
{
	kdDebug(5950) << "KAlarm::enableEvent(" << enable << "): " << event.id() << endl;

	if (enable != event.enabled())
	{
		event.setEnabled(enable);

		// Update the event in the calendar file
		AlarmCalendar* cal = AlarmCalendar::activeCalendar();
		cal->updateEvent(event);
		if (!cal->save())
			return SAVE_FAILED;

		// If we're disabling a display alarm, close any message window
		if (!enable  &&  event.displayAction())
		{
			MessageWin* win = MessageWin::findEvent(event.id());
			delete win;
		}

		// Update the window lists
		AlarmListView::modifyEvent(event, selectionView);
	}
	return UPDATE_OK;
}

/******************************************************************************
* Display an error message about an error saving an event.
*/
void displayUpdateError(TQWidget* tqparent, UpdatetqStatus, UpdateError code, int nAlarms)
{
	TQString errmsg;
	switch (code)
	{
		case ERR_ADD:
			errmsg = (nAlarms > 1) ? i18n("Error saving alarms")
			                       : i18n("Error saving alarm");
			break;
		case ERR_DELETE:
			errmsg = (nAlarms > 1) ? i18n("Error deleting alarms")
			                       : i18n("Error deleting alarm");
			break;
		case ERR_REACTIVATE:
			errmsg = (nAlarms > 1) ? i18n("Error saving reactivated alarms")
			                       : i18n("Error saving reactivated alarm");
			break;
		case ERR_TEMPLATE:
			errmsg = i18n("Error saving alarm template");
			break;
	}
	KMessageBox::error(tqparent, errmsg);
}

/******************************************************************************
* Display an error message corresponding to a specified alarm update error code.
*/
void displayKOrgUpdateError(TQWidget* tqparent, KOrgUpdateError code, int nAlarms)
{
	TQString errmsg;
	switch (code)
	{
		case KORG_ERR_ADD:
			errmsg = (nAlarms > 1) ? i18n("Unable to show alarms in KOrganizer")
			                       : i18n("Unable to show alarm in KOrganizer");
			break;
		case KORG_ERR_MODIFY:
			errmsg = i18n("Unable to update alarm in KOrganizer");
			break;
		case KORG_ERR_DELETE:
			errmsg = (nAlarms > 1) ? i18n("Unable to delete alarms from KOrganizer")
			                       : i18n("Unable to delete alarm from KOrganizer");
			break;
	}
	KMessageBox::error(tqparent, errmsg);
}

/******************************************************************************
* Display the alarm edit dialogue to edit a specified alarm.
*/
bool edit(const TQString& eventID)
{
	AlarmCalendar* cal;
	switch (KAEvent::uidtqStatus(eventID))
	{
		case KAEvent::ACTIVE:
			cal = AlarmCalendar::activeCalendar();
			break;
		case KAEvent::TEMPLATE:
			cal = AlarmCalendar::templateCalendarOpen();
			break;
		default:
			kdError(5950) << "KAlarm::edit(" << eventID << "): event not active or template" << endl;
			return false;
	}
	KCal::Event* kcalEvent = cal->event(eventID);
	if (!kcalEvent)
	{
		kdError(5950) << "KAlarm::edit(): event ID not found: " << eventID << endl;
		return false;
	}
	KAEvent event(*kcalEvent);
	MainWindow::executeEdit(event);
	return true;
}

/******************************************************************************
* Display the alarm edit dialogue to edit a new alarm, optionally preset with
* a template.
*/
bool editNew(const TQString& templateName)
{
	bool result = true;
	if (!templateName.isEmpty())
	{
		AlarmCalendar* cal = AlarmCalendar::templateCalendarOpen();
		if (cal)
		{
			KAEvent templateEvent = KAEvent::findTemplateName(*cal, templateName);
			if (templateEvent.valid())
			{
				MainWindow::executeNew(templateEvent);
				return true;
			}
			kdWarning(5950) << "KAlarm::editNew(" << templateName << "): template not found" << endl;
		}
		result = false;
	}
	MainWindow::executeNew();
	return result;
}

/******************************************************************************
*  Returns a list of all alarm templates.
*  If shell commands are disabled, command alarm templates are omitted.
*/
TQValueList<KAEvent> templateList()
{
	TQValueList<KAEvent> templates;
	AlarmCalendar* cal = AlarmCalendar::templateCalendarOpen();
	if (cal)
	{
		bool includeCmdAlarms = ShellProcess::authorised();
		KCal::Event::List events = cal->events();
		for (KCal::Event::List::ConstIterator it = events.begin();  it != events.end();  ++it)
		{
			KCal::Event* kcalEvent = *it;
			KAEvent event(*kcalEvent);
			if (includeCmdAlarms  ||  event.action() != KAEvent::COMMAND)
				templates.append(event);
		}
	}
	return templates;
}

/******************************************************************************
* To be called after an alarm has been edited.
* Prompt the user to re-enable alarms if they are currently disabled, and if
* it's an email alarm, warn if no 'From' email address is configured.
*/
void outputAlarmWarnings(TQWidget* tqparent, const KAEvent* event)
{
	if (event  &&  event->action() == KAEvent::EMAIL
	&&  Preferences::emailAddress().isEmpty())
		KMessageBox::information(tqparent, i18n("Please set the 'From' email address...",
		                                      "%1\nPlease set it in the Preferences dialog.").tqarg(KAMail::i18n_NeedFromEmailAddress()));

	if (!Daemon::monitoringAlarms())
	{
		if (KMessageBox::warningYesNo(tqparent, i18n("Alarms are currently disabled.\nDo you want to enable alarms now?"),
		                              TQString(), i18n("Enable"), i18n("Keep Disabled"),
		                              TQString::tqfromLatin1("EditEnableAlarms"))
		                == KMessageBox::Yes)
			Daemon::setAlarmsEnabled();
	}
}

/******************************************************************************
* Reset the alarm daemon and reload the calendar.
* If the daemon is not already running, start it.
*/
void resetDaemon()
{
	kdDebug(5950) << "KAlarm::resetDaemon()" << endl;
	if (!resetDaemonQueued)
	{
		resetDaemonQueued = true;
		theApp()->processQueue();
	}
}

/******************************************************************************
* This method must only be called from the main KAlarm queue processing loop,
* to prevent asynchronous calendar operations interfering with one another.
*
* If resetDaemon() has been called, reset the alarm daemon and reload the calendars.
* If the daemon is not already running, start it.
*/
void resetDaemonIfQueued()
{
	if (resetDaemonQueued)
	{
		kdDebug(5950) << "KAlarm::resetDaemonIfNeeded()" << endl;
		AlarmCalendar::activeCalendar()->reload();
		AlarmCalendar::expiredCalendar()->reload();

		// Close any message windows for alarms which are now disabled
		KAEvent event;
		KCal::Event::List events = AlarmCalendar::activeCalendar()->events();
		for (KCal::Event::List::ConstIterator it = events.begin();  it != events.end();  ++it)
		{
			KCal::Event* kcalEvent = *it;
			event.set(*kcalEvent);
			if (!event.enabled()  &&  event.displayAction())
			{
				MessageWin* win = MessageWin::findEvent(event.id());
				delete win;
			}
		}

		MainWindow::refresh();
		if (!Daemon::reset())
			Daemon::start();
		resetDaemonQueued = false;
	}
}

/******************************************************************************
*  Start KMail if it isn't already running, and optionally iconise it.
*  Reply = reason for failure to run KMail (which may be the empty string)
*        = null string if success.
*/
TQString runKMail(bool minimise)
{
	TQCString dcopName;
	TQString errmsg;
	if (!runProgram("kmail", (minimise ? KMAIL_DCOP_WINDOW : ""), dcopName, errmsg))
		return i18n("Unable to start KMail\n(%1)").tqarg(errmsg);
	return TQString();
}

/******************************************************************************
*  Start another program for DCOP access if it isn't already running.
*  If 'windowName' is not empty, the program's window of that name is iconised.
*  On exit, 'dcopName' contains the DCOP name to access the application, and
*  'errorMessage' contains an error message if failure.
*  Reply = true if the program is now running.
*/
bool runProgram(const TQCString& program, const TQCString& windowName, TQCString& dcopName, TQString& errorMessage)
{
	if (!kapp->dcopClient()->isApplicationRegistered(program))
	{
		// KOrganizer is not already running, so start it
		if (KApplication::startServiceByDesktopName(TQString::tqfromLatin1(program), TQString(), &errorMessage, &dcopName))
		{
			kdError(5950) << "runProgram(): couldn't start " << program << " (" << errorMessage << ")\n";
			return false;
		}
		// Minimise its window - don't use hide() since this would remove all
		// trace of it from the panel if it is not configured to be docked in
		// the system tray.
		kapp->dcopClient()->send(dcopName, windowName, "minimize()", TQString());
	}
	else if (dcopName.isEmpty())
		dcopName = program;
	errorMessage = TQString();
	return true;
}

/******************************************************************************
*  Read the size for the specified window from the config file, for the
*  current screen resolution.
*  Reply = true if size set in the config file, in which case 'result' is set
*        = false if no size is set, in which case 'result' is unchanged.
*/
bool readConfigWindowSize(const char* window, TQSize& result)
{
	KConfig* config = KGlobal::config();
	config->setGroup(TQString::tqfromLatin1(window));
	TQWidget* desktop = TQT_TQWIDGET(KApplication::desktop());
	TQSize s = TQSize(config->readNumEntry(TQString::tqfromLatin1("Width %1").tqarg(desktop->width()), 0),
	                config->readNumEntry(TQString::tqfromLatin1("Height %1").tqarg(desktop->height()), 0));
	if (s.isEmpty())
		return false;
	result = s;
	return true;
}

/******************************************************************************
*  Write the size for the specified window to the config file, for the
*  current screen resolution.
*/
void writeConfigWindowSize(const char* window, const TQSize& size)
{
	KConfig* config = KGlobal::config();
	config->setGroup(TQString::tqfromLatin1(window));
	TQWidget* desktop = TQT_TQWIDGET(KApplication::desktop());
	config->writeEntry(TQString::tqfromLatin1("Width %1").tqarg(desktop->width()), size.width());
	config->writeEntry(TQString::tqfromLatin1("Height %1").tqarg(desktop->height()), size.height());
	config->sync();
}

/******************************************************************************
* Return the current KAlarm version number.
*/
int Version()
{
	static int version = 0;
	if (!version)
		version = getVersionNumber(KALARM_VERSION);
	return version;
}

/******************************************************************************
* Convert the supplied KAlarm version string to a version number.
* Reply = version number (double digit for each of major, minor & issue number,
*         e.g. 010203 for 1.2.3
*       = 0 if invalid version string.
*/
int getVersionNumber(const TQString& version, TQString* subVersion)
{
	// N.B. Remember to change  Version(int major, int minor, int rev)
	//      if the representation returned by this method changes.
	if (subVersion)
		*subVersion = TQString();
	int count = version.contains('.') + 1;
	if (count < 2)
		return 0;
	bool ok;
	unsigned vernum = version.section('.', 0, 0).toUInt(&ok) * 10000;  // major version
	if (!ok)
		return 0;
	unsigned v = version.section('.', 1, 1).toUInt(&ok);               // minor version
	if (!ok)
		return 0;
	vernum += (v < 99 ? v : 99) * 100;
	if (count >= 3)
	{
		// Issue number: allow other characters to follow the last digit
		TQString issue = version.section('.', 2);
		if (!issue.at(0).isDigit())
			return 0;
		int n = issue.length();
		int i;
		for (i = 0;  i < n && issue.at(i).isDigit();  ++i) ;
		if (subVersion)
			*subVersion = issue.mid(i);
		v = issue.left(i).toUInt();   // issue number
		vernum += (v < 99 ? v : 99);
	}
	return vernum;
}

/******************************************************************************
* Check from its mime type whether a file appears to be a text or image file.
* If a text file, its type is distinguished.
* Reply = file type.
*/
FileType fileType(const TQString& mimetype)
{
	static const char* applicationTypes[] = {
		"x-shellscript", "x-nawk", "x-awk", "x-perl", "x-python",
		"x-desktop", "x-troff", 0 };
	static const char* formattedTextTypes[] = {
		"html", "xml", 0 };

	if (mimetype.startsWith(TQString::tqfromLatin1("image/")))
		return Image;
	int slash = mimetype.find('/');
	if (slash < 0)
		return Unknown;
	TQString type = mimetype.mid(slash + 1);
	const char* typel = type.latin1();
	if (mimetype.startsWith(TQString::tqfromLatin1("application")))
	{
		for (int i = 0;  applicationTypes[i];  ++i)
			if (!strcmp(typel, applicationTypes[i]))
				return TextApplication;
	}
	else if (mimetype.startsWith(TQString::tqfromLatin1("text")))
	{
		for (int i = 0;  formattedTextTypes[i];  ++i)
			if (!strcmp(typel, formattedTextTypes[i]))
				return TextFormatted;
		return TextPlain;
	}
	return Unknown;
}

/******************************************************************************
* Display a modal dialogue to choose an existing file, initially highlighting
* any specified file.
* @param initialFile The file to initially highlight - must be a full path name or URL.
* @param defaultDir The directory to start in if @p initialFile is empty. If empty,
*                   the user's home directory will be used. Updated to the
*                   directory containing the selected file, if a file is chosen.
* @param mode OR of KFile::Mode values, e.g. ExistingOnly, LocalOnly.
* Reply = URL selected. If none is selected, URL.isEmpty() is true.
*/
TQString browseFile(const TQString& caption, TQString& defaultDir, const TQString& initialFile,
                   const TQString& filter, int mode, TQWidget* tqparent, const char* name)
{
	TQString initialDir = !initialFile.isEmpty() ? TQString(initialFile).remove(TQRegExp("/[^/]*$"))
	                   : !defaultDir.isEmpty()  ? defaultDir
	                   :                          TQDir::homeDirPath();
	KFileDialog fileDlg(initialDir, filter, tqparent, name, true);
	fileDlg.setOperationMode(mode & KFile::ExistingOnly ? KFileDialog::Opening : KFileDialog::Saving);
	fileDlg.setMode(KFile::File | mode);
	fileDlg.setCaption(caption);
	if (!initialFile.isEmpty())
		fileDlg.setSelection(initialFile);
	if (fileDlg.exec() != TQDialog::Accepted)
		return TQString();
	KURL url = fileDlg.selectedURL();
	defaultDir = url.path();
	return (mode & KFile::LocalOnly) ? url.path() : url.prettyURL();
}

/******************************************************************************
*  Return the first day of the week for the user's locale.
*  Reply = 1 (Mon) .. 7 (Sun).
*/
int localeFirstDayOfWeek()
{
	static int firstDay = 0;
	if (!firstDay)
		firstDay = KGlobal::locale()->weekStartDay();
	return firstDay;
}

/******************************************************************************
*  Return the supplied string with any accelerator code stripped out.
*/
TQString stripAccel(const TQString& text)
{
	unsigned len = text.length();
	TQString out = TQDeepCopy<TQString>(text);
	TQChar *corig = (TQChar*)out.tqunicode();
	TQChar *cout  = corig;
	TQChar *cin   = cout;
	while (len)
	{
		if ( *cin == '&' )
		{
			++cin;
			--len;
			if ( !len )
				break;
		}
		*cout = *cin;
		++cout;
		++cin;
		--len;
	}
	unsigned newlen = cout - corig;
	if (newlen != out.length())
		out.truncate(newlen);
	return out;
}

} // namespace KAlarm


namespace {

/******************************************************************************
*  Tell KOrganizer to put an alarm in its calendar.
*  It will be held by KOrganizer as a simple event, without alarms - KAlarm
*  is still responsible for alarming.
*/
bool sendToKOrganizer(const KAEvent& event)
{
	KCal::Event* kcalEvent = event.event();
	TQString uid = KAEvent::uid(event.id(), KAEvent::KORGANIZER);
	kcalEvent->setUid(uid);
	kcalEvent->clearAlarms();
	TQString userEmail;
	switch (event.action())
	{
		case KAEvent::MESSAGE:
		case KAEvent::FILE:
		case KAEvent::COMMAND:
			kcalEvent->setSummary(event.cleanText());
			userEmail = Preferences::emailAddress();
			break;
		case KAEvent::EMAIL:
		{
			TQString from = event.emailFromId()
			             ? KAMail::identityManager()->identityForUoid(event.emailFromId()).fullEmailAddr()
			             : Preferences::emailAddress();
			AlarmText atext;
			atext.setEmail(event.emailAddresses(", "), from, TQString(), TQString(), event.emailSubject(), TQString());
			kcalEvent->setSummary(atext.displayText());
			userEmail = from;
			break;
		}
	}
	kcalEvent->setOrganizer(KCal::Person(TQString(), userEmail));

	// Translate the event into string format
	KCal::ICalFormat format;
	format.setTimeZone(TQString(), false);
	TQString iCal = format.toICalString(kcalEvent);
kdDebug(5950)<<"Korg->"<<iCal<<endl;
	delete kcalEvent;

	// Send the event to KOrganizer
	if (!runKOrganizer())     // start KOrganizer if it isn't already running
		return false;
	TQByteArray  data, replyData;
	TQCString    replyType;
	TQDataStream arg(data, IO_WriteOnly);
	arg << iCal;
	if (kapp->dcopClient()->call(korganizerName, KORG_DCOP_OBJECT, "addIncidence(TQString)", data, replyType, replyData)
	&&  replyType == "bool")
	{
		bool result;
		TQDataStream reply(replyData, IO_ReadOnly);
		reply >> result;
		if (result)
		{
			kdDebug(5950) << "sendToKOrganizer(" << uid << "): success\n";
			return true;
		}
	}
	kdError(5950) << "sendToKOrganizer(): KOrganizer addEvent(" << uid << ") dcop call failed\n";
	return false;
}

/******************************************************************************
*  Tell KOrganizer to delete an event from its calendar.
*/
bool deleteFromKOrganizer(const TQString& eventID)
{
	if (!runKOrganizer())     // start KOrganizer if it isn't already running
		return false;
	TQString newID = KAEvent::uid(eventID, KAEvent::KORGANIZER);
	TQByteArray  data, replyData;
	TQCString    replyType;
	TQDataStream arg(data, IO_WriteOnly);
	arg << newID << true;
	if (kapp->dcopClient()->call(korganizerName, KORG_DCOP_OBJECT, "deleteIncidence(TQString,bool)", data, replyType, replyData)
	&&  replyType == "bool")
	{
		bool result;
		TQDataStream reply(replyData, IO_ReadOnly);
		reply >> result;
		if (result)
		{
			kdDebug(5950) << "deleteFromKOrganizer(" << newID << "): success\n";
			return true;
		}
	}
	kdError(5950) << "sendToKOrganizer(): KOrganizer deleteEvent(" << newID << ") dcop call failed\n";
	return false;
}

/******************************************************************************
* Start KOrganizer if not already running, and create its DCOP interface.
*/
bool runKOrganizer()
{
	TQString error;
	TQCString dcopService;
	int result = KDCOPServiceStarter::self()->findServiceFor("DCOP/Organizer", TQString(), TQString(), &error, &dcopService);
	if (result)
	{
		kdDebug(5950) << "Unable to start DCOP/Organizer: " << dcopService << " " << error << endl;
		return false;
	}
	// If Kontact is running, there is be a load() method which needs to be called
	// to load KOrganizer into Kontact. But if KOrganizer is running independently,
	// the load() method doesn't exist.
	TQCString dummy;
	if (!kapp->dcopClient()->findObject(dcopService, KORG_DCOP_OBJECT, "", TQByteArray(), dummy, dummy))
	{
		DCOPRef ref(dcopService, dcopService); // talk to the KUniqueApplication or its Kontact wrapper
		DCOPReply reply = ref.call("load()");
		if (!reply.isValid() || !(bool)reply)
		{
			kdWarning(5950) << "Error loading " << dcopService << endl;
			return false;
		}
		if (!kapp->dcopClient()->findObject(dcopService, KORG_DCOP_OBJECT, "", TQByteArray(), dummy, dummy))
		{
			kdWarning(5950) << "Unable to access KOrganizer's "KORG_DCOP_OBJECT" DCOP object" << endl;
			return false;
		}
	}
	return true;
}

} // namespace

#ifdef HAVE_XTEST
#include <X11/keysym.h>
#include <X11/extensions/XTest.h>
#include <tqwindowdefs.h>

/******************************************************************************
* Cancel the screen saver, in case it is active.
* Only implemented if the X11 XTest extension is installed.
*/
void x11_cancelScreenSaver()
{
	kdDebug(5950) << "KAlarm::cancelScreenSaver()" << endl;
	Display* display = qt_xdisplay();
	static int XTestKeyCode = 0;
	if (!XTestKeyCode)
		XTestKeyCode = XKeysymToKeycode(display, XK_Shift_L);
	XTestFakeKeyEvent(display, XTestKeyCode, true, CurrentTime);
	XTestFakeKeyEvent(display, XTestKeyCode, false, CurrentTime);
	XSync(display, false);
}
#endif // HAVE_XTEST