• Skip to content
  • Skip to link menu
  • KDE API Reference
  • kdepimlibs-4.9.4 API Reference
  • KDE Home
  • Contact Us
 

KAlarm Library

  • kalarmcal
kaevent.cpp
1 /*
2  * kaevent.cpp - represents calendar events
3  * This file is part of kalarmcal library, which provides access to KAlarm
4  * calendar data.
5  * Copyright © 2001-2012 by David Jarvie <djarvie@kde.org>
6  *
7  * This library is free software; you can redistribute it and/or modify
8  * it under the terms of the GNU Library General Public License as published
9  * by the Free Software Foundation; either version 2 of the License, or (at
10  * your option) any later version.
11  *
12  * This library is distributed in the hope that it will be useful, but WITHOUT
13  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
14  * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public
15  * License for more details.
16  *
17  * You should have received a copy of the GNU Library General Public License
18  * along with this library; see the file COPYING.LIB. If not, write to the
19  * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
20  * MA 02110-1301, USA.
21  */
22 
23 #include "kaevent.h"
24 
25 #include "alarmtext.h"
26 #include "identities.h"
27 #include "version.h"
28 
29 #ifndef KALARMCAL_USE_KRESOURCES
30 #include <kcalcore/memorycalendar.h>
31 #else
32 #include <kcal/calendarlocal.h>
33 #endif
34 #include <kholidays/holidays.h>
35 using namespace KHolidays;
36 
37 #include <ksystemtimezone.h>
38 #include <klocale.h>
39 #ifdef KALARMCAL_USE_KRESOURCES
40 #include <kglobal.h>
41 #include <kconfiggroup.h>
42 #endif
43 #include <kdebug.h>
44 
45 #ifndef KALARMCAL_USE_KRESOURCES
46 using namespace KCalCore;
47 #else
48 using namespace KCal;
49 #endif
50 using namespace KHolidays;
51 
52 namespace KAlarmCal
53 {
54 
55 #ifndef KALARMCAL_USE_KRESOURCES
56 typedef KCalCore::Person EmailAddress;
57 class EmailAddressList : public KCalCore::Person::List
58 #else
59 typedef KCal::Person EmailAddress;
60 class EmailAddressList : public QList<KCal::Person>
61 #endif
62 {
63  public:
64 #ifndef KALARMCAL_USE_KRESOURCES
65  EmailAddressList() : KCalCore::Person::List() { }
66  EmailAddressList(const KCalCore::Person::List& list) { operator=(list); }
67  EmailAddressList& operator=(const KCalCore::Person::List&);
68 #else
69  EmailAddressList() : QList<KCal::Person>() { }
70  EmailAddressList(const QList<KCal::Person>& list) { operator=(list); }
71  EmailAddressList& operator=(const QList<KCal::Person>&);
72 #endif
73  operator QStringList() const;
74  QString join(const QString& separator) const;
75  QStringList pureAddresses() const;
76  QString pureAddresses(const QString& separator) const;
77  private:
78  QString address(int index) const;
79 };
80 
81 
82 class KAAlarm::Private
83 {
84  public:
85  Private();
86 
87  Action mActionType; // alarm action type
88  Type mType; // alarm type
89  DateTime mNextMainDateTime; // next time to display the alarm, excluding repetitions
90  Repetition mRepetition; // sub-repetition count and interval
91  int mNextRepeat; // repetition count of next due sub-repetition
92  bool mRepeatAtLogin; // whether to repeat the alarm at every login
93  bool mRecurs; // there is a recurrence rule for the alarm
94  bool mDeferred; // whether the alarm is an extra deferred/deferred-reminder alarm
95  bool mTimedDeferral; // if mDeferred = true: true if the deferral is timed, false if date-only
96 };
97 
98 
99 class KAEvent::Private : public QSharedData
100 {
101  public:
102  // Read-only internal flags additional to KAEvent::Flags enum values.
103  // NOTE: If any values are added to those in KAEvent::Flags, ensure
104  // that these values don't overlap them.
105  enum
106  {
107  REMINDER = 0x100000,
108  DEFERRAL = 0x200000,
109  TIMED_FLAG = 0x400000,
110  DATE_DEFERRAL = DEFERRAL,
111  TIME_DEFERRAL = DEFERRAL | TIMED_FLAG,
112  DISPLAYING_ = 0x800000,
113  READ_ONLY_FLAGS = 0xF00000
114  };
115  enum ReminderType // current active state of reminder
116  {
117  NO_REMINDER, // reminder is not due
118  ACTIVE_REMINDER, // reminder is due
119  HIDDEN_REMINDER // reminder-after is disabled due to main alarm being deferred past it
120  };
121  enum DeferType
122  {
123  NO_DEFERRAL = 0, // there is no deferred alarm
124  NORMAL_DEFERRAL, // the main alarm, a recurrence or a repeat is deferred
125  REMINDER_DEFERRAL // a reminder alarm is deferred
126  };
127  // Alarm types.
128  // This uses the same scheme as KAAlarm::Type, with some extra values.
129  // Note that the actual enum values need not be the same as in KAAlarm::Type.
130  enum AlarmType
131  {
132  INVALID_ALARM = 0, // Not an alarm
133  MAIN_ALARM = 1, // THE real alarm. Must be the first in the enumeration.
134  REMINDER_ALARM = 0x02, // Reminder in advance of/after the main alarm
135  DEFERRED_ALARM = 0x04, // Deferred alarm
136  DEFERRED_REMINDER_ALARM = REMINDER_ALARM | DEFERRED_ALARM, // Deferred reminder alarm
137  // The following values must be greater than the preceding ones, to
138  // ensure that in ordered processing they are processed afterwards.
139  AT_LOGIN_ALARM = 0x10, // Additional repeat-at-login trigger
140  DISPLAYING_ALARM = 0x20, // Copy of the alarm currently being displayed
141  // The following are extra internal KAEvent values
142  AUDIO_ALARM = 0x30, // sound to play when displaying the alarm
143  PRE_ACTION_ALARM = 0x40, // command to execute before displaying the alarm
144  POST_ACTION_ALARM = 0x50 // command to execute after the alarm window is closed
145  };
146 
147  struct AlarmData
148  {
149 #ifndef KALARMCAL_USE_KRESOURCES
150  Alarm::Ptr alarm;
151 #else
152  const Alarm* alarm;
153 #endif
154  QString cleanText; // text or audio file name
155  uint emailFromId;
156  QFont font;
157  QColor bgColour, fgColour;
158  float soundVolume;
159  float fadeVolume;
160  int fadeSeconds;
161  int repeatSoundPause;
162  int nextRepeat;
163  bool speak;
164  KAEvent::Private::AlarmType type;
165  KAAlarm::Action action;
166  int displayingFlags;
167  ExtraActionOptions extraActionOptions;
168  bool defaultFont;
169  bool isEmailText;
170  bool commandScript;
171  bool timedDeferral;
172  bool hiddenReminder;
173  };
174  typedef QMap<AlarmType, AlarmData> AlarmMap;
175 
176  Private();
177  Private(const KDateTime&, const QString& message, const QColor& bg, const QColor& fg,
178  const QFont& f, SubAction, int lateCancel, Flags flags, bool changesPending = false);
179 #ifndef KALARMCAL_USE_KRESOURCES
180  explicit Private(const KCalCore::Event::Ptr&);
181 #else
182  explicit Private(const KCal::Event*);
183 #endif
184  Private(const Private&);
185  ~Private() { delete mRecurrence; }
186  Private& operator=(const Private& e) { if (&e != this) copy(e); return *this; }
187 #ifndef KALARMCAL_USE_KRESOURCES
188  void set(const KCalCore::Event::Ptr&);
189 #else
190  void set(const KCal::Event*);
191 #endif
192  void set(const KDateTime&, const QString& message, const QColor& bg, const QColor& fg,
193  const QFont&, SubAction, int lateCancel, Flags flags, bool changesPending = false);
194  void setAudioFile(const QString& filename, float volume, float fadeVolume, int fadeSeconds, int repeatPause, bool allowEmptyFile);
195  OccurType setNextOccurrence(const KDateTime& preDateTime);
196  void setFirstRecurrence();
197  void setCategory(CalEvent::Type);
198  void setRepeatAtLogin(bool);
199  void setRepeatAtLoginTrue(bool clearReminder);
200  void setReminder(int minutes, bool onceOnly);
201  void activateReminderAfter(const DateTime& mainAlarmTime);
202  void defer(const DateTime&, bool reminder, bool adjustRecurrence = false);
203  void cancelDefer();
204 #ifndef KALARMCAL_USE_KRESOURCES
205  bool setDisplaying(const Private&, KAAlarm::Type, Akonadi::Collection::Id, const KDateTime& dt, bool showEdit, bool showDefer);
206  void reinstateFromDisplaying(const KCalCore::Event::Ptr&, Akonadi::Collection::Id&, bool& showEdit, bool& showDefer);
207 #else
208  bool setDisplaying(const Private&, KAAlarm::Type, const QString& resourceID, const KDateTime& dt, bool showEdit, bool showDefer);
209  void reinstateFromDisplaying(const KCal::Event*, QString& resourceID, bool& showEdit, bool& showDefer);
210  void setCommandError(const QString& configString);
211  void setCommandError(CmdErrType, bool writeConfig) const;
212 #endif
213  void startChanges() { ++mChangeCount; }
214  void endChanges();
215  void removeExpiredAlarm(KAAlarm::Type);
216  KAAlarm alarm(KAAlarm::Type) const;
217  KAAlarm firstAlarm() const;
218  KAAlarm nextAlarm(KAAlarm::Type) const;
219 #ifndef KALARMCAL_USE_KRESOURCES
220  bool updateKCalEvent(const KCalCore::Event::Ptr&, UidAction, bool setCustomProperties = true) const;
221 #else
222  bool updateKCalEvent(KCal::Event*, UidAction) const;
223 #endif
224  DateTime mainDateTime(bool withRepeats = false) const
225  { return (withRepeats && mNextRepeat && mRepetition)
226  ? mRepetition.duration(mNextRepeat).end(mNextMainDateTime.kDateTime()) : mNextMainDateTime; }
227  DateTime mainEndRepeatTime() const
228  { return mRepetition ? mRepetition.duration().end(mNextMainDateTime.kDateTime()) : mNextMainDateTime; }
229  DateTime deferralLimit(DeferLimitType* = 0) const;
230  Flags flags() const;
231  bool isWorkingTime(const KDateTime&) const;
232  bool setRepetition(const Repetition&);
233  bool occursAfter(const KDateTime& preDateTime, bool includeRepetitions) const;
234  OccurType nextOccurrence(const KDateTime& preDateTime, DateTime& result, OccurOption = IGNORE_REPETITION) const;
235  OccurType previousOccurrence(const KDateTime& afterDateTime, DateTime& result, bool includeRepetitions = false) const;
236  void setRecurrence(const KARecurrence&);
237 #ifndef KALARMCAL_USE_KRESOURCES
238  bool setRecur(KCalCore::RecurrenceRule::PeriodType, int freq, int count, const QDate& end, KARecurrence::Feb29Type = KARecurrence::Feb29_None);
239  bool setRecur(KCalCore::RecurrenceRule::PeriodType, int freq, int count, const KDateTime& end, KARecurrence::Feb29Type = KARecurrence::Feb29_None);
240 #else
241  bool setRecur(KCal::RecurrenceRule::PeriodType, int freq, int count, const QDate& end, KARecurrence::Feb29Type = KARecurrence::Feb29_None);
242  bool setRecur(KCal::RecurrenceRule::PeriodType, int freq, int count, const KDateTime& end, KARecurrence::Feb29Type = KARecurrence::Feb29_None);
243 #endif
244  KARecurrence::Type checkRecur() const;
245  void clearRecur();
246  void calcTriggerTimes() const;
247 #ifdef KDE_NO_DEBUG_OUTPUT
248  void dumpDebug() const { }
249 #else
250  void dumpDebug() const;
251 #endif
252 #ifndef KALARMCAL_USE_KRESOURCES
253  static bool convertRepetition(const KCalCore::Event::Ptr&);
254  static bool convertStartOfDay(const KCalCore::Event::Ptr&);
255  static DateTime readDateTime(const KCalCore::Event::Ptr&, bool dateOnly, DateTime& start);
256  static void readAlarms(const KCalCore::Event::Ptr&, void* alarmMap, bool cmdDisplay = false);
257  static void readAlarm(const KCalCore::Alarm::Ptr&, AlarmData&, bool audioMain, bool cmdDisplay = false);
258 #else
259  static bool convertRepetition(KCal::Event*);
260  static bool convertStartOfDay(KCal::Event*);
261  static DateTime readDateTime(const KCal::Event*, bool dateOnly, DateTime& start);
262  static void readAlarms(const KCal::Event*, void* alarmMap, bool cmdDisplay = false);
263  static void readAlarm(const KCal::Alarm*, AlarmData&, bool audioMain, bool cmdDisplay = false);
264 #endif
265 
266  private:
267  void copy(const Private&);
268  bool mayOccurDailyDuringWork(const KDateTime&) const;
269  int nextWorkRepetition(const KDateTime& pre) const;
270  void calcNextWorkingTime(const DateTime& nextTrigger) const;
271  DateTime nextWorkingTime() const;
272  OccurType nextRecurrence(const KDateTime& preDateTime, DateTime& result) const;
273 #ifndef KALARMCAL_USE_KRESOURCES
274  void setAudioAlarm(const KCalCore::Alarm::Ptr&) const;
275  KCalCore::Alarm::Ptr initKCalAlarm(const KCalCore::Event::Ptr&, const DateTime&, const QStringList& types, AlarmType = INVALID_ALARM) const;
276  KCalCore::Alarm::Ptr initKCalAlarm(const KCalCore::Event::Ptr&, int startOffsetSecs, const QStringList& types, AlarmType = INVALID_ALARM) const;
277 #else
278  void setAudioAlarm(KCal::Alarm*) const;
279  KCal::Alarm* initKCalAlarm(KCal::Event*, const DateTime&, const QStringList& types, AlarmType = INVALID_ALARM) const;
280  KCal::Alarm* initKCalAlarm(KCal::Event*, int startOffsetSecs, const QStringList& types, AlarmType = INVALID_ALARM) const;
281 #endif
282  inline void set_deferral(DeferType);
283  inline void activate_reminder(bool activate);
284 
285  public:
286 #ifdef KALARMCAL_USE_KRESOURCES
287  static QString mCmdErrConfigGroup; // config file group for command error recording
288 #endif
289  static QFont mDefaultFont; // default alarm message font
290  static const KHolidays::HolidayRegion* mHolidays; // holiday region to use
291  static QBitArray mWorkDays; // working days of the week
292  static QTime mWorkDayStart; // start time of the working day
293  static QTime mWorkDayEnd; // end time of the working day
294  static int mWorkTimeIndex; // incremented every time working days/times are changed
295 #ifdef KALARMCAL_USE_KRESOURCES
296  AlarmResource* mResource; // resource which owns the event (for convenience - not used by this class)
297 #endif
298  mutable DateTime mAllTrigger; // next trigger time, including reminders, ignoring working hours
299  mutable DateTime mMainTrigger; // next trigger time, ignoring reminders and working hours
300  mutable DateTime mAllWorkTrigger; // next trigger time, taking account of reminders and working hours
301  mutable DateTime mMainWorkTrigger; // next trigger time, ignoring reminders but taking account of working hours
302  mutable CmdErrType mCommandError; // command execution error last time the alarm triggered
303 
304  QString mEventID; // UID: KCal::Event unique ID
305  QString mTemplateName; // alarm template's name, or null if normal event
306 #ifndef KALARMCAL_USE_KRESOURCES
307  QMap<QByteArray, QString> mCustomProperties; // KCal::Event's non-KAlarm custom properties
308  Akonadi::Item::Id mItemId; // Akonadi::Item ID for this event
309  mutable Akonadi::Collection::Id mCollectionId; // ID of collection containing the event, or for a displaying event,
310  // saved collection ID (not the collection the event is in)
311 #else
312  QString mOriginalResourceId;// saved resource ID (not the resource the event is in)
313 #endif
314  QString mText; // message text, file URL, command, email body [or audio file for KAAlarm]
315  QString mAudioFile; // ATTACH: audio file to play
316  QString mPreAction; // command to execute before alarm is displayed
317  QString mPostAction; // command to execute after alarm window is closed
318  DateTime mStartDateTime; // DTSTART and DTEND: start and end time for event
319  KDateTime mCreatedDateTime; // CREATED: date event was created, or saved in archive calendar
320  DateTime mNextMainDateTime; // next time to display the alarm, excluding repetitions
321  KDateTime mAtLoginDateTime; // repeat-at-login end time
322  DateTime mDeferralTime; // extra time to trigger alarm (if alarm or reminder deferred)
323  DateTime mDisplayingTime; // date/time shown in the alarm currently being displayed
324  int mDisplayingFlags; // type of alarm which is currently being displayed
325  int mReminderMinutes; // how long in advance reminder is to be, or 0 if none (<0 for reminder AFTER the alarm)
326  DateTime mReminderAfterTime; // if mReminderActive true, time to trigger reminder AFTER the main alarm, or invalid if not pending
327  ReminderType mReminderActive; // whether a reminder is due (before next, or after last, main alarm/recurrence)
328  int mDeferDefaultMinutes; // default number of minutes for deferral dialog, or 0 to select time control
329  bool mDeferDefaultDateOnly;// select date-only by default in deferral dialog
330  int mRevision; // SEQUENCE: revision number of the original alarm, or 0
331  KARecurrence* mRecurrence; // RECUR: recurrence specification, or 0 if none
332  Repetition mRepetition; // sub-repetition count and interval
333  int mNextRepeat; // repetition count of next due sub-repetition
334  int mAlarmCount; // number of alarms: count of !mMainExpired, mRepeatAtLogin, mDeferral, mReminderActive, mDisplaying
335  DeferType mDeferral; // whether the alarm is an extra deferred/deferred-reminder alarm
336  unsigned long mKMailSerialNumber; // if email text, message's KMail serial number
337  int mTemplateAfterTime; // time not specified: use n minutes after default time, or -1 (applies to templates only)
338  QColor mBgColour; // background colour of alarm message
339  QColor mFgColour; // foreground colour of alarm message, or invalid for default
340  QFont mFont; // font of alarm message (ignored if mUseDefaultFont true)
341  uint mEmailFromIdentity; // standard email identity uoid for 'From' field, or empty
342  EmailAddressList mEmailAddresses; // ATTENDEE: addresses to send email to
343  QString mEmailSubject; // SUMMARY: subject line of email
344  QStringList mEmailAttachments; // ATTACH: email attachment file names
345  mutable int mChangeCount; // >0 = inhibit calling calcTriggerTimes()
346  mutable bool mTriggerChanged; // true if need to recalculate trigger times
347  QString mLogFile; // alarm output is to be logged to this URL
348  float mSoundVolume; // volume for sound file (range 0 - 1), or < 0 for unspecified
349  float mFadeVolume; // initial volume for sound file (range 0 - 1), or < 0 for no fade
350  int mFadeSeconds; // fade time (seconds) for sound file, or 0 if none
351  int mRepeatSoundPause; // seconds to pause between sound file repetitions, or -1 if no repetition
352  int mLateCancel; // how many minutes late will cancel the alarm, or 0 for no cancellation
353  mutable const KHolidays::HolidayRegion*
354  mExcludeHolidays; // non-null to not trigger alarms on holidays (= mHolidays when trigger calculated)
355  mutable int mWorkTimeOnly; // non-zero to trigger alarm only during working hours (= mWorkTimeIndex when trigger calculated)
356  SubAction mActionSubType; // sub-action type for the event's main alarm
357  CalEvent::Type mCategory; // event category (active, archived, template, ...)
358  ExtraActionOptions mExtraActionOptions;// options for pre- or post-alarm actions
359 #ifndef KALARMCAL_USE_KRESOURCES
360  KACalendar::Compat mCompatibility; // event's storage format compatibility
361  bool mReadOnly; // event is read-only in its original calendar file
362 #endif
363  bool mConfirmAck; // alarm acknowledgement requires confirmation by user
364  bool mUseDefaultFont; // use default message font, not mFont
365  bool mCommandScript; // the command text is a script, not a shell command line
366  bool mCommandXterm; // command alarm is to be executed in a terminal window
367  bool mCommandDisplay; // command output is to be displayed in an alarm window
368  bool mEmailBcc; // blind copy the email to the user
369  bool mBeep; // whether to beep when the alarm is displayed
370  bool mSpeak; // whether to speak the message when the alarm is displayed
371  bool mCopyToKOrganizer; // KOrganizer should hold a copy of the event
372  bool mReminderOnceOnly; // the reminder is output only for the first recurrence
373  bool mAutoClose; // whether to close the alarm window after the late-cancel period
374  bool mMainExpired; // main alarm has expired (in which case a deferral alarm will exist)
375  bool mRepeatAtLogin; // whether to repeat the alarm at every login
376  bool mArchiveRepeatAtLogin; // if now archived, original event was repeat-at-login
377  bool mArchive; // event has triggered in the past, so archive it when closed
378  bool mDisplaying; // whether the alarm is currently being displayed (i.e. in displaying calendar)
379  bool mDisplayingDefer; // show Defer button (applies to displaying calendar only)
380  bool mDisplayingEdit; // show Edit button (applies to displaying calendar only)
381  bool mEnabled; // false if event is disabled
382 
383  public:
384  static const QByteArray FLAGS_PROPERTY;
385  static const QString DATE_ONLY_FLAG;
386  static const QString EMAIL_BCC_FLAG;
387  static const QString CONFIRM_ACK_FLAG;
388  static const QString KORGANIZER_FLAG;
389  static const QString EXCLUDE_HOLIDAYS_FLAG;
390  static const QString WORK_TIME_ONLY_FLAG;
391  static const QString REMINDER_ONCE_FLAG;
392  static const QString DEFER_FLAG;
393  static const QString LATE_CANCEL_FLAG;
394  static const QString AUTO_CLOSE_FLAG;
395  static const QString TEMPL_AFTER_TIME_FLAG;
396  static const QString KMAIL_SERNUM_FLAG;
397  static const QString ARCHIVE_FLAG;
398  static const QByteArray NEXT_RECUR_PROPERTY;
399  static const QByteArray REPEAT_PROPERTY;
400  static const QByteArray LOG_PROPERTY;
401  static const QString xtermURL;
402  static const QString displayURL;
403  static const QByteArray TYPE_PROPERTY;
404  static const QString FILE_TYPE;
405  static const QString AT_LOGIN_TYPE;
406  static const QString REMINDER_TYPE;
407  static const QString REMINDER_ONCE_TYPE;
408  static const QString TIME_DEFERRAL_TYPE;
409  static const QString DATE_DEFERRAL_TYPE;
410  static const QString DISPLAYING_TYPE;
411  static const QString PRE_ACTION_TYPE;
412  static const QString POST_ACTION_TYPE;
413  static const QString SOUND_REPEAT_TYPE;
414  static const QByteArray NEXT_REPEAT_PROPERTY;
415  static const QString HIDDEN_REMINDER_FLAG;
416  static const QByteArray FONT_COLOUR_PROPERTY;
417  static const QByteArray VOLUME_PROPERTY;
418  static const QString EMAIL_ID_FLAG;
419  static const QString SPEAK_FLAG;
420  static const QString EXEC_ON_DEFERRAL_FLAG;
421  static const QString CANCEL_ON_ERROR_FLAG;
422  static const QString DONT_SHOW_ERROR_FLAG;
423  static const QString DISABLED_STATUS;
424  static const QString DISP_DEFER;
425  static const QString DISP_EDIT;
426  static const QString CMD_ERROR_VALUE;
427  static const QString CMD_ERROR_PRE_VALUE;
428  static const QString CMD_ERROR_POST_VALUE;
429  static const QString SC;
430 };
431 
432 
433 // KAlarm version which first used the current calendar/event format.
434 // If this changes, KAEvent::convertKCalEvents() must be changed correspondingly.
435 // The string version is the KAlarm version string used in the calendar file.
436 QByteArray KAEvent::currentCalendarVersionString() { return QByteArray("2.7.0"); }
437 int KAEvent::currentCalendarVersion() { return Version(2,7,0); }
438 
439 // Custom calendar properties.
440 // Note that all custom property names are prefixed with X-KDE-KALARM- in the calendar file.
441 
442 // Event properties
443 const QByteArray KAEvent::Private::FLAGS_PROPERTY("FLAGS"); // X-KDE-KALARM-FLAGS property
444 const QString KAEvent::Private::DATE_ONLY_FLAG = QLatin1String("DATE");
445 const QString KAEvent::Private::EMAIL_BCC_FLAG = QLatin1String("BCC");
446 const QString KAEvent::Private::CONFIRM_ACK_FLAG = QLatin1String("ACKCONF");
447 const QString KAEvent::Private::KORGANIZER_FLAG = QLatin1String("KORG");
448 const QString KAEvent::Private::EXCLUDE_HOLIDAYS_FLAG = QLatin1String("EXHOLIDAYS");
449 const QString KAEvent::Private::WORK_TIME_ONLY_FLAG = QLatin1String("WORKTIME");
450 const QString KAEvent::Private::REMINDER_ONCE_FLAG = QLatin1String("ONCE");
451 const QString KAEvent::Private::DEFER_FLAG = QLatin1String("DEFER"); // default defer interval for this alarm
452 const QString KAEvent::Private::LATE_CANCEL_FLAG = QLatin1String("LATECANCEL");
453 const QString KAEvent::Private::AUTO_CLOSE_FLAG = QLatin1String("LATECLOSE");
454 const QString KAEvent::Private::TEMPL_AFTER_TIME_FLAG = QLatin1String("TMPLAFTTIME");
455 const QString KAEvent::Private::KMAIL_SERNUM_FLAG = QLatin1String("KMAIL");
456 const QString KAEvent::Private::ARCHIVE_FLAG = QLatin1String("ARCHIVE");
457 
458 const QByteArray KAEvent::Private::NEXT_RECUR_PROPERTY("NEXTRECUR"); // X-KDE-KALARM-NEXTRECUR property
459 const QByteArray KAEvent::Private::REPEAT_PROPERTY("REPEAT"); // X-KDE-KALARM-REPEAT property
460 const QByteArray KAEvent::Private::LOG_PROPERTY("LOG"); // X-KDE-KALARM-LOG property
461 const QString KAEvent::Private::xtermURL = QLatin1String("xterm:");
462 const QString KAEvent::Private::displayURL = QLatin1String("display:");
463 
464 // - General alarm properties
465 const QByteArray KAEvent::Private::TYPE_PROPERTY("TYPE"); // X-KDE-KALARM-TYPE property
466 const QString KAEvent::Private::FILE_TYPE = QLatin1String("FILE");
467 const QString KAEvent::Private::AT_LOGIN_TYPE = QLatin1String("LOGIN");
468 const QString KAEvent::Private::REMINDER_TYPE = QLatin1String("REMINDER");
469 const QString KAEvent::Private::TIME_DEFERRAL_TYPE = QLatin1String("DEFERRAL");
470 const QString KAEvent::Private::DATE_DEFERRAL_TYPE = QLatin1String("DATE_DEFERRAL");
471 const QString KAEvent::Private::DISPLAYING_TYPE = QLatin1String("DISPLAYING"); // used only in displaying calendar
472 const QString KAEvent::Private::PRE_ACTION_TYPE = QLatin1String("PRE");
473 const QString KAEvent::Private::POST_ACTION_TYPE = QLatin1String("POST");
474 const QString KAEvent::Private::SOUND_REPEAT_TYPE = QLatin1String("SOUNDREPEAT");
475 const QByteArray KAEvent::Private::NEXT_REPEAT_PROPERTY("NEXTREPEAT"); // X-KDE-KALARM-NEXTREPEAT property
476 const QString KAEvent::Private::HIDDEN_REMINDER_FLAG = QLatin1String("HIDE");
477 // - Display alarm properties
478 const QByteArray KAEvent::Private::FONT_COLOUR_PROPERTY("FONTCOLOR"); // X-KDE-KALARM-FONTCOLOR property
479 // - Email alarm properties
480 const QString KAEvent::Private::EMAIL_ID_FLAG = QLatin1String("EMAILID");
481 // - Audio alarm properties
482 const QByteArray KAEvent::Private::VOLUME_PROPERTY("VOLUME"); // X-KDE-KALARM-VOLUME property
483 const QString KAEvent::Private::SPEAK_FLAG = QLatin1String("SPEAK");
484 // - Command alarm properties
485 const QString KAEvent::Private::EXEC_ON_DEFERRAL_FLAG = QLatin1String("EXECDEFER");
486 const QString KAEvent::Private::CANCEL_ON_ERROR_FLAG = QLatin1String("ERRCANCEL");
487 const QString KAEvent::Private::DONT_SHOW_ERROR_FLAG = QLatin1String("ERRNOSHOW");
488 
489 // Event status strings
490 const QString KAEvent::Private::DISABLED_STATUS = QLatin1String("DISABLED");
491 
492 // Displaying event ID identifier
493 const QString KAEvent::Private::DISP_DEFER = QLatin1String("DEFER");
494 const QString KAEvent::Private::DISP_EDIT = QLatin1String("EDIT");
495 
496 // Command error strings
497 #ifdef KALARMCAL_USE_KRESOURCES
498 QString KAEvent::Private::mCmdErrConfigGroup = QLatin1String("CommandErrors");
499 #endif
500 const QString KAEvent::Private::CMD_ERROR_VALUE = QLatin1String("MAIN");
501 const QString KAEvent::Private::CMD_ERROR_PRE_VALUE = QLatin1String("PRE");
502 const QString KAEvent::Private::CMD_ERROR_POST_VALUE = QLatin1String("POST");
503 
504 const QString KAEvent::Private::SC = QLatin1String(";");
505 
506 QFont KAEvent::Private::mDefaultFont;
507 const KHolidays::HolidayRegion* KAEvent::Private::mHolidays = 0;
508 QBitArray KAEvent::Private::mWorkDays(7);
509 QTime KAEvent::Private::mWorkDayStart(9, 0, 0);
510 QTime KAEvent::Private::mWorkDayEnd(17, 0, 0);
511 int KAEvent::Private::mWorkTimeIndex = 1;
512 
513 
514 #ifndef KALARMCAL_USE_KRESOURCES
515 static void setProcedureAlarm(const Alarm::Ptr&, const QString& commandLine);
516 #else
517 static void setProcedureAlarm(Alarm*, const QString& commandLine);
518 #endif
519 static QString reminderToString(int minutes);
520 
521 
522 /*=============================================================================
523 = Class KAEvent
524 = Corresponds to a KCal::Event instance.
525 =============================================================================*/
526 
527 inline void KAEvent::Private::set_deferral(DeferType type)
528 {
529  if (type)
530  {
531  if (mDeferral == NO_DEFERRAL)
532  ++mAlarmCount;
533  }
534  else
535  {
536  if (mDeferral != NO_DEFERRAL)
537  --mAlarmCount;
538  }
539  mDeferral = type;
540 }
541 
542 inline void KAEvent::Private::activate_reminder(bool activate)
543 {
544  if (activate && mReminderActive != ACTIVE_REMINDER && mReminderMinutes)
545  {
546  if (mReminderActive == NO_REMINDER)
547  ++mAlarmCount;
548  mReminderActive = ACTIVE_REMINDER;
549  }
550  else if (!activate && mReminderActive != NO_REMINDER)
551  {
552  mReminderActive = NO_REMINDER;
553  mReminderAfterTime = DateTime();
554  --mAlarmCount;
555  }
556 }
557 
558 KAEvent::KAEvent()
559  : d(new Private)
560 { }
561 
562 KAEvent::Private::Private()
563  :
564 #ifdef KALARMCAL_USE_KRESOURCES
565  mResource(0),
566 #endif
567  mCommandError(CMD_NO_ERROR),
568 #ifndef KALARMCAL_USE_KRESOURCES
569  mItemId(-1),
570  mCollectionId(-1),
571 #endif
572  mReminderMinutes(0),
573  mReminderActive(NO_REMINDER),
574  mRevision(0),
575  mRecurrence(0),
576  mNextRepeat(0),
577  mAlarmCount(0),
578  mDeferral(NO_DEFERRAL),
579  mChangeCount(0),
580  mTriggerChanged(false),
581  mLateCancel(0),
582  mExcludeHolidays(0),
583  mWorkTimeOnly(0),
584  mCategory(CalEvent::EMPTY),
585 #ifndef KALARMCAL_USE_KRESOURCES
586  mCompatibility(KACalendar::Current),
587  mReadOnly(false),
588 #endif
589  mConfirmAck(false),
590  mEmailBcc(false),
591  mBeep(false),
592  mAutoClose(false),
593  mRepeatAtLogin(false),
594  mDisplaying(false)
595 { }
596 
597 KAEvent::KAEvent(const KDateTime& dt, const QString& message, const QColor& bg, const QColor& fg, const QFont& f,
598  SubAction action, int lateCancel, Flags flags, bool changesPending)
599  : d(new Private(dt, message, bg, fg, f, action, lateCancel, flags, changesPending))
600 {
601 }
602 
603 KAEvent::Private::Private(const KDateTime& dt, const QString& message, const QColor& bg, const QColor& fg, const QFont& f,
604  SubAction action, int lateCancel, Flags flags, bool changesPending)
605  : mRecurrence(0)
606 {
607  set(dt, message, bg, fg, f, action, lateCancel, flags, changesPending);
608 }
609 
610 #ifndef KALARMCAL_USE_KRESOURCES
611 KAEvent::KAEvent(const Event::Ptr& e)
612 #else
613 KAEvent::KAEvent(const Event* e)
614 #endif
615  : d(new Private(e))
616 {
617 }
618 
619 #ifndef KALARMCAL_USE_KRESOURCES
620 KAEvent::Private::Private(const Event::Ptr& e)
621 #else
622 KAEvent::Private::Private(const Event* e)
623 #endif
624  : mRecurrence(0)
625 {
626  set(e);
627 }
628 
629 KAEvent::Private::Private(const KAEvent::Private& e)
630  : QSharedData(e),
631  mRecurrence(0)
632 {
633  copy(e);
634 }
635 
636 KAEvent::KAEvent(const KAEvent& other)
637  : d(other.d)
638 { }
639 
640 KAEvent::~KAEvent()
641 { }
642 
643 KAEvent& KAEvent::operator=(const KAEvent& other)
644 {
645  if (&other != this)
646  d = other.d;
647  return *this;
648 }
649 
650 /******************************************************************************
651 * Copies the data from another instance.
652 */
653 void KAEvent::Private::copy(const KAEvent::Private& event)
654 {
655 #ifdef KALARMCAL_USE_KRESOURCES
656  mResource = event.mResource;
657 #endif
658  mAllTrigger = event.mAllTrigger;
659  mMainTrigger = event.mMainTrigger;
660  mAllWorkTrigger = event.mAllWorkTrigger;
661  mMainWorkTrigger = event.mMainWorkTrigger;
662  mCommandError = event.mCommandError;
663  mEventID = event.mEventID;
664  mTemplateName = event.mTemplateName;
665 #ifndef KALARMCAL_USE_KRESOURCES
666  mCustomProperties = event.mCustomProperties;
667  mItemId = event.mItemId;
668  mCollectionId = event.mCollectionId;
669 #else
670  mOriginalResourceId = event.mOriginalResourceId;
671 #endif
672  mText = event.mText;
673  mAudioFile = event.mAudioFile;
674  mPreAction = event.mPreAction;
675  mPostAction = event.mPostAction;
676  mStartDateTime = event.mStartDateTime;
677  mCreatedDateTime = event.mCreatedDateTime;
678  mNextMainDateTime = event.mNextMainDateTime;
679  mAtLoginDateTime = event.mAtLoginDateTime;
680  mDeferralTime = event.mDeferralTime;
681  mDisplayingTime = event.mDisplayingTime;
682  mDisplayingFlags = event.mDisplayingFlags;
683  mReminderMinutes = event.mReminderMinutes;
684  mReminderAfterTime = event.mReminderAfterTime;
685  mReminderActive = event.mReminderActive;
686  mDeferDefaultMinutes = event.mDeferDefaultMinutes;
687  mDeferDefaultDateOnly = event.mDeferDefaultDateOnly;
688  mRevision = event.mRevision;
689  mRepetition = event.mRepetition;
690  mNextRepeat = event.mNextRepeat;
691  mAlarmCount = event.mAlarmCount;
692  mDeferral = event.mDeferral;
693  mKMailSerialNumber = event.mKMailSerialNumber;
694  mTemplateAfterTime = event.mTemplateAfterTime;
695  mBgColour = event.mBgColour;
696  mFgColour = event.mFgColour;
697  mFont = event.mFont;
698  mEmailFromIdentity = event.mEmailFromIdentity;
699  mEmailAddresses = event.mEmailAddresses;
700  mEmailSubject = event.mEmailSubject;
701  mEmailAttachments = event.mEmailAttachments;
702  mLogFile = event.mLogFile;
703  mSoundVolume = event.mSoundVolume;
704  mFadeVolume = event.mFadeVolume;
705  mFadeSeconds = event.mFadeSeconds;
706  mRepeatSoundPause = event.mRepeatSoundPause;
707  mLateCancel = event.mLateCancel;
708  mExcludeHolidays = event.mExcludeHolidays;
709  mWorkTimeOnly = event.mWorkTimeOnly;
710  mActionSubType = event.mActionSubType;
711  mCategory = event.mCategory;
712  mExtraActionOptions = event.mExtraActionOptions;
713 #ifndef KALARMCAL_USE_KRESOURCES
714  mCompatibility = event.mCompatibility;
715  mReadOnly = event.mReadOnly;
716 #endif
717  mConfirmAck = event.mConfirmAck;
718  mUseDefaultFont = event.mUseDefaultFont;
719  mCommandScript = event.mCommandScript;
720  mCommandXterm = event.mCommandXterm;
721  mCommandDisplay = event.mCommandDisplay;
722  mEmailBcc = event.mEmailBcc;
723  mBeep = event.mBeep;
724  mSpeak = event.mSpeak;
725  mCopyToKOrganizer = event.mCopyToKOrganizer;
726  mReminderOnceOnly = event.mReminderOnceOnly;
727  mAutoClose = event.mAutoClose;
728  mMainExpired = event.mMainExpired;
729  mRepeatAtLogin = event.mRepeatAtLogin;
730  mArchiveRepeatAtLogin = event.mArchiveRepeatAtLogin;
731  mArchive = event.mArchive;
732  mDisplaying = event.mDisplaying;
733  mDisplayingDefer = event.mDisplayingDefer;
734  mDisplayingEdit = event.mDisplayingEdit;
735  mEnabled = event.mEnabled;
736  mChangeCount = 0;
737  mTriggerChanged = event.mTriggerChanged;
738  delete mRecurrence;
739  if (event.mRecurrence)
740  mRecurrence = new KARecurrence(*event.mRecurrence);
741  else
742  mRecurrence = 0;
743 }
744 
745 #ifndef KALARMCAL_USE_KRESOURCES
746 void KAEvent::set(const Event::Ptr& e)
747 #else
748 void KAEvent::set(const Event* e)
749 #endif
750 {
751  d->set(e);
752 }
753 
754 /******************************************************************************
755 * Initialise the KAEvent::Private from a KCal::Event.
756 */
757 #ifndef KALARMCAL_USE_KRESOURCES
758 void KAEvent::Private::set(const Event::Ptr& event)
759 #else
760 void KAEvent::Private::set(const Event* event)
761 #endif
762 {
763  startChanges();
764  // Extract status from the event
765  mCommandError = CMD_NO_ERROR;
766 #ifdef KALARMCAL_USE_KRESOURCES
767  mResource = 0;
768 #endif
769  mEventID = event->uid();
770  mRevision = event->revision();
771  mTemplateName.clear();
772  mLogFile.clear();
773 #ifndef KALARMCAL_USE_KRESOURCES
774  mItemId = -1;
775  mCollectionId = -1;
776 #else
777  mOriginalResourceId.clear();
778 #endif
779  mTemplateAfterTime = -1;
780  mBeep = false;
781  mSpeak = false;
782  mEmailBcc = false;
783  mCommandXterm = false;
784  mCommandDisplay = false;
785  mCopyToKOrganizer = false;
786  mConfirmAck = false;
787  mArchive = false;
788  mReminderOnceOnly = false;
789  mAutoClose = false;
790  mArchiveRepeatAtLogin = false;
791  mDisplayingDefer = false;
792  mDisplayingEdit = false;
793  mDeferDefaultDateOnly = false;
794  mReminderActive = NO_REMINDER;
795  mReminderMinutes = 0;
796  mDeferDefaultMinutes = 0;
797  mLateCancel = 0;
798  mKMailSerialNumber = 0;
799  mExcludeHolidays = 0;
800  mWorkTimeOnly = 0;
801  mChangeCount = 0;
802  mBgColour = QColor(255, 255, 255); // missing/invalid colour - return white background
803  mFgColour = QColor(0, 0, 0); // and black foreground
804 #ifndef KALARMCAL_USE_KRESOURCES
805  mCompatibility = KACalendar::Current;
806  mReadOnly = event->isReadOnly();
807 #endif
808  mUseDefaultFont = true;
809  mEnabled = true;
810  clearRecur();
811  QString param;
812  bool ok;
813  mCategory = CalEvent::status(event, &param);
814  if (mCategory == CalEvent::DISPLAYING)
815  {
816  // It's a displaying calendar event - set values specific to displaying alarms
817  const QStringList params = param.split(SC, QString::KeepEmptyParts);
818  int n = params.count();
819  if (n)
820  {
821 #ifndef KALARMCAL_USE_KRESOURCES
822  const qlonglong id = params[0].toLongLong(&ok);
823  if (ok)
824  mCollectionId = id; // original collection ID which contained the event
825 #else
826  mOriginalResourceId = params[0];
827 #endif
828  for (int i = 1; i < n; ++i)
829  {
830  if (params[i] == DISP_DEFER)
831  mDisplayingDefer = true;
832  if (params[i] == DISP_EDIT)
833  mDisplayingEdit = true;
834  }
835  }
836  }
837 #ifndef KALARMCAL_USE_KRESOURCES
838  // Store the non-KAlarm custom properties of the event
839  const QByteArray kalarmKey = "X-KDE-" + KACalendar::APPNAME + '-';
840  mCustomProperties = event->customProperties();
841  for (QMap<QByteArray, QString>::Iterator it = mCustomProperties.begin(); it != mCustomProperties.end(); )
842  {
843  if (it.key().startsWith(kalarmKey))
844  it = mCustomProperties.erase(it);
845  else
846  ++it;
847  }
848 #endif
849 
850  bool dateOnly = false;
851  QStringList flags = event->customProperty(KACalendar::APPNAME, FLAGS_PROPERTY).split(SC, QString::SkipEmptyParts);
852  flags << QString() << QString(); // to avoid having to check for end of list
853  for (int i = 0, end = flags.count() - 1; i < end; ++i)
854  {
855  if (flags[i] == DATE_ONLY_FLAG)
856  dateOnly = true;
857  else if (flags[i] == CONFIRM_ACK_FLAG)
858  mConfirmAck = true;
859  else if (flags[i] == EMAIL_BCC_FLAG)
860  mEmailBcc = true;
861  else if (flags[i] == KORGANIZER_FLAG)
862  mCopyToKOrganizer = true;
863  else if (flags[i] == EXCLUDE_HOLIDAYS_FLAG)
864  mExcludeHolidays = mHolidays;
865  else if (flags[i] == WORK_TIME_ONLY_FLAG)
866  mWorkTimeOnly = 1;
867  else if (flags[i]== KMAIL_SERNUM_FLAG)
868  {
869  const unsigned long n = flags[i + 1].toULong(&ok);
870  if (!ok)
871  continue;
872  mKMailSerialNumber = n;
873  ++i;
874  }
875  else if (flags[i] == Private::ARCHIVE_FLAG)
876  mArchive = true;
877  else if (flags[i] == Private::AT_LOGIN_TYPE)
878  mArchiveRepeatAtLogin = true;
879  else if (flags[i] == Private::REMINDER_TYPE)
880  {
881  if (flags[++i] == Private::REMINDER_ONCE_FLAG)
882  {
883  mReminderOnceOnly = true;
884  ++i;
885  }
886  const int len = flags[i].length() - 1;
887  mReminderMinutes = -flags[i].left(len).toInt(); // -> 0 if conversion fails
888  switch (flags[i].at(len).toLatin1())
889  {
890  case 'M': break;
891  case 'H': mReminderMinutes *= 60; break;
892  case 'D': mReminderMinutes *= 1440; break;
893  default: mReminderMinutes = 0; break;
894  }
895  }
896  else if (flags[i] == DEFER_FLAG)
897  {
898  QString mins = flags[i + 1];
899  if (mins.endsWith('D'))
900  {
901  mDeferDefaultDateOnly = true;
902  mins.truncate(mins.length() - 1);
903  }
904  const int n = static_cast<int>(mins.toUInt(&ok));
905  if (!ok)
906  continue;
907  mDeferDefaultMinutes = n;
908  ++i;
909  }
910  else if (flags[i] == TEMPL_AFTER_TIME_FLAG)
911  {
912  const int n = static_cast<int>(flags[i + 1].toUInt(&ok));
913  if (!ok)
914  continue;
915  mTemplateAfterTime = n;
916  ++i;
917  }
918  else if (flags[i] == LATE_CANCEL_FLAG)
919  {
920  mLateCancel = static_cast<int>(flags[i + 1].toUInt(&ok));
921  if (ok)
922  ++i;
923  if (!ok || !mLateCancel)
924  mLateCancel = 1; // invalid parameter defaults to 1 minute
925  }
926  else if (flags[i] == AUTO_CLOSE_FLAG)
927  {
928  mLateCancel = static_cast<int>(flags[i + 1].toUInt(&ok));
929  if (ok)
930  ++i;
931  if (!ok || !mLateCancel)
932  mLateCancel = 1; // invalid parameter defaults to 1 minute
933  mAutoClose = true;
934  }
935  }
936 
937  QString prop = event->customProperty(KACalendar::APPNAME, LOG_PROPERTY);
938  if (!prop.isEmpty())
939  {
940  if (prop == xtermURL)
941  mCommandXterm = true;
942  else if (prop == displayURL)
943  mCommandDisplay = true;
944  else
945  mLogFile = prop;
946  }
947  prop = event->customProperty(KACalendar::APPNAME, REPEAT_PROPERTY);
948  if (!prop.isEmpty())
949  {
950  // This property is used when the main alarm has expired
951  const QStringList list = prop.split(QLatin1Char(':'));
952  if (list.count() >= 2)
953  {
954  const int interval = static_cast<int>(list[0].toUInt());
955  const int count = static_cast<int>(list[1].toUInt());
956  if (interval && count)
957  {
958  if (interval % (24*60))
959  mRepetition.set(Duration(interval * 60, Duration::Seconds), count);
960  else
961  mRepetition.set(Duration(interval / (24*60), Duration::Days), count);
962  }
963  }
964  }
965  mNextMainDateTime = readDateTime(event, dateOnly, mStartDateTime);
966  mCreatedDateTime = event->created();
967  if (dateOnly && !mRepetition.isDaily())
968  mRepetition.set(Duration(mRepetition.intervalDays(), Duration::Days));
969  if (mCategory == CalEvent::TEMPLATE)
970  mTemplateName = event->summary();
971 #ifndef KALARMCAL_USE_KRESOURCES
972  if (event->customStatus() == DISABLED_STATUS)
973 #else
974  if (event->statusStr() == DISABLED_STATUS)
975 #endif
976  mEnabled = false;
977 
978  // Extract status from the event's alarms.
979  // First set up defaults.
980  mActionSubType = MESSAGE;
981  mMainExpired = true;
982  mRepeatAtLogin = false;
983  mDisplaying = false;
984  mCommandScript = false;
985  mExtraActionOptions = 0;
986  mDeferral = NO_DEFERRAL;
987  mSoundVolume = -1;
988  mFadeVolume = -1;
989  mRepeatSoundPause = -1;
990  mFadeSeconds = 0;
991  mEmailFromIdentity = 0;
992  mReminderAfterTime = DateTime();
993  mText.clear();
994  mAudioFile.clear();
995  mPreAction.clear();
996  mPostAction.clear();
997  mEmailSubject.clear();
998  mEmailAddresses.clear();
999  mEmailAttachments.clear();
1000 
1001  // Extract data from all the event's alarms and index the alarms by sequence number
1002  AlarmMap alarmMap;
1003  readAlarms(event, &alarmMap, mCommandDisplay);
1004 
1005  // Incorporate the alarms' details into the overall event
1006  mAlarmCount = 0; // initialise as invalid
1007  DateTime alTime;
1008  bool set = false;
1009  bool isEmailText = false;
1010  bool setDeferralTime = false;
1011  Duration deferralOffset;
1012  for (AlarmMap::ConstIterator it = alarmMap.constBegin(); it != alarmMap.constEnd(); ++it)
1013  {
1014  const AlarmData& data = it.value();
1015  const DateTime dateTime = data.alarm->hasStartOffset() ? data.alarm->startOffset().end(mNextMainDateTime.effectiveKDateTime()) : data.alarm->time();
1016  switch (data.type)
1017  {
1018  case MAIN_ALARM:
1019  mMainExpired = false;
1020  alTime = dateTime;
1021  alTime.setDateOnly(mStartDateTime.isDateOnly());
1022  if (data.alarm->repeatCount() && data.alarm->snoozeTime())
1023  {
1024  mRepetition.set(data.alarm->snoozeTime(), data.alarm->repeatCount()); // values may be adjusted in setRecurrence()
1025  mNextRepeat = data.nextRepeat;
1026  }
1027  if (data.action != KAAlarm::AUDIO)
1028  break;
1029  // Fall through to AUDIO_ALARM
1030  case AUDIO_ALARM:
1031  mAudioFile = data.cleanText;
1032  mSpeak = data.speak && mAudioFile.isEmpty();
1033  mBeep = !mSpeak && mAudioFile.isEmpty();
1034  mSoundVolume = (!mBeep && !mSpeak) ? data.soundVolume : -1;
1035  mFadeVolume = (mSoundVolume >= 0 && data.fadeSeconds > 0) ? data.fadeVolume : -1;
1036  mFadeSeconds = (mFadeVolume >= 0) ? data.fadeSeconds : 0;
1037  mRepeatSoundPause = (!mBeep && !mSpeak) ? data.repeatSoundPause : -1;
1038  break;
1039  case AT_LOGIN_ALARM:
1040  mRepeatAtLogin = true;
1041  mAtLoginDateTime = dateTime.kDateTime();
1042  alTime = mAtLoginDateTime;
1043  break;
1044  case REMINDER_ALARM:
1045  // N.B. there can be a start offset but no valid date/time (e.g. in template)
1046  if (data.alarm->startOffset().asSeconds() / 60)
1047  {
1048  mReminderActive = ACTIVE_REMINDER;
1049  if (mReminderMinutes < 0)
1050  {
1051  mReminderAfterTime = dateTime; // the reminder is AFTER the main alarm
1052  mReminderAfterTime.setDateOnly(dateOnly);
1053  if (data.hiddenReminder)
1054  mReminderActive = HIDDEN_REMINDER;
1055  }
1056  }
1057  break;
1058  case DEFERRED_REMINDER_ALARM:
1059  case DEFERRED_ALARM:
1060  mDeferral = (data.type == DEFERRED_REMINDER_ALARM) ? REMINDER_DEFERRAL : NORMAL_DEFERRAL;
1061  mDeferralTime = dateTime;
1062  if (!data.timedDeferral)
1063  mDeferralTime.setDateOnly(true);
1064  if (data.alarm->hasStartOffset())
1065  deferralOffset = data.alarm->startOffset();
1066  break;
1067  case DISPLAYING_ALARM:
1068  {
1069  mDisplaying = true;
1070  mDisplayingFlags = data.displayingFlags;
1071  const bool dateOnly = (mDisplayingFlags & DEFERRAL) ? !(mDisplayingFlags & TIMED_FLAG)
1072  : mStartDateTime.isDateOnly();
1073  mDisplayingTime = dateTime;
1074  mDisplayingTime.setDateOnly(dateOnly);
1075  alTime = mDisplayingTime;
1076  break;
1077  }
1078  case PRE_ACTION_ALARM:
1079  mPreAction = data.cleanText;
1080  mExtraActionOptions = data.extraActionOptions;
1081  break;
1082  case POST_ACTION_ALARM:
1083  mPostAction = data.cleanText;
1084  break;
1085  case INVALID_ALARM:
1086  default:
1087  break;
1088  }
1089 
1090  bool noSetNextTime = false;
1091  switch (data.type)
1092  {
1093  case DEFERRED_REMINDER_ALARM:
1094  case DEFERRED_ALARM:
1095  if (!set)
1096  {
1097  // The recurrence has to be evaluated before we can
1098  // calculate the time of a deferral alarm.
1099  setDeferralTime = true;
1100  noSetNextTime = true;
1101  }
1102  // fall through to REMINDER_ALARM
1103  case REMINDER_ALARM:
1104  case AT_LOGIN_ALARM:
1105  case DISPLAYING_ALARM:
1106  if (!set && !noSetNextTime)
1107  mNextMainDateTime = alTime;
1108  // fall through to MAIN_ALARM
1109  case MAIN_ALARM:
1110  // Ensure that the basic fields are set up even if there is no main
1111  // alarm in the event (if it has expired and then been deferred)
1112  if (!set)
1113  {
1114  mActionSubType = (KAEvent::SubAction)data.action;
1115  mText = (mActionSubType == COMMAND) ? data.cleanText.trimmed() : data.cleanText;
1116  switch (data.action)
1117  {
1118  case KAAlarm::COMMAND:
1119  mCommandScript = data.commandScript;
1120  if (!mCommandDisplay)
1121  break;
1122  // fall through to MESSAGE
1123  case KAAlarm::MESSAGE:
1124  mFont = data.font;
1125  mUseDefaultFont = data.defaultFont;
1126  if (data.isEmailText)
1127  isEmailText = true;
1128  // fall through to FILE
1129  case KAAlarm::FILE:
1130  mBgColour = data.bgColour;
1131  mFgColour = data.fgColour;
1132  break;
1133  case KAAlarm::EMAIL:
1134  mEmailFromIdentity = data.emailFromId;
1135  mEmailAddresses = data.alarm->mailAddresses();
1136  mEmailSubject = data.alarm->mailSubject();
1137  mEmailAttachments = data.alarm->mailAttachments();
1138  break;
1139  case KAAlarm::AUDIO:
1140  // Already mostly handled above
1141  mRepeatSoundPause = data.repeatSoundPause;
1142  break;
1143  default:
1144  break;
1145  }
1146  set = true;
1147  }
1148  if (data.action == KAAlarm::FILE && mActionSubType == MESSAGE)
1149  mActionSubType = FILE;
1150  ++mAlarmCount;
1151  break;
1152  case AUDIO_ALARM:
1153  case PRE_ACTION_ALARM:
1154  case POST_ACTION_ALARM:
1155  case INVALID_ALARM:
1156  default:
1157  break;
1158  }
1159  }
1160  if (!isEmailText)
1161  mKMailSerialNumber = 0;
1162 
1163  Recurrence* recur = event->recurrence();
1164  if (recur && recur->recurs())
1165  {
1166  const int nextRepeat = mNextRepeat; // setRecurrence() clears mNextRepeat
1167  setRecurrence(*recur);
1168  if (nextRepeat <= mRepetition.count())
1169  mNextRepeat = nextRepeat;
1170  }
1171  else if (mRepetition)
1172  {
1173  // Convert a repetition with no recurrence into a recurrence
1174  if (mRepetition.isDaily())
1175  recur->setDaily(mRepetition.intervalDays());
1176  else
1177  recur->setMinutely(mRepetition.intervalMinutes());
1178  recur->setDuration(mRepetition.count() + 1);
1179  mRepetition.set(0, 0);
1180  }
1181 
1182  if (mRepeatAtLogin)
1183  {
1184  mArchiveRepeatAtLogin = false;
1185  if (mReminderMinutes > 0)
1186  {
1187  mReminderMinutes = 0; // pre-alarm reminder not allowed for at-login alarm
1188  mReminderActive = NO_REMINDER;
1189  }
1190  setRepeatAtLoginTrue(false); // clear other incompatible statuses
1191  }
1192 
1193  if (mMainExpired && deferralOffset && checkRecur() != KARecurrence::NO_RECUR)
1194  {
1195  // Adjust the deferral time for an expired recurrence, since the
1196  // offset is relative to the first actual occurrence.
1197  DateTime dt = mRecurrence->getNextDateTime(mStartDateTime.addDays(-1).kDateTime());
1198  dt.setDateOnly(mStartDateTime.isDateOnly());
1199  if (mDeferralTime.isDateOnly())
1200  {
1201  mDeferralTime = deferralOffset.end(dt.kDateTime());
1202  mDeferralTime.setDateOnly(true);
1203  }
1204  else
1205  mDeferralTime = deferralOffset.end(dt.effectiveKDateTime());
1206  }
1207  if (mDeferral != NO_DEFERRAL)
1208  {
1209  if (setDeferralTime)
1210  mNextMainDateTime = mDeferralTime;
1211  }
1212  mTriggerChanged = true;
1213  endChanges();
1214 }
1215 
1216 void KAEvent::set(const KDateTime& dt, const QString& message, const QColor& bg, const QColor& fg,
1217  const QFont& f, SubAction act, int lateCancel, Flags flags, bool changesPending)
1218 {
1219  d->set(dt, message, bg, fg, f, act, lateCancel, flags, changesPending);
1220 }
1221 
1222 /******************************************************************************
1223 * Initialise the instance with the specified parameters.
1224 */
1225 void KAEvent::Private::set(const KDateTime& dateTime, const QString& text, const QColor& bg, const QColor& fg,
1226  const QFont& font, SubAction action, int lateCancel, Flags flags, bool changesPending)
1227 {
1228  clearRecur();
1229  mStartDateTime = dateTime;
1230  mStartDateTime.setDateOnly(flags & ANY_TIME);
1231  mNextMainDateTime = mStartDateTime;
1232  switch (action)
1233  {
1234  case MESSAGE:
1235  case FILE:
1236  case COMMAND:
1237  case EMAIL:
1238  case AUDIO:
1239  mActionSubType = (KAEvent::SubAction)action;
1240  break;
1241  default:
1242  mActionSubType = MESSAGE;
1243  break;
1244  }
1245  mEventID.clear();
1246  mTemplateName.clear();
1247 #ifndef KALARMCAL_USE_KRESOURCES
1248  mItemId = -1;
1249  mCollectionId = -1;
1250 #else
1251  mResource = 0;
1252  mOriginalResourceId.clear();
1253 #endif
1254  mPreAction.clear();
1255  mPostAction.clear();
1256  mText = (mActionSubType == COMMAND) ? text.trimmed()
1257  : (mActionSubType == AUDIO) ? QString() : text;
1258  mCategory = CalEvent::ACTIVE;
1259  mAudioFile = (mActionSubType == AUDIO) ? text : QString();
1260  mSoundVolume = -1;
1261  mFadeVolume = -1;
1262  mTemplateAfterTime = -1;
1263  mFadeSeconds = 0;
1264  mBgColour = bg;
1265  mFgColour = fg;
1266  mFont = font;
1267  mAlarmCount = 1;
1268  mLateCancel = lateCancel; // do this before setting flags
1269  mDeferral = NO_DEFERRAL; // do this before setting flags
1270 
1271  mStartDateTime.setDateOnly(flags & ANY_TIME);
1272  set_deferral((flags & DEFERRAL) ? NORMAL_DEFERRAL : NO_DEFERRAL);
1273  mRepeatAtLogin = flags & REPEAT_AT_LOGIN;
1274  mConfirmAck = flags & CONFIRM_ACK;
1275  mUseDefaultFont = flags & DEFAULT_FONT;
1276  mCommandScript = flags & SCRIPT;
1277  mCommandXterm = flags & EXEC_IN_XTERM;
1278  mCommandDisplay = flags & DISPLAY_COMMAND;
1279  mCopyToKOrganizer = flags & COPY_KORGANIZER;
1280  mExcludeHolidays = (flags & EXCL_HOLIDAYS) ? mHolidays : 0;
1281  mWorkTimeOnly = flags & WORK_TIME_ONLY;
1282  mEmailBcc = flags & EMAIL_BCC;
1283  mEnabled = !(flags & DISABLED);
1284  mDisplaying = flags & DISPLAYING_;
1285  mReminderOnceOnly = flags & REMINDER_ONCE;
1286  mAutoClose = (flags & AUTO_CLOSE) && mLateCancel;
1287  mRepeatSoundPause = (flags & REPEAT_SOUND) ? 0 : -1;
1288  mSpeak = (flags & SPEAK) && action != AUDIO;
1289  mBeep = (flags & BEEP) && action != AUDIO && !mSpeak;
1290  if (mRepeatAtLogin) // do this after setting other flags
1291  {
1292  ++mAlarmCount;
1293  setRepeatAtLoginTrue(false);
1294  }
1295 
1296  mKMailSerialNumber = 0;
1297  mReminderMinutes = 0;
1298  mDeferDefaultMinutes = 0;
1299  mDeferDefaultDateOnly = false;
1300  mArchiveRepeatAtLogin = false;
1301  mReminderActive = NO_REMINDER;
1302  mDisplaying = false;
1303  mMainExpired = false;
1304  mDisplayingDefer = false;
1305  mDisplayingEdit = false;
1306  mArchive = false;
1307  mReminderAfterTime = DateTime();
1308  mExtraActionOptions = 0;
1309 #ifndef KALARMCAL_USE_KRESOURCES
1310  mCompatibility = KACalendar::Current;
1311  mReadOnly = false;
1312 #endif
1313  mCommandError = CMD_NO_ERROR;
1314  mChangeCount = changesPending ? 1 : 0;
1315  mTriggerChanged = true;
1316 }
1317 
1318 /******************************************************************************
1319 * Update an existing KCal::Event with the KAEvent::Private data.
1320 * If 'setCustomProperties' is true, all the KCal::Event's existing custom
1321 * properties are cleared and replaced with the KAEvent's custom properties. If
1322 * false, the KCal::Event's non-KAlarm custom properties are left untouched.
1323 */
1324 #ifndef KALARMCAL_USE_KRESOURCES
1325 bool KAEvent::updateKCalEvent(const KCalCore::Event::Ptr& e, UidAction u, bool setCustomProperties) const
1326 {
1327  return d->updateKCalEvent(e, u, setCustomProperties);
1328 }
1329 
1330 #else
1331 bool KAEvent::updateKCalEvent(KCal::Event* e, UidAction u) const
1332 {
1333  return d->updateKCalEvent(e, u);
1334 }
1335 #endif
1336 
1337 #ifndef KALARMCAL_USE_KRESOURCES
1338 bool KAEvent::Private::updateKCalEvent(const Event::Ptr& ev, UidAction uidact, bool setCustomProperties) const
1339 #else
1340 bool KAEvent::Private::updateKCalEvent(Event* ev, UidAction uidact) const
1341 #endif
1342 {
1343  // If it's an archived event, the event start date/time will be adjusted to its original
1344  // value instead of its next occurrence, and the expired main alarm will be reinstated.
1345  const bool archived = (mCategory == CalEvent::ARCHIVED);
1346 
1347  if (!ev
1348  || (uidact == UID_CHECK && !mEventID.isEmpty() && mEventID != ev->uid())
1349  || (!mAlarmCount && (!archived || !mMainExpired)))
1350  return false;
1351 
1352  ev->startUpdates(); // prevent multiple update notifications
1353  checkRecur(); // ensure recurrence/repetition data is consistent
1354  const bool readOnly = ev->isReadOnly();
1355  if (uidact == KAEvent::UID_SET)
1356  ev->setUid(mEventID);
1357 #ifndef KALARMCAL_USE_KRESOURCES
1358  ev->setReadOnly(mReadOnly);
1359 #else
1360  ev->setReadOnly(false);
1361 #endif
1362  ev->setTransparency(Event::Transparent);
1363 
1364  // Set up event-specific data
1365 
1366  // Set up custom properties.
1367 #ifndef KALARMCAL_USE_KRESOURCES
1368  if (setCustomProperties)
1369  ev->setCustomProperties(mCustomProperties);
1370 #endif
1371  ev->removeCustomProperty(KACalendar::APPNAME, FLAGS_PROPERTY);
1372  ev->removeCustomProperty(KACalendar::APPNAME, NEXT_RECUR_PROPERTY);
1373  ev->removeCustomProperty(KACalendar::APPNAME, REPEAT_PROPERTY);
1374  ev->removeCustomProperty(KACalendar::APPNAME, LOG_PROPERTY);
1375 
1376  QString param;
1377  if (mCategory == CalEvent::DISPLAYING)
1378  {
1379 #ifndef KALARMCAL_USE_KRESOURCES
1380  param = QString::number(mCollectionId); // original collection ID which contained the event
1381 #else
1382  param = mOriginalResourceId;
1383 #endif
1384  if (mDisplayingDefer)
1385  param += SC + DISP_DEFER;
1386  if (mDisplayingEdit)
1387  param += SC + DISP_EDIT;
1388  }
1389 #ifndef KALARMCAL_USE_KRESOURCES
1390  CalEvent::setStatus(ev, mCategory, param);
1391 #else
1392  CalEvent::setStatus(ev, mCategory, param);
1393 #endif
1394  QStringList flags;
1395  if (mStartDateTime.isDateOnly())
1396  flags += DATE_ONLY_FLAG;
1397  if (mConfirmAck)
1398  flags += CONFIRM_ACK_FLAG;
1399  if (mEmailBcc)
1400  flags += EMAIL_BCC_FLAG;
1401  if (mCopyToKOrganizer)
1402  flags += KORGANIZER_FLAG;
1403  if (mExcludeHolidays)
1404  flags += EXCLUDE_HOLIDAYS_FLAG;
1405  if (mWorkTimeOnly)
1406  flags += WORK_TIME_ONLY_FLAG;
1407  if (mLateCancel)
1408  (flags += (mAutoClose ? AUTO_CLOSE_FLAG : LATE_CANCEL_FLAG)) += QString::number(mLateCancel);
1409  if (mReminderMinutes)
1410  {
1411  flags += REMINDER_TYPE;
1412  if (mReminderOnceOnly)
1413  flags += REMINDER_ONCE_FLAG;
1414  flags += reminderToString(-mReminderMinutes);
1415  }
1416  if (mDeferDefaultMinutes)
1417  {
1418  QString param = QString::number(mDeferDefaultMinutes);
1419  if (mDeferDefaultDateOnly)
1420  param += 'D';
1421  (flags += DEFER_FLAG) += param;
1422  }
1423  if (!mTemplateName.isEmpty() && mTemplateAfterTime >= 0)
1424  (flags += TEMPL_AFTER_TIME_FLAG) += QString::number(mTemplateAfterTime);
1425  if (mKMailSerialNumber)
1426  (flags += KMAIL_SERNUM_FLAG) += QString::number(mKMailSerialNumber);
1427  if (mArchive && !archived)
1428  {
1429  flags += ARCHIVE_FLAG;
1430  if (mArchiveRepeatAtLogin)
1431  flags += AT_LOGIN_TYPE;
1432  }
1433  if (!flags.isEmpty())
1434  ev->setCustomProperty(KACalendar::APPNAME, FLAGS_PROPERTY, flags.join(SC));
1435 
1436  if (mCommandXterm)
1437  ev->setCustomProperty(KACalendar::APPNAME, LOG_PROPERTY, xtermURL);
1438  else if (mCommandDisplay)
1439  ev->setCustomProperty(KACalendar::APPNAME, LOG_PROPERTY, displayURL);
1440  else if (!mLogFile.isEmpty())
1441  ev->setCustomProperty(KACalendar::APPNAME, LOG_PROPERTY, mLogFile);
1442 
1443  ev->setCustomStatus(mEnabled ? QString() : DISABLED_STATUS);
1444  ev->setRevision(mRevision);
1445  ev->clearAlarms();
1446 
1447  /* Always set DTSTART as date/time, and use the category "DATE" to indicate
1448  * a date-only event, instead of calling setAllDay(). This is necessary to
1449  * allow a time zone to be specified for a date-only event. Also, KAlarm
1450  * allows the alarm to float within the 24-hour period defined by the
1451  * start-of-day time (which is user-dependent and therefore can't be
1452  * written into the calendar) rather than midnight to midnight, and there
1453  * is no RFC2445 conformant way to specify this.
1454  * RFC2445 states that alarm trigger times specified in absolute terms
1455  * (rather than relative to DTSTART or DTEND) can only be specified as a
1456  * UTC DATE-TIME value. So always use a time relative to DTSTART instead of
1457  * an absolute time.
1458  */
1459  ev->setDtStart(mStartDateTime.calendarKDateTime());
1460  ev->setAllDay(false);
1461  ev->setHasEndDate(false);
1462 
1463  const DateTime dtMain = archived ? mStartDateTime : mNextMainDateTime;
1464  int ancillaryType = 0; // 0 = invalid, 1 = time, 2 = offset
1465  DateTime ancillaryTime; // time for ancillary alarms (pre-action, extra audio, etc)
1466  int ancillaryOffset = 0; // start offset for ancillary alarms
1467  if (!mMainExpired || archived)
1468  {
1469  /* The alarm offset must always be zero for the main alarm. To determine
1470  * which recurrence is due, the property X-KDE-KALARM_NEXTRECUR is used.
1471  * If the alarm offset was non-zero, exception dates and rules would not
1472  * work since they apply to the event time, not the alarm time.
1473  */
1474  if (!archived && checkRecur() != KARecurrence::NO_RECUR)
1475  {
1476  QDateTime dt = mNextMainDateTime.kDateTime().toTimeSpec(mStartDateTime.timeSpec()).dateTime();
1477  ev->setCustomProperty(KACalendar::APPNAME, NEXT_RECUR_PROPERTY,
1478  dt.toString(mNextMainDateTime.isDateOnly() ? "yyyyMMdd" : "yyyyMMddThhmmss"));
1479  }
1480  // Add the main alarm
1481  initKCalAlarm(ev, 0, QStringList(), MAIN_ALARM);
1482  ancillaryOffset = 0;
1483  ancillaryType = dtMain.isValid() ? 2 : 0;
1484  }
1485  else if (mRepetition)
1486  {
1487  // Alarm repetition is normally held in the main alarm, but since
1488  // the main alarm has expired, store in a custom property.
1489  const QString param = QString("%1:%2").arg(mRepetition.intervalMinutes()).arg(mRepetition.count());
1490  ev->setCustomProperty(KACalendar::APPNAME, REPEAT_PROPERTY, param);
1491  }
1492 
1493  // Add subsidiary alarms
1494  if (mRepeatAtLogin || (mArchiveRepeatAtLogin && archived))
1495  {
1496  DateTime dtl;
1497  if (mArchiveRepeatAtLogin)
1498  dtl = mStartDateTime.calendarKDateTime().addDays(-1);
1499  else if (mAtLoginDateTime.isValid())
1500  dtl = mAtLoginDateTime;
1501  else if (mStartDateTime.isDateOnly())
1502  dtl = DateTime(KDateTime::currentLocalDate().addDays(-1), mStartDateTime.timeSpec());
1503  else
1504  dtl = KDateTime::currentUtcDateTime();
1505  initKCalAlarm(ev, dtl, QStringList(AT_LOGIN_TYPE));
1506  if (!ancillaryType && dtl.isValid())
1507  {
1508  ancillaryTime = dtl;
1509  ancillaryType = 1;
1510  }
1511  }
1512 
1513  // Find the base date/time for calculating alarm offsets
1514  DateTime nextDateTime = mNextMainDateTime;
1515  if (mMainExpired)
1516  {
1517  if (checkRecur() == KARecurrence::NO_RECUR)
1518  nextDateTime = mStartDateTime;
1519  else if (!archived)
1520  {
1521  // It's a deferral of an expired recurrence.
1522  // Need to ensure that the alarm offset is to an occurrence
1523  // which isn't excluded by an exception - otherwise, it will
1524  // never be triggered. So choose the first recurrence which
1525  // isn't an exception.
1526  KDateTime dt = mRecurrence->getNextDateTime(mStartDateTime.addDays(-1).kDateTime());
1527  dt.setDateOnly(mStartDateTime.isDateOnly());
1528  nextDateTime = dt;
1529  }
1530  }
1531 
1532  if (mReminderMinutes && (mReminderActive != NO_REMINDER || archived))
1533  {
1534  int startOffset;
1535  if (mReminderMinutes < 0 && mReminderActive != NO_REMINDER)
1536  {
1537  // A reminder AFTER the main alarm is active or disabled
1538  startOffset = nextDateTime.calendarKDateTime().secsTo(mReminderAfterTime.calendarKDateTime());
1539  }
1540  else
1541  {
1542  // A reminder BEFORE the main alarm is active
1543  startOffset = -mReminderMinutes * 60;
1544  }
1545  initKCalAlarm(ev, startOffset, QStringList(REMINDER_TYPE));
1546  // Don't set ancillary time if the reminder AFTER is hidden by a deferral
1547  if (!ancillaryType && (mReminderActive == ACTIVE_REMINDER || archived))
1548  {
1549  ancillaryOffset = startOffset;
1550  ancillaryType = 2;
1551  }
1552  }
1553  if (mDeferral != NO_DEFERRAL)
1554  {
1555  int startOffset;
1556  QStringList list;
1557  if (mDeferralTime.isDateOnly())
1558  {
1559  startOffset = nextDateTime.secsTo(mDeferralTime.calendarKDateTime());
1560  list += DATE_DEFERRAL_TYPE;
1561  }
1562  else
1563  {
1564  startOffset = nextDateTime.calendarKDateTime().secsTo(mDeferralTime.calendarKDateTime());
1565  list += TIME_DEFERRAL_TYPE;
1566  }
1567  if (mDeferral == REMINDER_DEFERRAL)
1568  list += REMINDER_TYPE;
1569  initKCalAlarm(ev, startOffset, list);
1570  if (!ancillaryType && mDeferralTime.isValid())
1571  {
1572  ancillaryOffset = startOffset;
1573  ancillaryType = 2;
1574  }
1575  }
1576  if (!mTemplateName.isEmpty())
1577  ev->setSummary(mTemplateName);
1578  else if (mDisplaying)
1579  {
1580  QStringList list(DISPLAYING_TYPE);
1581  if (mDisplayingFlags & REPEAT_AT_LOGIN)
1582  list += AT_LOGIN_TYPE;
1583  else if (mDisplayingFlags & DEFERRAL)
1584  {
1585  if (mDisplayingFlags & TIMED_FLAG)
1586  list += TIME_DEFERRAL_TYPE;
1587  else
1588  list += DATE_DEFERRAL_TYPE;
1589  }
1590  if (mDisplayingFlags & REMINDER)
1591  list += REMINDER_TYPE;
1592  initKCalAlarm(ev, mDisplayingTime, list);
1593  if (!ancillaryType && mDisplayingTime.isValid())
1594  {
1595  ancillaryTime = mDisplayingTime;
1596  ancillaryType = 1;
1597  }
1598  }
1599  if ((mBeep || mSpeak || !mAudioFile.isEmpty()) && mActionSubType != AUDIO)
1600  {
1601  // A sound is specified
1602  if (ancillaryType == 2)
1603  initKCalAlarm(ev, ancillaryOffset, QStringList(), AUDIO_ALARM);
1604  else
1605  initKCalAlarm(ev, ancillaryTime, QStringList(), AUDIO_ALARM);
1606  }
1607  if (!mPreAction.isEmpty())
1608  {
1609  // A pre-display action is specified
1610  if (ancillaryType == 2)
1611  initKCalAlarm(ev, ancillaryOffset, QStringList(PRE_ACTION_TYPE), PRE_ACTION_ALARM);
1612  else
1613  initKCalAlarm(ev, ancillaryTime, QStringList(PRE_ACTION_TYPE), PRE_ACTION_ALARM);
1614  }
1615  if (!mPostAction.isEmpty())
1616  {
1617  // A post-display action is specified
1618  if (ancillaryType == 2)
1619  initKCalAlarm(ev, ancillaryOffset, QStringList(POST_ACTION_TYPE), POST_ACTION_ALARM);
1620  else
1621  initKCalAlarm(ev, ancillaryTime, QStringList(POST_ACTION_TYPE), POST_ACTION_ALARM);
1622  }
1623 
1624  if (mRecurrence)
1625  mRecurrence->writeRecurrence(*ev->recurrence());
1626  else
1627  ev->clearRecurrence();
1628  if (mCreatedDateTime.isValid())
1629  ev->setCreated(mCreatedDateTime);
1630  ev->setReadOnly(readOnly);
1631  ev->endUpdates(); // finally issue an update notification
1632  return true;
1633 }
1634 
1635 /******************************************************************************
1636 * Create a new alarm for a libkcal event, and initialise it according to the
1637 * alarm action. If 'types' is non-null, it is appended to the X-KDE-KALARM-TYPE
1638 * property value list.
1639 * NOTE: The variant taking a DateTime calculates the offset from mStartDateTime,
1640 * which is not suitable for an alarm in a recurring event.
1641 */
1642 #ifndef KALARMCAL_USE_KRESOURCES
1643 Alarm::Ptr KAEvent::Private::initKCalAlarm(const Event::Ptr& event, const DateTime& dt, const QStringList& types, AlarmType type) const
1644 #else
1645 Alarm* KAEvent::Private::initKCalAlarm(Event* event, const DateTime& dt, const QStringList& types, AlarmType type) const
1646 #endif
1647 {
1648  const int startOffset = dt.isDateOnly() ? mStartDateTime.secsTo(dt)
1649  : mStartDateTime.calendarKDateTime().secsTo(dt.calendarKDateTime());
1650  return initKCalAlarm(event, startOffset, types, type);
1651 }
1652 
1653 #ifndef KALARMCAL_USE_KRESOURCES
1654 Alarm::Ptr KAEvent::Private::initKCalAlarm(const Event::Ptr& event, int startOffsetSecs, const QStringList& types, AlarmType type) const
1655 #else
1656 Alarm* KAEvent::Private::initKCalAlarm(Event* event, int startOffsetSecs, const QStringList& types, AlarmType type) const
1657 #endif
1658 {
1659  QStringList alltypes;
1660  QStringList flags;
1661 #ifndef KALARMCAL_USE_KRESOURCES
1662  Alarm::Ptr alarm = event->newAlarm();
1663 #else
1664  Alarm* alarm = event->newAlarm();
1665 #endif
1666  alarm->setEnabled(true);
1667  if (type != MAIN_ALARM)
1668  {
1669  // RFC2445 specifies that absolute alarm times must be stored as a UTC DATE-TIME value.
1670  // Set the alarm time as an offset to DTSTART for the reasons described in updateKCalEvent().
1671  alarm->setStartOffset(startOffsetSecs);
1672  }
1673 
1674  switch (type)
1675  {
1676  case AUDIO_ALARM:
1677  setAudioAlarm(alarm);
1678  if (mSpeak)
1679  flags << Private::SPEAK_FLAG;
1680  if (mRepeatSoundPause >= 0)
1681  {
1682  // Alarm::setSnoozeTime() sets 5 seconds if duration parameter is zero,
1683  // so repeat count = -1 represents 0 pause, -2 represents non-zero pause.
1684  alarm->setRepeatCount(mRepeatSoundPause ? -2 : -1);
1685  alarm->setSnoozeTime(Duration(mRepeatSoundPause, Duration::Seconds));
1686  }
1687  break;
1688  case PRE_ACTION_ALARM:
1689  setProcedureAlarm(alarm, mPreAction);
1690  if (mExtraActionOptions & ExecPreActOnDeferral)
1691  flags << Private::EXEC_ON_DEFERRAL_FLAG;
1692  if (mExtraActionOptions & CancelOnPreActError)
1693  flags << Private::CANCEL_ON_ERROR_FLAG;
1694  if (mExtraActionOptions & DontShowPreActError)
1695  flags << Private::DONT_SHOW_ERROR_FLAG;
1696  break;
1697  case POST_ACTION_ALARM:
1698  setProcedureAlarm(alarm, mPostAction);
1699  break;
1700  case MAIN_ALARM:
1701  alarm->setSnoozeTime(mRepetition.interval());
1702  alarm->setRepeatCount(mRepetition.count());
1703  if (mRepetition)
1704  alarm->setCustomProperty(KACalendar::APPNAME, NEXT_REPEAT_PROPERTY,
1705  QString::number(mNextRepeat));
1706  // fall through to INVALID_ALARM
1707  case REMINDER_ALARM:
1708  case INVALID_ALARM:
1709  {
1710  if (types == QStringList(REMINDER_TYPE)
1711  && mReminderMinutes < 0 && mReminderActive == HIDDEN_REMINDER)
1712  {
1713  // It's a reminder AFTER the alarm which is currently disabled
1714  // due to the main alarm being deferred past it.
1715  flags << HIDDEN_REMINDER_FLAG;
1716  }
1717  bool display = false;
1718  switch (mActionSubType)
1719  {
1720  case FILE:
1721  alltypes += FILE_TYPE;
1722  // fall through to MESSAGE
1723  case MESSAGE:
1724  alarm->setDisplayAlarm(AlarmText::toCalendarText(mText));
1725  display = true;
1726  break;
1727  case COMMAND:
1728  if (mCommandScript)
1729  alarm->setProcedureAlarm("", mText);
1730  else
1731  setProcedureAlarm(alarm, mText);
1732  display = mCommandDisplay;
1733  break;
1734  case EMAIL:
1735  alarm->setEmailAlarm(mEmailSubject, mText, mEmailAddresses, mEmailAttachments);
1736  if (mEmailFromIdentity)
1737  flags << Private::EMAIL_ID_FLAG << QString::number(mEmailFromIdentity);
1738  break;
1739  case AUDIO:
1740  setAudioAlarm(alarm);
1741  if (mRepeatSoundPause >= 0)
1742  alltypes += SOUND_REPEAT_TYPE;
1743  break;
1744  }
1745  if (display)
1746  alarm->setCustomProperty(KACalendar::APPNAME, FONT_COLOUR_PROPERTY,
1747  QString::fromLatin1("%1;%2;%3").arg(mBgColour.name())
1748  .arg(mFgColour.name())
1749  .arg(mUseDefaultFont ? QString() : mFont.toString()));
1750  break;
1751  }
1752  case DEFERRED_ALARM:
1753  case DEFERRED_REMINDER_ALARM:
1754  case AT_LOGIN_ALARM:
1755  case DISPLAYING_ALARM:
1756  break;
1757  }
1758  alltypes += types;
1759  if (!alltypes.isEmpty())
1760  alarm->setCustomProperty(KACalendar::APPNAME, TYPE_PROPERTY, alltypes.join(","));
1761  if (!flags.isEmpty())
1762  alarm->setCustomProperty(KACalendar::APPNAME, FLAGS_PROPERTY, flags.join(SC));
1763  return alarm;
1764 }
1765 
1766 bool KAEvent::isValid() const
1767 {
1768  return d->mAlarmCount && (d->mAlarmCount != 1 || !d->mRepeatAtLogin);
1769 }
1770 
1771 void KAEvent::setEnabled(bool enable)
1772 {
1773  d->mEnabled = enable;
1774 }
1775 
1776 bool KAEvent::enabled() const
1777 {
1778  return d->mEnabled;
1779 }
1780 
1781 #ifndef KALARMCAL_USE_KRESOURCES
1782 void KAEvent::setReadOnly(bool ro)
1783 {
1784  d->mReadOnly = ro;
1785 }
1786 
1787 bool KAEvent::isReadOnly() const
1788 {
1789  return d->mReadOnly;
1790 }
1791 #endif
1792 
1793 void KAEvent::setArchive()
1794 {
1795  d->mArchive = true;
1796 }
1797 
1798 bool KAEvent::toBeArchived() const
1799 {
1800  return d->mArchive;
1801 }
1802 
1803 bool KAEvent::mainExpired() const
1804 {
1805  return d->mMainExpired;
1806 }
1807 
1808 bool KAEvent::expired() const
1809 {
1810  return (d->mDisplaying && d->mMainExpired) || d->mCategory == CalEvent::ARCHIVED;
1811 }
1812 
1813 KAEvent::Flags KAEvent::flags() const
1814 {
1815  return d->flags();
1816 }
1817 
1818 KAEvent::Flags KAEvent::Private::flags() const
1819 {
1820  Flags result(0);
1821  if (mBeep) result |= BEEP;
1822  if (mRepeatSoundPause >= 0) result |= REPEAT_SOUND;
1823  if (mEmailBcc) result |= EMAIL_BCC;
1824  if (mStartDateTime.isDateOnly()) result |= ANY_TIME;
1825  if (mSpeak) result |= SPEAK;
1826  if (mRepeatAtLogin) result |= REPEAT_AT_LOGIN;
1827  if (mConfirmAck) result |= CONFIRM_ACK;
1828  if (mUseDefaultFont) result |= DEFAULT_FONT;
1829  if (mCommandScript) result |= SCRIPT;
1830  if (mCommandXterm) result |= EXEC_IN_XTERM;
1831  if (mCommandDisplay) result |= DISPLAY_COMMAND;
1832  if (mCopyToKOrganizer) result |= COPY_KORGANIZER;
1833  if (mExcludeHolidays) result |= EXCL_HOLIDAYS;
1834  if (mWorkTimeOnly) result |= WORK_TIME_ONLY;
1835  if (mReminderOnceOnly) result |= REMINDER_ONCE;
1836  if (mAutoClose) result |= AUTO_CLOSE;
1837  if (!mEnabled) result |= DISABLED;
1838  return result;
1839 }
1840 
1841 /******************************************************************************
1842 * Change the type of an event.
1843 * If it is being set to archived, set the archived indication in the event ID;
1844 * otherwise, remove the archived indication from the event ID.
1845 */
1846 void KAEvent::setCategory(CalEvent::Type s)
1847 {
1848  d->setCategory(s);
1849 }
1850 
1851 void KAEvent::Private::setCategory(CalEvent::Type s)
1852 {
1853  if (s == mCategory)
1854  return;
1855  mEventID = CalEvent::uid(mEventID, s);
1856  mCategory = s;
1857  mTriggerChanged = true; // templates and archived don't have trigger times
1858 }
1859 
1860 CalEvent::Type KAEvent::category() const
1861 {
1862  return d->mCategory;
1863 }
1864 
1865 void KAEvent::setEventId(const QString& id)
1866 {
1867  d->mEventID = id;
1868 }
1869 
1870 QString KAEvent::id() const
1871 {
1872  return d->mEventID;
1873 }
1874 
1875 void KAEvent::incrementRevision()
1876 {
1877  ++d->mRevision;
1878 }
1879 
1880 int KAEvent::revision() const
1881 {
1882  return d->mRevision;
1883 }
1884 
1885 #ifndef KALARMCAL_USE_KRESOURCES
1886 void KAEvent::setCollectionId(Akonadi::Collection::Id id)
1887 {
1888  d->mCollectionId = id;
1889 }
1890 
1891 void KAEvent::setCollectionId_const(Akonadi::Collection::Id id) const
1892 {
1893  d->mCollectionId = id;
1894 }
1895 
1896 Akonadi::Collection::Id KAEvent::collectionId() const
1897 {
1898  // A displaying alarm contains the event's original collection ID
1899  return d->mDisplaying ? -1 : d->mCollectionId;
1900 }
1901 
1902 void KAEvent::setItemId(Akonadi::Item::Id id)
1903 {
1904  d->mItemId = id;
1905 }
1906 
1907 Akonadi::Item::Id KAEvent::itemId() const
1908 {
1909  return d->mItemId;
1910 }
1911 
1912 /******************************************************************************
1913 * Initialise an Item with the event.
1914 * Note that the event is not updated with the Item ID.
1915 * Reply = true if successful,
1916 * false if event's category does not match collection's mime types.
1917 */
1918 bool KAEvent::setItemPayload(Akonadi::Item& item, const QStringList& collectionMimeTypes) const
1919 {
1920  QString mimetype;
1921  switch (d->mCategory)
1922  {
1923  case CalEvent::ACTIVE: mimetype = MIME_ACTIVE; break;
1924  case CalEvent::ARCHIVED: mimetype = MIME_ARCHIVED; break;
1925  case CalEvent::TEMPLATE: mimetype = MIME_TEMPLATE; break;
1926  default: Q_ASSERT(0); return false;
1927  }
1928  if (!collectionMimeTypes.contains(mimetype))
1929  return false;
1930  item.setMimeType(mimetype);
1931  item.setPayload<KAEvent>(*this);
1932  return true;
1933 }
1934 
1935 void KAEvent::setCompatibility(KACalendar::Compat c)
1936 {
1937  d->mCompatibility = c;
1938 }
1939 
1940 KACalendar::Compat KAEvent::compatibility() const
1941 {
1942  return d->mCompatibility;
1943 }
1944 
1945 QMap<QByteArray, QString> KAEvent::customProperties() const
1946 {
1947  return d->mCustomProperties;
1948 }
1949 
1950 #else
1951 void KAEvent::setResource(AlarmResource* r)
1952 {
1953  d->mResource = r;
1954 }
1955 
1956 AlarmResource* KAEvent::resource() const
1957 {
1958  return d->mResource;
1959 }
1960 #endif
1961 
1962 KAEvent::SubAction KAEvent::actionSubType() const
1963 {
1964  return d->mActionSubType;
1965 }
1966 
1967 KAEvent::Actions KAEvent::actionTypes() const
1968 {
1969  switch (d->mActionSubType)
1970  {
1971  case MESSAGE:
1972  case FILE: return ACT_DISPLAY;
1973  case COMMAND: return d->mCommandDisplay ? ACT_DISPLAY_COMMAND : ACT_COMMAND;
1974  case EMAIL: return ACT_EMAIL;
1975  case AUDIO: return ACT_AUDIO;
1976  default: return ACT_NONE;
1977  }
1978 }
1979 
1980 void KAEvent::setLateCancel(int minutes)
1981 {
1982  if (d->mRepeatAtLogin)
1983  minutes = 0;
1984  d->mLateCancel = minutes;
1985  if (!minutes)
1986  d->mAutoClose = false;
1987 }
1988 
1989 int KAEvent::lateCancel() const
1990 {
1991  return d->mLateCancel;
1992 }
1993 
1994 void KAEvent::setAutoClose(bool ac)
1995 {
1996  d->mAutoClose = ac;
1997 }
1998 
1999 bool KAEvent::autoClose() const
2000 {
2001  return d->mAutoClose;
2002 }
2003 
2004 void KAEvent::setKMailSerialNumber(unsigned long n)
2005 {
2006  d->mKMailSerialNumber = n;
2007 }
2008 
2009 unsigned long KAEvent::kmailSerialNumber() const
2010 {
2011  return d->mKMailSerialNumber;
2012 }
2013 
2014 QString KAEvent::cleanText() const
2015 {
2016  return d->mText;
2017 }
2018 
2019 QString KAEvent::message() const
2020 {
2021  return (d->mActionSubType == MESSAGE
2022  || d->mActionSubType == EMAIL) ? d->mText : QString();
2023 }
2024 
2025 QString KAEvent::displayMessage() const
2026 {
2027  return (d->mActionSubType == MESSAGE) ? d->mText : QString();
2028 }
2029 
2030 QString KAEvent::fileName() const
2031 {
2032  return (d->mActionSubType == FILE) ? d->mText : QString();
2033 }
2034 
2035 QColor KAEvent::bgColour() const
2036 {
2037  return d->mBgColour;
2038 }
2039 
2040 QColor KAEvent::fgColour() const
2041 {
2042  return d->mFgColour;
2043 }
2044 
2045 void KAEvent::setDefaultFont(const QFont& f)
2046 {
2047  Private::mDefaultFont = f;
2048 }
2049 
2050 bool KAEvent::useDefaultFont() const
2051 {
2052  return d->mUseDefaultFont;
2053 }
2054 
2055 QFont KAEvent::font() const
2056 {
2057  return d->mUseDefaultFont ? Private::mDefaultFont : d->mFont;
2058 }
2059 
2060 QString KAEvent::command() const
2061 {
2062  return (d->mActionSubType == COMMAND) ? d->mText : QString();
2063 }
2064 
2065 bool KAEvent::commandScript() const
2066 {
2067  return d->mCommandScript;
2068 }
2069 
2070 bool KAEvent::commandXterm() const
2071 {
2072  return d->mCommandXterm;
2073 }
2074 
2075 bool KAEvent::commandDisplay() const
2076 {
2077  return d->mCommandDisplay;
2078 }
2079 
2080 #ifndef KALARMCAL_USE_KRESOURCES
2081 void KAEvent::setCommandError(CmdErrType t) const
2082 {
2083  d->mCommandError = t;
2084 }
2085 
2086 #else
2087 /******************************************************************************
2088 * Set the command last error status.
2089 * If 'writeConfig' is true, the status is written to the config file.
2090 */
2091 void KAEvent::setCommandError(CmdErrType t, bool writeConfig) const
2092 {
2093  d->setCommandError(t, writeConfig);
2094 }
2095 
2096 void KAEvent::Private::setCommandError(CmdErrType error, bool writeConfig) const
2097 {
2098  kDebug() << mEventID << "," << error;
2099  if (error == mCommandError)
2100  return;
2101  mCommandError = error;
2102  if (writeConfig)
2103  {
2104  KConfigGroup config(KGlobal::config(), mCmdErrConfigGroup);
2105  if (mCommandError == CMD_NO_ERROR)
2106  config.deleteEntry(mEventID);
2107  else
2108  {
2109  QString errtext;
2110  switch (mCommandError)
2111  {
2112  case CMD_ERROR: errtext = CMD_ERROR_VALUE; break;
2113  case CMD_ERROR_PRE: errtext = CMD_ERROR_PRE_VALUE; break;
2114  case CMD_ERROR_POST: errtext = CMD_ERROR_POST_VALUE; break;
2115  case CMD_ERROR_PRE_POST:
2116  errtext = CMD_ERROR_PRE_VALUE + ',' + CMD_ERROR_POST_VALUE;
2117  break;
2118  default:
2119  break;
2120  }
2121  config.writeEntry(mEventID, errtext);
2122  }
2123  config.sync();
2124  }
2125 }
2126 
2127 /******************************************************************************
2128 * Initialise the command last error status of the alarm from the config file.
2129 */
2130 void KAEvent::setCommandError(const QString& configString)
2131 {
2132  d->setCommandError(configString);
2133 }
2134 
2135 void KAEvent::Private::setCommandError(const QString& configString)
2136 {
2137  mCommandError = CMD_NO_ERROR;
2138  const QStringList errs = configString.split(',');
2139  if (errs.indexOf(CMD_ERROR_VALUE) >= 0)
2140  mCommandError = CMD_ERROR;
2141  else
2142  {
2143  if (errs.indexOf(CMD_ERROR_PRE_VALUE) >= 0)
2144  mCommandError = CMD_ERROR_PRE;
2145  if (errs.indexOf(CMD_ERROR_POST_VALUE) >= 0)
2146  mCommandError = static_cast<CmdErrType>(mCommandError | CMD_ERROR_POST);
2147  }
2148 }
2149 
2150 QString KAEvent::commandErrorConfigGroup()
2151 {
2152  return Private::mCmdErrConfigGroup;
2153 }
2154 #endif
2155 
2156 KAEvent::CmdErrType KAEvent::commandError() const
2157 {
2158  return d->mCommandError;
2159 }
2160 
2161 void KAEvent::setLogFile(const QString& logfile)
2162 {
2163  d->mLogFile = logfile;
2164  if (!logfile.isEmpty())
2165  d->mCommandDisplay = d->mCommandXterm = false;
2166 }
2167 
2168 QString KAEvent::logFile() const
2169 {
2170  return d->mLogFile;
2171 }
2172 
2173 bool KAEvent::confirmAck() const
2174 {
2175  return d->mConfirmAck;
2176 }
2177 
2178 bool KAEvent::copyToKOrganizer() const
2179 {
2180  return d->mCopyToKOrganizer;
2181 }
2182 
2183 #ifndef KALARMCAL_USE_KRESOURCES
2184 void KAEvent::setEmail(uint from, const KCalCore::Person::List& addresses, const QString& subject,
2185  const QStringList& attachments)
2186 #else
2187 void KAEvent::setEmail(uint from, const QList<KCal::Person>& addresses, const QString& subject,
2188  const QStringList& attachments)
2189 #endif
2190 {
2191  d->mEmailFromIdentity = from;
2192  d->mEmailAddresses = addresses;
2193  d->mEmailSubject = subject;
2194  d->mEmailAttachments = attachments;
2195 }
2196 
2197 QString KAEvent::emailMessage() const
2198 {
2199  return (d->mActionSubType == EMAIL) ? d->mText : QString();
2200 }
2201 
2202 uint KAEvent::emailFromId() const
2203 {
2204  return d->mEmailFromIdentity;
2205 }
2206 
2207 #ifndef KALARMCAL_USE_KRESOURCES
2208 KCalCore::Person::List KAEvent::emailAddressees() const
2209 #else
2210 QList<KCal::Person> KAEvent::emailAddressees() const
2211 #endif
2212 {
2213  return d->mEmailAddresses;
2214 }
2215 
2216 QStringList KAEvent::emailAddresses() const
2217 {
2218  return static_cast<QStringList>(d->mEmailAddresses);
2219 }
2220 
2221 QString KAEvent::emailAddresses(const QString& sep) const
2222 {
2223  return d->mEmailAddresses.join(sep);
2224 }
2225 
2226 #ifndef KALARMCAL_USE_KRESOURCES
2227 QString KAEvent::joinEmailAddresses(const KCalCore::Person::List& addresses, const QString& separator)
2228 #else
2229 QString KAEvent::joinEmailAddresses(const QList<KCal::Person>& addresses, const QString& separator)
2230 #endif
2231 {
2232  return EmailAddressList(addresses).join(separator);
2233 }
2234 
2235 QStringList KAEvent::emailPureAddresses() const
2236 {
2237  return d->mEmailAddresses.pureAddresses();
2238 }
2239 
2240 QString KAEvent::emailPureAddresses(const QString& sep) const
2241 {
2242  return d->mEmailAddresses.pureAddresses(sep);
2243 }
2244 
2245 QString KAEvent::emailSubject() const
2246 {
2247  return d->mEmailSubject;
2248 }
2249 
2250 QStringList KAEvent::emailAttachments() const
2251 {
2252  return d->mEmailAttachments;
2253 }
2254 
2255 QString KAEvent::emailAttachments(const QString& sep) const
2256 {
2257  return d->mEmailAttachments.join(sep);
2258 }
2259 
2260 bool KAEvent::emailBcc() const
2261 {
2262  return d->mEmailBcc;
2263 }
2264 
2265 void KAEvent::setAudioFile(const QString& filename, float volume, float fadeVolume, int fadeSeconds, int repeatPause, bool allowEmptyFile)
2266 {
2267  d->setAudioFile(filename, volume, fadeVolume, fadeSeconds, repeatPause, allowEmptyFile);
2268 }
2269 
2270 void KAEvent::Private::setAudioFile(const QString& filename, float volume, float fadeVolume, int fadeSeconds, int repeatPause, bool allowEmptyFile)
2271 {
2272  mAudioFile = filename;
2273  mSoundVolume = (!allowEmptyFile && filename.isEmpty()) ? -1 : volume;
2274  if (mSoundVolume >= 0)
2275  {
2276  mFadeVolume = (fadeSeconds > 0) ? fadeVolume : -1;
2277  mFadeSeconds = (mFadeVolume >= 0) ? fadeSeconds : 0;
2278  }
2279  else
2280  {
2281  mFadeVolume = -1;
2282  mFadeSeconds = 0;
2283  }
2284  mRepeatSoundPause = repeatPause;
2285 }
2286 
2287 QString KAEvent::audioFile() const
2288 {
2289  return d->mAudioFile;
2290 }
2291 
2292 float KAEvent::soundVolume() const
2293 {
2294  return d->mSoundVolume;
2295 }
2296 
2297 float KAEvent::fadeVolume() const
2298 {
2299  return d->mSoundVolume >= 0 && d->mFadeSeconds ? d->mFadeVolume : -1;
2300 }
2301 
2302 int KAEvent::fadeSeconds() const
2303 {
2304  return d->mSoundVolume >= 0 && d->mFadeVolume >= 0 ? d->mFadeSeconds : 0;
2305 }
2306 
2307 bool KAEvent::repeatSound() const
2308 {
2309  return d->mRepeatSoundPause >= 0;
2310 }
2311 
2312 int KAEvent::repeatSoundPause() const
2313 {
2314  return d->mRepeatSoundPause;
2315 }
2316 
2317 bool KAEvent::beep() const
2318 {
2319  return d->mBeep;
2320 }
2321 
2322 bool KAEvent::speak() const
2323 {
2324  return (d->mActionSubType == MESSAGE
2325  || (d->mActionSubType == COMMAND && d->mCommandDisplay))
2326  && d->mSpeak;
2327 }
2328 
2329 /******************************************************************************
2330 * Set the event to be an alarm template.
2331 */
2332 void KAEvent::setTemplate(const QString& name, int afterTime)
2333 {
2334  d->setCategory(CalEvent::TEMPLATE);
2335  d->mTemplateName = name;
2336  d->mTemplateAfterTime = afterTime;
2337  d->mTriggerChanged = true; // templates and archived don't have trigger times
2338 }
2339 
2340 bool KAEvent::isTemplate() const
2341 {
2342  return !d->mTemplateName.isEmpty();
2343 }
2344 
2345 QString KAEvent::templateName() const
2346 {
2347  return d->mTemplateName;
2348 }
2349 
2350 bool KAEvent::usingDefaultTime() const
2351 {
2352  return d->mTemplateAfterTime == 0;
2353 }
2354 
2355 int KAEvent::templateAfterTime() const
2356 {
2357  return d->mTemplateAfterTime;
2358 }
2359 
2360 void KAEvent::setActions(const QString& pre, const QString& post, ExtraActionOptions options)
2361 {
2362  d->mPreAction = pre;
2363  d->mPostAction = post;
2364  d->mExtraActionOptions = options;
2365 }
2366 
2367 void KAEvent::setActions(const QString& pre, const QString& post, bool cancelOnError, bool dontShowError)
2368 {
2369  ExtraActionOptions opts(0);
2370  if (cancelOnError)
2371  opts |= CancelOnPreActError;
2372  if (dontShowError)
2373  opts |= DontShowPreActError;
2374  setActions(pre, post, opts);
2375 }
2376 
2377 QString KAEvent::preAction() const
2378 {
2379  return d->mPreAction;
2380 }
2381 
2382 QString KAEvent::postAction() const
2383 {
2384  return d->mPostAction;
2385 }
2386 
2387 KAEvent::ExtraActionOptions KAEvent::extraActionOptions() const
2388 {
2389  return d->mExtraActionOptions;
2390 }
2391 
2392 bool KAEvent::cancelOnPreActionError() const
2393 {
2394  return d->mExtraActionOptions & CancelOnPreActError;
2395 }
2396 
2397 bool KAEvent::dontShowPreActionError() const
2398 {
2399  return d->mExtraActionOptions & DontShowPreActError;
2400 }
2401 
2402 /******************************************************************************
2403 * Set a reminder.
2404 * 'minutes' = number of minutes BEFORE the main alarm.
2405 */
2406 void KAEvent::setReminder(int minutes, bool onceOnly)
2407 {
2408  d->setReminder(minutes, onceOnly);
2409 }
2410 
2411 void KAEvent::Private::setReminder(int minutes, bool onceOnly)
2412 {
2413  if (minutes > 0 && mRepeatAtLogin)
2414  minutes = 0;
2415  if (minutes != mReminderMinutes || (minutes && mReminderActive != ACTIVE_REMINDER))
2416  {
2417  if (minutes && mReminderActive == NO_REMINDER)
2418  ++mAlarmCount;
2419  else if (!minutes && mReminderActive != NO_REMINDER)
2420  --mAlarmCount;
2421  mReminderMinutes = minutes;
2422  mReminderActive = minutes ? ACTIVE_REMINDER : NO_REMINDER;
2423  mReminderOnceOnly = onceOnly;
2424  mReminderAfterTime = DateTime();
2425  mTriggerChanged = true;
2426  }
2427 }
2428 
2429 /******************************************************************************
2430 * Activate the event's reminder which occurs AFTER the given main alarm time.
2431 * Reply = true if successful (i.e. reminder falls before the next main alarm).
2432 */
2433 void KAEvent::activateReminderAfter(const DateTime& mainAlarmTime)
2434 {
2435  d->activateReminderAfter(mainAlarmTime);
2436 }
2437 
2438 void KAEvent::Private::activateReminderAfter(const DateTime& mainAlarmTime)
2439 {
2440  if (mReminderMinutes >= 0 || mReminderActive == ACTIVE_REMINDER || !mainAlarmTime.isValid())
2441  return;
2442  // There is a reminder AFTER the main alarm.
2443  if (checkRecur() != KARecurrence::NO_RECUR)
2444  {
2445  // For a recurring alarm, the given alarm time must be a recurrence, not a sub-repetition.
2446  DateTime next;
2447  //???? For some unknown reason, addSecs(-1) returns the recurrence after the next,
2448  //???? so addSecs(-60) is used instead.
2449  if (nextRecurrence(mainAlarmTime.addSecs(-60).effectiveKDateTime(), next) == NO_OCCURRENCE
2450  || mainAlarmTime != next)
2451  return;
2452  }
2453  else if (!mRepeatAtLogin)
2454  {
2455  // For a non-recurring alarm, the given alarm time must be the main alarm time.
2456  if (mainAlarmTime != mStartDateTime)
2457  return;
2458  }
2459 
2460  const DateTime reminderTime = mainAlarmTime.addMins(-mReminderMinutes);
2461  DateTime next;
2462  if (nextOccurrence(mainAlarmTime.effectiveKDateTime(), next, RETURN_REPETITION) != NO_OCCURRENCE
2463  && reminderTime >= next)
2464  return; // the reminder time is after the next occurrence of the main alarm
2465 
2466  kDebug() << "Setting reminder at" << reminderTime.effectiveKDateTime().dateTime();
2467  activate_reminder(true);
2468  mReminderAfterTime = reminderTime;
2469 }
2470 
2471 int KAEvent::reminderMinutes() const
2472 {
2473  return d->mReminderMinutes;
2474 }
2475 
2476 bool KAEvent::reminderActive() const
2477 {
2478  return d->mReminderActive == Private::ACTIVE_REMINDER;
2479 }
2480 
2481 bool KAEvent::reminderOnceOnly() const
2482 {
2483  return d->mReminderOnceOnly;
2484 }
2485 
2486 bool KAEvent::reminderDeferral() const
2487 {
2488  return d->mDeferral == Private::REMINDER_DEFERRAL;
2489 }
2490 
2491 /******************************************************************************
2492 * Defer the event to the specified time.
2493 * If the main alarm time has passed, the main alarm is marked as expired.
2494 * If 'adjustRecurrence' is true, ensure that the next scheduled recurrence is
2495 * after the current time.
2496 */
2497 void KAEvent::defer(const DateTime& dt, bool reminder, bool adjustRecurrence)
2498 {
2499  return d->defer(dt, reminder, adjustRecurrence);
2500 }
2501 
2502 void KAEvent::Private::defer(const DateTime& dateTime, bool reminder, bool adjustRecurrence)
2503 {
2504  startChanges(); // prevent multiple trigger time evaluation here
2505  bool setNextRepetition = false;
2506  bool checkRepetition = false;
2507  bool checkReminderAfter = false;
2508  if (checkRecur() == KARecurrence::NO_RECUR)
2509  {
2510  // Deferring a non-recurring alarm
2511  if (mReminderMinutes)
2512  {
2513  bool deferReminder = false;
2514  if (mReminderMinutes > 0)
2515  {
2516  // There's a reminder BEFORE the main alarm
2517  if (dateTime < mNextMainDateTime.effectiveKDateTime())
2518  deferReminder = true;
2519  else if (mReminderActive == ACTIVE_REMINDER || mDeferral == REMINDER_DEFERRAL)
2520  {
2521  // Deferring past the main alarm time, so adjust any existing deferral
2522  set_deferral(NO_DEFERRAL);
2523  mTriggerChanged = true;
2524  }
2525  }
2526  else if (mReminderMinutes < 0 && reminder)
2527  deferReminder = true; // deferring a reminder AFTER the main alarm
2528  if (deferReminder)
2529  {
2530  set_deferral(REMINDER_DEFERRAL); // defer reminder alarm
2531  mDeferralTime = dateTime;
2532  mTriggerChanged = true;
2533  }
2534  if (mReminderActive == ACTIVE_REMINDER)
2535  {
2536  activate_reminder(false);
2537  mTriggerChanged = true;
2538  }
2539  }
2540  if (mDeferral != REMINDER_DEFERRAL)
2541  {
2542  // We're deferring the main alarm.
2543  // Main alarm has now expired.
2544  mNextMainDateTime = mDeferralTime = dateTime;
2545  set_deferral(NORMAL_DEFERRAL);
2546  mTriggerChanged = true;
2547  checkReminderAfter = true;
2548  if (!mMainExpired)
2549  {
2550  // Mark the alarm as expired now
2551  mMainExpired = true;
2552  --mAlarmCount;
2553  if (mRepeatAtLogin)
2554  {
2555  // Remove the repeat-at-login alarm, but keep a note of it for archiving purposes
2556  mArchiveRepeatAtLogin = true;
2557  mRepeatAtLogin = false;
2558  --mAlarmCount;
2559  }
2560  }
2561  }
2562  }
2563  else if (reminder)
2564  {
2565  // Deferring a reminder for a recurring alarm
2566  if (dateTime >= mNextMainDateTime.effectiveKDateTime())
2567  {
2568  // Trying to defer it past the next main alarm (regardless of whether
2569  // the reminder triggered before or after the main alarm).
2570  set_deferral(NO_DEFERRAL); // (error)
2571  }
2572  else
2573  {
2574  set_deferral(REMINDER_DEFERRAL);
2575  mDeferralTime = dateTime;
2576  checkRepetition = true;
2577  }
2578  mTriggerChanged = true;
2579  }
2580  else
2581  {
2582  // Deferring a recurring alarm
2583  mDeferralTime = dateTime;
2584  if (mDeferral == NO_DEFERRAL)
2585  set_deferral(NORMAL_DEFERRAL);
2586  mTriggerChanged = true;
2587  checkReminderAfter = true;
2588  if (adjustRecurrence)
2589  {
2590  const KDateTime now = KDateTime::currentUtcDateTime();
2591  if (mainEndRepeatTime() < now)
2592  {
2593  // The last repetition (if any) of the current recurrence has already passed.
2594  // Adjust to the next scheduled recurrence after now.
2595  if (!mMainExpired && setNextOccurrence(now) == NO_OCCURRENCE)
2596  {
2597  mMainExpired = true;
2598  --mAlarmCount;
2599  }
2600  }
2601  else
2602  setNextRepetition = mRepetition;
2603  }
2604  else
2605  checkRepetition = true;
2606  }
2607  if (checkReminderAfter && mReminderMinutes < 0 && mReminderActive != NO_REMINDER)
2608  {
2609  // Enable/disable the active reminder AFTER the main alarm,
2610  // depending on whether the deferral is before or after the reminder.
2611  mReminderActive = (mDeferralTime < mReminderAfterTime) ? ACTIVE_REMINDER : HIDDEN_REMINDER;
2612  }
2613  if (checkRepetition)
2614  setNextRepetition = (mRepetition && mDeferralTime < mainEndRepeatTime());
2615  if (setNextRepetition)
2616  {
2617  // The alarm is repeated, and we're deferring to a time before the last repetition.
2618  // Set the next scheduled repetition to the one after the deferral.
2619  if (mNextMainDateTime >= mDeferralTime)
2620  mNextRepeat = 0;
2621  else
2622  mNextRepeat = mRepetition.nextRepeatCount(mNextMainDateTime.kDateTime(), mDeferralTime.kDateTime());
2623  mTriggerChanged = true;
2624  }
2625  endChanges();
2626 }
2627 
2628 /******************************************************************************
2629 * Cancel any deferral alarm.
2630 */
2631 void KAEvent::cancelDefer()
2632 {
2633  d->cancelDefer();
2634 }
2635 
2636 void KAEvent::Private::cancelDefer()
2637 {
2638  if (mDeferral != NO_DEFERRAL)
2639  {
2640  mDeferralTime = DateTime();
2641  set_deferral(NO_DEFERRAL);
2642  mTriggerChanged = true;
2643  }
2644 }
2645 
2646 void KAEvent::setDeferDefaultMinutes(int minutes, bool dateOnly)
2647 {
2648  d->mDeferDefaultMinutes = minutes;
2649  d->mDeferDefaultDateOnly = dateOnly;
2650 }
2651 
2652 bool KAEvent::deferred() const
2653 {
2654  return d->mDeferral > 0;
2655 }
2656 
2657 DateTime KAEvent::deferDateTime() const
2658 {
2659  return d->mDeferralTime;
2660 }
2661 
2662 /******************************************************************************
2663 * Find the latest time which the alarm can currently be deferred to.
2664 */
2665 DateTime KAEvent::deferralLimit(DeferLimitType* limitType) const
2666 {
2667  return d->deferralLimit(limitType);
2668 }
2669 
2670 DateTime KAEvent::Private::deferralLimit(DeferLimitType* limitType) const
2671 {
2672  DeferLimitType ltype = LIMIT_NONE;
2673  DateTime endTime;
2674  if (checkRecur() != KARecurrence::NO_RECUR)
2675  {
2676  // It's a recurring alarm. Find the latest time it can be deferred to:
2677  // it cannot be deferred past its next occurrence or sub-repetition,
2678  // or any advance reminder before that.
2679  DateTime reminderTime;
2680  const KDateTime now = KDateTime::currentUtcDateTime();
2681  const OccurType type = nextOccurrence(now, endTime, RETURN_REPETITION);
2682  if (type & OCCURRENCE_REPEAT)
2683  ltype = LIMIT_REPETITION;
2684  else if (type == NO_OCCURRENCE)
2685  ltype = LIMIT_NONE;
2686  else if (mReminderActive == ACTIVE_REMINDER && mReminderMinutes > 0
2687  && (now < (reminderTime = endTime.addMins(-mReminderMinutes))))
2688  {
2689  endTime = reminderTime;
2690  ltype = LIMIT_REMINDER;
2691  }
2692  else
2693  ltype = LIMIT_RECURRENCE;
2694  }
2695  else if (mReminderMinutes < 0)
2696  {
2697  // There is a reminder alarm which occurs AFTER the main alarm.
2698  // Don't allow the reminder to be deferred past the next main alarm time.
2699  if (KDateTime::currentUtcDateTime() < mNextMainDateTime.effectiveKDateTime())
2700  {
2701  endTime = mNextMainDateTime;
2702  ltype = LIMIT_MAIN;
2703  }
2704  }
2705  else if (mReminderMinutes > 0
2706  && KDateTime::currentUtcDateTime() < mNextMainDateTime.effectiveKDateTime())
2707  {
2708  // It's a reminder BEFORE the main alarm.
2709  // Don't allow it to be deferred past its main alarm time.
2710  endTime = mNextMainDateTime;
2711  ltype = LIMIT_MAIN;
2712  }
2713  if (ltype != LIMIT_NONE)
2714  endTime = endTime.addMins(-1);
2715  if (limitType)
2716  *limitType = ltype;
2717  return endTime;
2718 }
2719 
2720 int KAEvent::deferDefaultMinutes() const
2721 {
2722  return d->mDeferDefaultMinutes;
2723 }
2724 
2725 bool KAEvent::deferDefaultDateOnly() const
2726 {
2727  return d->mDeferDefaultDateOnly;
2728 }
2729 
2730 DateTime KAEvent::startDateTime() const
2731 {
2732  return d->mStartDateTime;
2733 }
2734 
2735 void KAEvent::setTime(const KDateTime& dt)
2736 {
2737  d->mNextMainDateTime = dt;
2738  d->mTriggerChanged = true;
2739 }
2740 
2741 DateTime KAEvent::mainDateTime(bool withRepeats) const
2742 {
2743  return d->mainDateTime(withRepeats);
2744 }
2745 
2746 QTime KAEvent::mainTime() const
2747 {
2748  return d->mNextMainDateTime.effectiveTime();
2749 }
2750 
2751 DateTime KAEvent::mainEndRepeatTime() const
2752 {
2753  return d->mainEndRepeatTime();
2754 }
2755 
2756 /******************************************************************************
2757 * Set the start-of-day time for date-only alarms.
2758 */
2759 void KAEvent::setStartOfDay(const QTime& startOfDay)
2760 {
2761  DateTime::setStartOfDay(startOfDay);
2762 #ifdef __GNUC__
2763 #warning Does this need all trigger times for date-only alarms to be recalculated?
2764 #endif
2765 }
2766 
2767 /******************************************************************************
2768 * Called when the user changes the start-of-day time.
2769 * Adjust the start time of the recurrence to match, for each date-only event in
2770 * a list.
2771 */
2772 void KAEvent::adjustStartOfDay(const KAEvent::List& events)
2773 {
2774  for (int i = 0, end = events.count(); i < end; ++i)
2775  {
2776  Private* const p = events[i]->d;
2777  if (p->mStartDateTime.isDateOnly() && p->checkRecur() != KARecurrence::NO_RECUR)
2778  p->mRecurrence->setStartDateTime(p->mStartDateTime.effectiveKDateTime(), true);
2779  }
2780 }
2781 
2782 DateTime KAEvent::nextTrigger(TriggerType type) const
2783 {
2784  d->calcTriggerTimes();
2785  switch (type)
2786  {
2787  case ALL_TRIGGER: return d->mAllTrigger;
2788  case MAIN_TRIGGER: return d->mMainTrigger;
2789  case ALL_WORK_TRIGGER: return d->mAllWorkTrigger;
2790  case WORK_TRIGGER: return d->mMainWorkTrigger;
2791  case DISPLAY_TRIGGER:
2792  {
2793  const bool reminderAfter = d->mMainExpired && d->mReminderActive && d->mReminderMinutes < 0;
2794  return d->checkRecur() != KARecurrence::NO_RECUR && (d->mWorkTimeOnly || d->mExcludeHolidays)
2795  ? (reminderAfter ? d->mAllWorkTrigger : d->mMainWorkTrigger)
2796  : (reminderAfter ? d->mAllTrigger : d->mMainTrigger);
2797  }
2798  default: return DateTime();
2799  }
2800 }
2801 
2802 void KAEvent::setCreatedDateTime(const KDateTime& dt)
2803 {
2804  d->mCreatedDateTime = dt;
2805 }
2806 
2807 KDateTime KAEvent::createdDateTime() const
2808 {
2809  return d->mCreatedDateTime;
2810 }
2811 
2812 /******************************************************************************
2813 * Set or clear repeat-at-login.
2814 */
2815 void KAEvent::setRepeatAtLogin(bool rl)
2816 {
2817  d->setRepeatAtLogin(rl);
2818 }
2819 
2820 void KAEvent::Private::setRepeatAtLogin(bool rl)
2821 {
2822  if (rl && !mRepeatAtLogin)
2823  {
2824  setRepeatAtLoginTrue(true); // clear incompatible statuses
2825  ++mAlarmCount;
2826  }
2827  else if (!rl && mRepeatAtLogin)
2828  --mAlarmCount;
2829  mRepeatAtLogin = rl;
2830  mTriggerChanged = true;
2831 }
2832 
2833 /******************************************************************************
2834 * Clear incompatible statuses when repeat-at-login is set.
2835 */
2836 void KAEvent::Private::setRepeatAtLoginTrue(bool clearReminder)
2837 {
2838  clearRecur(); // clear recurrences
2839  if (mReminderMinutes >= 0 && clearReminder)
2840  setReminder(0, false); // clear pre-alarm reminder
2841  mLateCancel = 0;
2842  mAutoClose = false;
2843  mCopyToKOrganizer = false;
2844 }
2845 
2846 bool KAEvent::repeatAtLogin(bool includeArchived) const
2847 {
2848  return d->mRepeatAtLogin || (includeArchived && d->mArchiveRepeatAtLogin);
2849 }
2850 
2851 void KAEvent::setExcludeHolidays(bool ex)
2852 {
2853  d->mExcludeHolidays = ex ? Private::mHolidays : 0;
2854  // Option only affects recurring alarms
2855  d->mTriggerChanged = (d->checkRecur() != KARecurrence::NO_RECUR);
2856 }
2857 
2858 bool KAEvent::holidaysExcluded() const
2859 {
2860  return d->mExcludeHolidays;
2861 }
2862 
2863 /******************************************************************************
2864 * Set a new holiday region.
2865 * Alarms which exclude holidays record the pointer to the holiday definition
2866 * at the time their next trigger times were last calculated. The change in
2867 * holiday definition pointer will cause their next trigger times to be
2868 * recalculated.
2869 */
2870 void KAEvent::setHolidays(const HolidayRegion& h)
2871 {
2872  Private::mHolidays = &h;
2873 }
2874 
2875 void KAEvent::setWorkTimeOnly(bool wto)
2876 {
2877  d->mWorkTimeOnly = wto;
2878  // Option only affects recurring alarms
2879  d->mTriggerChanged = (d->checkRecur() != KARecurrence::NO_RECUR);
2880 }
2881 
2882 bool KAEvent::workTimeOnly() const
2883 {
2884  return d->mWorkTimeOnly;
2885 }
2886 
2887 /******************************************************************************
2888 * Check whether a date/time is during working hours and/or holidays, depending
2889 * on the flags set for the specified event.
2890 */
2891 bool KAEvent::isWorkingTime(const KDateTime& dt) const
2892 {
2893  return d->isWorkingTime(dt);
2894 }
2895 
2896 bool KAEvent::Private::isWorkingTime(const KDateTime& dt) const
2897 {
2898  if ((mWorkTimeOnly && !mWorkDays.testBit(dt.date().dayOfWeek() - 1))
2899  || (mExcludeHolidays && mHolidays && mHolidays->isHoliday(dt.date())))
2900  return false;
2901  if (!mWorkTimeOnly)
2902  return true;
2903  return dt.isDateOnly()
2904  || (dt.time() >= mWorkDayStart && dt.time() < mWorkDayEnd);
2905 }
2906 
2907 /******************************************************************************
2908 * Set new working days and times.
2909 * Increment a counter so that working-time-only alarms can detect that they
2910 * need to update their next trigger time.
2911 */
2912 void KAEvent::setWorkTime(const QBitArray& days, const QTime& start, const QTime& end)
2913 {
2914  if (days != Private::mWorkDays || start != Private::mWorkDayStart || end != Private::mWorkDayEnd)
2915  {
2916  Private::mWorkDays = days;
2917  Private::mWorkDayStart = start;
2918  Private::mWorkDayEnd = end;
2919  if (!++Private::mWorkTimeIndex)
2920  ++Private::mWorkTimeIndex;
2921  }
2922 }
2923 
2924 /******************************************************************************
2925 * Clear the event's recurrence and alarm repetition data.
2926 */
2927 void KAEvent::setNoRecur()
2928 {
2929  d->clearRecur();
2930 }
2931 
2932 void KAEvent::Private::clearRecur()
2933 {
2934  if (mRecurrence || mRepetition)
2935  {
2936  delete mRecurrence;
2937  mRecurrence = 0;
2938  mRepetition.set(0, 0);
2939  mTriggerChanged = true;
2940  }
2941  mNextRepeat = 0;
2942 }
2943 
2944 /******************************************************************************
2945 * Initialise the event's recurrence from a KCal::Recurrence.
2946 * The event's start date/time is not changed.
2947 */
2948 void KAEvent::setRecurrence(const KARecurrence& recurrence)
2949 {
2950  d->setRecurrence(recurrence);
2951 }
2952 
2953 void KAEvent::Private::setRecurrence(const KARecurrence& recurrence)
2954 {
2955  startChanges(); // prevent multiple trigger time evaluation here
2956  delete mRecurrence;
2957  if (recurrence.recurs())
2958  {
2959  mRecurrence = new KARecurrence(recurrence);
2960  mRecurrence->setStartDateTime(mStartDateTime.effectiveKDateTime(), mStartDateTime.isDateOnly());
2961  mTriggerChanged = true;
2962  }
2963  else
2964  {
2965  if (mRecurrence)
2966  mTriggerChanged = true;
2967  mRecurrence = 0;
2968  }
2969 
2970  // Adjust sub-repetition values to fit the recurrence.
2971  setRepetition(mRepetition);
2972 
2973  endChanges();
2974 }
2975 
2976 /******************************************************************************
2977 * Set the recurrence to recur at a minutes interval.
2978 * Parameters:
2979 * freq = how many minutes between recurrences.
2980 * count = number of occurrences, including first and last.
2981 * = -1 to recur indefinitely.
2982 * = 0 to use 'end' instead.
2983 * end = end date/time (invalid to use 'count' instead).
2984 * Reply = false if no recurrence was set up.
2985 */
2986 bool KAEvent::setRecurMinutely(int freq, int count, const KDateTime& end)
2987 {
2988  const bool success = d->setRecur(RecurrenceRule::rMinutely, freq, count, end);
2989  d->mTriggerChanged = true;
2990  return success;
2991 }
2992 
2993 /******************************************************************************
2994 * Set the recurrence to recur daily.
2995 * Parameters:
2996 * freq = how many days between recurrences.
2997 * days = which days of the week alarms are allowed to occur on.
2998 * count = number of occurrences, including first and last.
2999 * = -1 to recur indefinitely.
3000 * = 0 to use 'end' instead.
3001 * end = end date (invalid to use 'count' instead).
3002 * Reply = false if no recurrence was set up.
3003 */
3004 bool KAEvent::setRecurDaily(int freq, const QBitArray& days, int count, const QDate& end)
3005 {
3006  const bool success = d->setRecur(RecurrenceRule::rDaily, freq, count, end);
3007  if (success)
3008  {
3009  int n = 0;
3010  for (int i = 0; i < 7; ++i)
3011  {
3012  if (days.testBit(i))
3013  ++n;
3014  }
3015  if (n < 7)
3016  d->mRecurrence->addWeeklyDays(days);
3017  }
3018  d->mTriggerChanged = true;
3019  return success;
3020 }
3021 
3022 /******************************************************************************
3023 * Set the recurrence to recur weekly, on the specified weekdays.
3024 * Parameters:
3025 * freq = how many weeks between recurrences.
3026 * days = which days of the week alarms should occur on.
3027 * count = number of occurrences, including first and last.
3028 * = -1 to recur indefinitely.
3029 * = 0 to use 'end' instead.
3030 * end = end date (invalid to use 'count' instead).
3031 * Reply = false if no recurrence was set up.
3032 */
3033 bool KAEvent::setRecurWeekly(int freq, const QBitArray& days, int count, const QDate& end)
3034 {
3035  const bool success = d->setRecur(RecurrenceRule::rWeekly, freq, count, end);
3036  if (success)
3037  d->mRecurrence->addWeeklyDays(days);
3038  d->mTriggerChanged = true;
3039  return success;
3040 }
3041 
3042 /******************************************************************************
3043 * Set the recurrence to recur monthly, on the specified days within the month.
3044 * Parameters:
3045 * freq = how many months between recurrences.
3046 * days = which days of the month alarms should occur on.
3047 * count = number of occurrences, including first and last.
3048 * = -1 to recur indefinitely.
3049 * = 0 to use 'end' instead.
3050 * end = end date (invalid to use 'count' instead).
3051 * Reply = false if no recurrence was set up.
3052 */
3053 bool KAEvent::setRecurMonthlyByDate(int freq, const QVector<int>& days, int count, const QDate& end)
3054 {
3055  const bool success = d->setRecur(RecurrenceRule::rMonthly, freq, count, end);
3056  if (success)
3057  {
3058  for (int i = 0, end = days.count(); i < end; ++i)
3059  d->mRecurrence->addMonthlyDate(days[i]);
3060  }
3061  d->mTriggerChanged = true;
3062  return success;
3063 }
3064 
3065 /******************************************************************************
3066 * Set the recurrence to recur monthly, on the specified weekdays in the
3067 * specified weeks of the month.
3068 * Parameters:
3069 * freq = how many months between recurrences.
3070 * posns = which days of the week/weeks of the month alarms should occur on.
3071 * count = number of occurrences, including first and last.
3072 * = -1 to recur indefinitely.
3073 * = 0 to use 'end' instead.
3074 * end = end date (invalid to use 'count' instead).
3075 * Reply = false if no recurrence was set up.
3076 */
3077 bool KAEvent::setRecurMonthlyByPos(int freq, const QVector<MonthPos>& posns, int count, const QDate& end)
3078 {
3079  const bool success = d->setRecur(RecurrenceRule::rMonthly, freq, count, end);
3080  if (success)
3081  {
3082  for (int i = 0, end = posns.count(); i < end; ++i)
3083  d->mRecurrence->addMonthlyPos(posns[i].weeknum, posns[i].days);
3084  }
3085  d->mTriggerChanged = true;
3086  return success;
3087 }
3088 
3089 /******************************************************************************
3090 * Set the recurrence to recur annually, on the specified start date in each
3091 * of the specified months.
3092 * Parameters:
3093 * freq = how many years between recurrences.
3094 * months = which months of the year alarms should occur on.
3095 * day = day of month, or 0 to use start date
3096 * feb29 = when February 29th should recur in non-leap years.
3097 * count = number of occurrences, including first and last.
3098 * = -1 to recur indefinitely.
3099 * = 0 to use 'end' instead.
3100 * end = end date (invalid to use 'count' instead).
3101 * Reply = false if no recurrence was set up.
3102 */
3103 bool KAEvent::setRecurAnnualByDate(int freq, const QVector<int>& months, int day, KARecurrence::Feb29Type feb29, int count, const QDate& end)
3104 {
3105  const bool success = d->setRecur(RecurrenceRule::rYearly, freq, count, end, feb29);
3106  if (success)
3107  {
3108  for (int i = 0, end = months.count(); i < end; ++i)
3109  d->mRecurrence->addYearlyMonth(months[i]);
3110  if (day)
3111  d->mRecurrence->addMonthlyDate(day);
3112  }
3113  d->mTriggerChanged = true;
3114  return success;
3115 }
3116 
3117 /******************************************************************************
3118 * Set the recurrence to recur annually, on the specified weekdays in the
3119 * specified weeks of the specified months.
3120 * Parameters:
3121 * freq = how many years between recurrences.
3122 * posns = which days of the week/weeks of the month alarms should occur on.
3123 * months = which months of the year alarms should occur on.
3124 * count = number of occurrences, including first and last.
3125 * = -1 to recur indefinitely.
3126 * = 0 to use 'end' instead.
3127 * end = end date (invalid to use 'count' instead).
3128 * Reply = false if no recurrence was set up.
3129 */
3130 bool KAEvent::setRecurAnnualByPos(int freq, const QVector<MonthPos>& posns, const QVector<int>& months, int count, const QDate& end)
3131 {
3132  const bool success = d->setRecur(RecurrenceRule::rYearly, freq, count, end);
3133  if (success)
3134  {
3135  int i = 0;
3136  int iend;
3137  for (iend = months.count(); i < iend; ++i)
3138  d->mRecurrence->addYearlyMonth(months[i]);
3139  for (i = 0, iend = posns.count(); i < iend; ++i)
3140  d->mRecurrence->addYearlyPos(posns[i].weeknum, posns[i].days);
3141  }
3142  d->mTriggerChanged = true;
3143  return success;
3144 }
3145 
3146 /******************************************************************************
3147 * Initialise the event's recurrence data.
3148 * Parameters:
3149 * freq = how many intervals between recurrences.
3150 * count = number of occurrences, including first and last.
3151 * = -1 to recur indefinitely.
3152 * = 0 to use 'end' instead.
3153 * end = end date/time (invalid to use 'count' instead).
3154 * Reply = false if no recurrence was set up.
3155 */
3156 bool KAEvent::Private::setRecur(RecurrenceRule::PeriodType recurType, int freq, int count, const QDate& end, KARecurrence::Feb29Type feb29)
3157 {
3158  KDateTime edt = mNextMainDateTime.kDateTime();
3159  edt.setDate(end);
3160  return setRecur(recurType, freq, count, edt, feb29);
3161 }
3162 bool KAEvent::Private::setRecur(RecurrenceRule::PeriodType recurType, int freq, int count, const KDateTime& end, KARecurrence::Feb29Type feb29)
3163 {
3164  if (count >= -1 && (count || end.date().isValid()))
3165  {
3166  if (!mRecurrence)
3167  mRecurrence = new KARecurrence;
3168  if (mRecurrence->init(recurType, freq, count, mNextMainDateTime.kDateTime(), end, feb29))
3169  return true;
3170  }
3171  clearRecur();
3172  return false;
3173 }
3174 
3175 bool KAEvent::recurs() const
3176 {
3177  return d->checkRecur() != KARecurrence::NO_RECUR;
3178 }
3179 
3180 KARecurrence::Type KAEvent::recurType() const
3181 {
3182  return d->checkRecur();
3183 }
3184 
3185 KARecurrence* KAEvent::recurrence() const
3186 {
3187  return d->mRecurrence;
3188 }
3189 
3190 /******************************************************************************
3191 * Return the recurrence interval in units of the recurrence period type.
3192 */
3193 int KAEvent::recurInterval() const
3194 {
3195  if (d->mRecurrence)
3196  {
3197  switch (d->mRecurrence->type())
3198  {
3199  case KARecurrence::MINUTELY:
3200  case KARecurrence::DAILY:
3201  case KARecurrence::WEEKLY:
3202  case KARecurrence::MONTHLY_DAY:
3203  case KARecurrence::MONTHLY_POS:
3204  case KARecurrence::ANNUAL_DATE:
3205  case KARecurrence::ANNUAL_POS:
3206  return d->mRecurrence->frequency();
3207  default:
3208  break;
3209  }
3210  }
3211  return 0;
3212 }
3213 
3214 Duration KAEvent::longestRecurrenceInterval() const
3215 {
3216  return d->mRecurrence ? d->mRecurrence->longestInterval() : Duration(0);
3217 }
3218 
3219 /******************************************************************************
3220 * Adjust the event date/time to the first recurrence of the event, on or after
3221 * start date/time. The event start date may not be a recurrence date, in which
3222 * case a later date will be set.
3223 */
3224 void KAEvent::setFirstRecurrence()
3225 {
3226  d->setFirstRecurrence();
3227 }
3228 
3229 void KAEvent::Private::setFirstRecurrence()
3230 {
3231  switch (checkRecur())
3232  {
3233  case KARecurrence::NO_RECUR:
3234  case KARecurrence::MINUTELY:
3235  return;
3236  case KARecurrence::ANNUAL_DATE:
3237  case KARecurrence::ANNUAL_POS:
3238  if (mRecurrence->yearMonths().isEmpty())
3239  return; // (presumably it's a template)
3240  break;
3241  case KARecurrence::DAILY:
3242  case KARecurrence::WEEKLY:
3243  case KARecurrence::MONTHLY_POS:
3244  case KARecurrence::MONTHLY_DAY:
3245  break;
3246  }
3247  const KDateTime recurStart = mRecurrence->startDateTime();
3248  if (mRecurrence->recursOn(recurStart.date(), recurStart.timeSpec()))
3249  return; // it already recurs on the start date
3250 
3251  // Set the frequency to 1 to find the first possible occurrence
3252  const int frequency = mRecurrence->frequency();
3253  mRecurrence->setFrequency(1);
3254  DateTime next;
3255  nextRecurrence(mNextMainDateTime.effectiveKDateTime(), next);
3256  if (!next.isValid())
3257  mRecurrence->setStartDateTime(recurStart, mStartDateTime.isDateOnly()); // reinstate the old value
3258  else
3259  {
3260  mRecurrence->setStartDateTime(next.effectiveKDateTime(), next.isDateOnly());
3261  mStartDateTime = mNextMainDateTime = next;
3262  mTriggerChanged = true;
3263  }
3264  mRecurrence->setFrequency(frequency); // restore the frequency
3265 }
3266 
3267 /******************************************************************************
3268 * Return the recurrence interval as text suitable for display.
3269 */
3270 QString KAEvent::recurrenceText(bool brief) const
3271 {
3272  if (d->mRepeatAtLogin)
3273  return brief ? i18nc("@info/plain Brief form of 'At Login'", "Login") : i18nc("@info/plain", "At login");
3274  if (d->mRecurrence)
3275  {
3276  const int frequency = d->mRecurrence->frequency();
3277  switch (d->mRecurrence->defaultRRuleConst()->recurrenceType())
3278  {
3279  case RecurrenceRule::rMinutely:
3280  if (frequency < 60)
3281  return i18ncp("@info/plain", "1 Minute", "%1 Minutes", frequency);
3282  else if (frequency % 60 == 0)
3283  return i18ncp("@info/plain", "1 Hour", "%1 Hours", frequency/60);
3284  else
3285  {
3286  QString mins;
3287  return i18nc("@info/plain Hours and minutes", "%1h %2m", frequency/60, mins.sprintf("%02d", frequency%60));
3288  }
3289  case RecurrenceRule::rDaily:
3290  return i18ncp("@info/plain", "1 Day", "%1 Days", frequency);
3291  case RecurrenceRule::rWeekly:
3292  return i18ncp("@info/plain", "1 Week", "%1 Weeks", frequency);
3293  case RecurrenceRule::rMonthly:
3294  return i18ncp("@info/plain", "1 Month", "%1 Months", frequency);
3295  case RecurrenceRule::rYearly:
3296  return i18ncp("@info/plain", "1 Year", "%1 Years", frequency);
3297  case RecurrenceRule::rNone:
3298  default:
3299  break;
3300  }
3301  }
3302  return brief ? QString() : i18nc("@info/plain No recurrence", "None");
3303 }
3304 
3305 /******************************************************************************
3306 * Initialise the event's sub-repetition.
3307 * The repetition length is adjusted if necessary to fit the recurrence interval.
3308 * If the event doesn't recur, the sub-repetition is cleared.
3309 * Reply = false if a non-daily interval was specified for a date-only recurrence.
3310 */
3311 bool KAEvent::setRepetition(const Repetition& r)
3312 {
3313  return d->setRepetition(r);
3314 }
3315 
3316 bool KAEvent::Private::setRepetition(const Repetition& repetition)
3317 {
3318  // Don't set mRepetition to zero at the start of this function, in case the
3319  // 'repetition' parameter passed in is a reference to mRepetition.
3320  mNextRepeat = 0;
3321  if (repetition && !mRepeatAtLogin)
3322  {
3323  Q_ASSERT(checkRecur() != KARecurrence::NO_RECUR);
3324  if (!repetition.isDaily() && mStartDateTime.isDateOnly())
3325  {
3326  mRepetition.set(0, 0);
3327  return false; // interval must be in units of days for date-only alarms
3328  }
3329  Duration longestInterval = mRecurrence->longestInterval();
3330  if (repetition.duration() >= longestInterval)
3331  {
3332  const int count = mStartDateTime.isDateOnly()
3333  ? (longestInterval.asDays() - 1) / repetition.intervalDays()
3334  : (longestInterval.asSeconds() - 1) / repetition.intervalSeconds();
3335  mRepetition.set(repetition.interval(), count);
3336  }
3337  else
3338  mRepetition = repetition;
3339  mTriggerChanged = true;
3340  }
3341  else if (mRepetition)
3342  {
3343  mRepetition.set(0, 0);
3344  mTriggerChanged = true;
3345  }
3346  return true;
3347 }
3348 
3349 Repetition KAEvent::repetition() const
3350 {
3351  return d->mRepetition;
3352 }
3353 
3354 int KAEvent::nextRepetition() const
3355 {
3356  return d->mNextRepeat;
3357 }
3358 
3359 /******************************************************************************
3360 * Return the repetition interval as text suitable for display.
3361 */
3362 QString KAEvent::repetitionText(bool brief) const
3363 {
3364  if (d->mRepetition)
3365  {
3366  if (!d->mRepetition.isDaily())
3367  {
3368  const int minutes = d->mRepetition.intervalMinutes();
3369  if (minutes < 60)
3370  return i18ncp("@info/plain", "1 Minute", "%1 Minutes", minutes);
3371  if (minutes % 60 == 0)
3372  return i18ncp("@info/plain", "1 Hour", "%1 Hours", minutes/60);
3373  QString mins;
3374  return i18nc("@info/plain Hours and minutes", "%1h %2m", minutes/60, mins.sprintf("%02d", minutes%60));
3375  }
3376  const int days = d->mRepetition.intervalDays();
3377  if (days % 7)
3378  return i18ncp("@info/plain", "1 Day", "%1 Days", days);
3379  return i18ncp("@info/plain", "1 Week", "%1 Weeks", days / 7);
3380  }
3381  return brief ? QString() : i18nc("@info/plain No repetition", "None");
3382 }
3383 
3384 /******************************************************************************
3385 * Determine whether the event will occur after the specified date/time.
3386 * If 'includeRepetitions' is true and the alarm has a sub-repetition, it
3387 * returns true if any repetitions occur after the specified date/time.
3388 */
3389 bool KAEvent::occursAfter(const KDateTime& preDateTime, bool includeRepetitions) const
3390 {
3391  return d->occursAfter(preDateTime, includeRepetitions);
3392 }
3393 
3394 bool KAEvent::Private::occursAfter(const KDateTime& preDateTime, bool includeRepetitions) const
3395 {
3396  KDateTime dt;
3397  if (checkRecur() != KARecurrence::NO_RECUR)
3398  {
3399  if (mRecurrence->duration() < 0)
3400  return true; // infinite recurrence
3401  dt = mRecurrence->endDateTime();
3402  }
3403  else
3404  dt = mNextMainDateTime.effectiveKDateTime();
3405  if (mStartDateTime.isDateOnly())
3406  {
3407  QDate pre = preDateTime.date();
3408  if (preDateTime.toTimeSpec(mStartDateTime.timeSpec()).time() < DateTime::startOfDay())
3409  pre = pre.addDays(-1); // today's recurrence (if today recurs) is still to come
3410  if (pre < dt.date())
3411  return true;
3412  }
3413  else if (preDateTime < dt)
3414  return true;
3415 
3416  if (includeRepetitions && mRepetition)
3417  {
3418  if (preDateTime < mRepetition.duration().end(dt))
3419  return true;
3420  }
3421  return false;
3422 }
3423 
3424 /******************************************************************************
3425 * Set the date/time of the event to the next scheduled occurrence after the
3426 * specified date/time, provided that this is later than its current date/time.
3427 * Any reminder alarm is adjusted accordingly.
3428 * If the alarm has a sub-repetition, and a repetition of a previous recurrence
3429 * occurs after the specified date/time, that repetition is set as the next
3430 * occurrence.
3431 */
3432 KAEvent::OccurType KAEvent::setNextOccurrence(const KDateTime& preDateTime)
3433 {
3434  return d->setNextOccurrence(preDateTime);
3435 }
3436 
3437 KAEvent::OccurType KAEvent::Private::setNextOccurrence(const KDateTime& preDateTime)
3438 {
3439  if (preDateTime < mNextMainDateTime.effectiveKDateTime())
3440  return FIRST_OR_ONLY_OCCURRENCE; // it might not be the first recurrence - tant pis
3441  KDateTime pre = preDateTime;
3442  // If there are repetitions, adjust the comparison date/time so that
3443  // we find the earliest recurrence which has a repetition falling after
3444  // the specified preDateTime.
3445  if (mRepetition)
3446  pre = mRepetition.duration(-mRepetition.count()).end(preDateTime);
3447 
3448  DateTime afterPre; // next recurrence after 'pre'
3449  OccurType type;
3450  if (pre < mNextMainDateTime.effectiveKDateTime())
3451  {
3452  afterPre = mNextMainDateTime;
3453  type = FIRST_OR_ONLY_OCCURRENCE; // may not actually be the first occurrence
3454  }
3455  else if (checkRecur() != KARecurrence::NO_RECUR)
3456  {
3457  type = nextRecurrence(pre, afterPre);
3458  if (type == NO_OCCURRENCE)
3459  return NO_OCCURRENCE;
3460  if (type != FIRST_OR_ONLY_OCCURRENCE && afterPre != mNextMainDateTime)
3461  {
3462  // Need to reschedule the next trigger date/time
3463  mNextMainDateTime = afterPre;
3464  if (mReminderMinutes > 0 && (mDeferral == REMINDER_DEFERRAL || mReminderActive != ACTIVE_REMINDER))
3465  {
3466  // Reinstate the advance reminder for the rescheduled recurrence.
3467  // Note that a reminder AFTER the main alarm will be left active.
3468  activate_reminder(!mReminderOnceOnly);
3469  }
3470  if (mDeferral == REMINDER_DEFERRAL)
3471  set_deferral(NO_DEFERRAL);
3472  mTriggerChanged = true;
3473  }
3474  }
3475  else
3476  return NO_OCCURRENCE;
3477 
3478  if (mRepetition)
3479  {
3480  if (afterPre <= preDateTime)
3481  {
3482  // The next occurrence is a sub-repetition.
3483  type = static_cast<OccurType>(type | OCCURRENCE_REPEAT);
3484  mNextRepeat = mRepetition.nextRepeatCount(afterPre.effectiveKDateTime(), preDateTime);
3485  // Repetitions can't have a reminder, so remove any.
3486  activate_reminder(false);
3487  if (mDeferral == REMINDER_DEFERRAL)
3488  set_deferral(NO_DEFERRAL);
3489  mTriggerChanged = true;
3490  }
3491  else if (mNextRepeat)
3492  {
3493  // The next occurrence is the main occurrence, not a repetition
3494  mNextRepeat = 0;
3495  mTriggerChanged = true;
3496  }
3497  }
3498  return type;
3499 }
3500 
3501 /******************************************************************************
3502 * Get the date/time of the next occurrence of the event, after the specified
3503 * date/time.
3504 * 'result' = date/time of next occurrence, or invalid date/time if none.
3505 */
3506 KAEvent::OccurType KAEvent::nextOccurrence(const KDateTime& preDateTime, DateTime& result, OccurOption o) const
3507 {
3508  return d->nextOccurrence(preDateTime, result, o);
3509 }
3510 
3511 KAEvent::OccurType KAEvent::Private::nextOccurrence(const KDateTime& preDateTime, DateTime& result,
3512  OccurOption includeRepetitions) const
3513 {
3514  KDateTime pre = preDateTime;
3515  if (includeRepetitions != IGNORE_REPETITION)
3516  { // RETURN_REPETITION or ALLOW_FOR_REPETITION
3517  if (!mRepetition)
3518  includeRepetitions = IGNORE_REPETITION;
3519  else
3520  pre = mRepetition.duration(-mRepetition.count()).end(preDateTime);
3521  }
3522 
3523  OccurType type;
3524  const bool recurs = (checkRecur() != KARecurrence::NO_RECUR);
3525  if (recurs)
3526  type = nextRecurrence(pre, result);
3527  else if (pre < mNextMainDateTime.effectiveKDateTime())
3528  {
3529  result = mNextMainDateTime;
3530  type = FIRST_OR_ONLY_OCCURRENCE;
3531  }
3532  else
3533  {
3534  result = DateTime();
3535  type = NO_OCCURRENCE;
3536  }
3537 
3538  if (type != NO_OCCURRENCE && result <= preDateTime && includeRepetitions != IGNORE_REPETITION)
3539  { // RETURN_REPETITION or ALLOW_FOR_REPETITION
3540  // The next occurrence is a sub-repetition
3541  int repetition = mRepetition.nextRepeatCount(result.kDateTime(), preDateTime);
3542  const DateTime repeatDT = mRepetition.duration(repetition).end(result.kDateTime());
3543  if (recurs)
3544  {
3545  // We've found a recurrence before the specified date/time, which has
3546  // a sub-repetition after the date/time.
3547  // However, if the intervals between recurrences vary, we could possibly
3548  // have missed a later recurrence which fits the criterion, so check again.
3549  DateTime dt;
3550  const OccurType newType = previousOccurrence(repeatDT.effectiveKDateTime(), dt, false);
3551  if (dt > result)
3552  {
3553  type = newType;
3554  result = dt;
3555  if (includeRepetitions == RETURN_REPETITION && result <= preDateTime)
3556  {
3557  // The next occurrence is a sub-repetition
3558  repetition = mRepetition.nextRepeatCount(result.kDateTime(), preDateTime);
3559  result = mRepetition.duration(repetition).end(result.kDateTime());
3560  type = static_cast<OccurType>(type | OCCURRENCE_REPEAT);
3561  }
3562  return type;
3563  }
3564  }
3565  if (includeRepetitions == RETURN_REPETITION)
3566  {
3567  // The next occurrence is a sub-repetition
3568  result = repeatDT;
3569  type = static_cast<OccurType>(type | OCCURRENCE_REPEAT);
3570  }
3571  }
3572  return type;
3573 }
3574 
3575 /******************************************************************************
3576 * Get the date/time of the last previous occurrence of the event, before the
3577 * specified date/time.
3578 * If 'includeRepetitions' is true and the alarm has a sub-repetition, the
3579 * last previous repetition is returned if appropriate.
3580 * 'result' = date/time of previous occurrence, or invalid date/time if none.
3581 */
3582 KAEvent::OccurType KAEvent::previousOccurrence(const KDateTime& afterDateTime, DateTime& result, bool includeRepetitions) const
3583 {
3584  return d->previousOccurrence(afterDateTime, result, includeRepetitions);
3585 }
3586 
3587 KAEvent::OccurType KAEvent::Private::previousOccurrence(const KDateTime& afterDateTime, DateTime& result,
3588  bool includeRepetitions) const
3589 {
3590  Q_ASSERT(!afterDateTime.isDateOnly());
3591  if (mStartDateTime >= afterDateTime)
3592  {
3593  result = KDateTime();
3594  return NO_OCCURRENCE; // the event starts after the specified date/time
3595  }
3596 
3597  // Find the latest recurrence of the event
3598  OccurType type;
3599  if (checkRecur() == KARecurrence::NO_RECUR)
3600  {
3601  result = mStartDateTime;
3602  type = FIRST_OR_ONLY_OCCURRENCE;
3603  }
3604  else
3605  {
3606  const KDateTime recurStart = mRecurrence->startDateTime();
3607  KDateTime after = afterDateTime.toTimeSpec(mStartDateTime.timeSpec());
3608  if (mStartDateTime.isDateOnly() && afterDateTime.time() > DateTime::startOfDay())
3609  after = after.addDays(1); // today's recurrence (if today recurs) has passed
3610  const KDateTime dt = mRecurrence->getPreviousDateTime(after);
3611  result = dt;
3612  result.setDateOnly(mStartDateTime.isDateOnly());
3613  if (!dt.isValid())
3614  return NO_OCCURRENCE;
3615  if (dt == recurStart)
3616  type = FIRST_OR_ONLY_OCCURRENCE;
3617  else if (mRecurrence->getNextDateTime(dt).isValid())
3618  type = result.isDateOnly() ? RECURRENCE_DATE : RECURRENCE_DATE_TIME;
3619  else
3620  type = LAST_RECURRENCE;
3621  }
3622 
3623  if (includeRepetitions && mRepetition)
3624  {
3625  // Find the latest repetition which is before the specified time.
3626  const int repetition = mRepetition.previousRepeatCount(result.effectiveKDateTime(), afterDateTime);
3627  if (repetition > 0)
3628  {
3629  result = mRepetition.duration(qMin(repetition, mRepetition.count())).end(result.kDateTime());
3630  return static_cast<OccurType>(type | OCCURRENCE_REPEAT);
3631  }
3632  }
3633  return type;
3634 }
3635 
3636 /******************************************************************************
3637 * Set the event to be a copy of the specified event, making the specified
3638 * alarm the 'displaying' alarm.
3639 * The purpose of setting up a 'displaying' alarm is to be able to reinstate
3640 * the alarm message in case of a crash, or to reinstate it should the user
3641 * choose to defer the alarm. Note that even repeat-at-login alarms need to be
3642 * saved in case their end time expires before the next login.
3643 * Reply = true if successful, false if alarm was not copied.
3644 */
3645 #ifndef KALARMCAL_USE_KRESOURCES
3646 bool KAEvent::setDisplaying(const KAEvent& e, KAAlarm::Type t, Akonadi::Collection::Id id, const KDateTime& dt, bool showEdit, bool showDefer)
3647 #else
3648 bool KAEvent::setDisplaying(const KAEvent& e, KAAlarm::Type t, const QString& id, const KDateTime& dt, bool showEdit, bool showDefer)
3649 #endif
3650 {
3651  return d->setDisplaying(*e.d, t, id, dt, showEdit, showDefer);
3652 }
3653 
3654 #ifndef KALARMCAL_USE_KRESOURCES
3655 bool KAEvent::Private::setDisplaying(const KAEvent::Private& event, KAAlarm::Type alarmType, Akonadi::Collection::Id collectionId,
3656  const KDateTime& repeatAtLoginTime, bool showEdit, bool showDefer)
3657 #else
3658 bool KAEvent::Private::setDisplaying(const KAEvent::Private& event, KAAlarm::Type alarmType, const QString& resourceID,
3659  const KDateTime& repeatAtLoginTime, bool showEdit, bool showDefer)
3660 #endif
3661 {
3662  if (!mDisplaying
3663  && (alarmType == KAAlarm::MAIN_ALARM
3664  || alarmType == KAAlarm::REMINDER_ALARM
3665  || alarmType == KAAlarm::DEFERRED_REMINDER_ALARM
3666  || alarmType == KAAlarm::DEFERRED_ALARM
3667  || alarmType == KAAlarm::AT_LOGIN_ALARM))
3668  {
3669 //kDebug()<<event.id()<<","<<(alarmType==KAAlarm::MAIN_ALARM?"MAIN":alarmType==KAAlarm::REMINDER_ALARM?"REMINDER":alarmType==KAAlarm::DEFERRED_REMINDER_ALARM?"REMINDER_DEFERRAL":alarmType==KAAlarm::DEFERRED_ALARM?"DEFERRAL":"LOGIN")<<"): time="<<repeatAtLoginTime.toString();
3670  KAAlarm al = event.alarm(alarmType);
3671  if (al.isValid())
3672  {
3673  *this = event;
3674  // Change the event ID to avoid duplicating the same unique ID as the original event
3675  setCategory(CalEvent::DISPLAYING);
3676 #ifndef KALARMCAL_USE_KRESOURCES
3677  mItemId = -1; // the display event doesn't have an associated Item
3678  mCollectionId = collectionId; // original collection ID which contained the event
3679 #else
3680  mOriginalResourceId = resourceID;
3681 #endif
3682  mDisplayingDefer = showDefer;
3683  mDisplayingEdit = showEdit;
3684  mDisplaying = true;
3685  mDisplayingTime = (alarmType == KAAlarm::AT_LOGIN_ALARM) ? repeatAtLoginTime : al.dateTime().kDateTime();
3686  switch (al.type())
3687  {
3688  case KAAlarm::AT_LOGIN_ALARM: mDisplayingFlags = REPEAT_AT_LOGIN; break;
3689  case KAAlarm::REMINDER_ALARM: mDisplayingFlags = REMINDER; break;
3690  case KAAlarm::DEFERRED_REMINDER_ALARM: mDisplayingFlags = al.timedDeferral() ? (REMINDER | TIME_DEFERRAL) : (REMINDER | DATE_DEFERRAL); break;
3691  case KAAlarm::DEFERRED_ALARM: mDisplayingFlags = al.timedDeferral() ? TIME_DEFERRAL : DATE_DEFERRAL; break;
3692  default: mDisplayingFlags = 0; break;
3693  }
3694  ++mAlarmCount;
3695  return true;
3696  }
3697  }
3698  return false;
3699 }
3700 
3701 /******************************************************************************
3702 * Reinstate the original event from the 'displaying' event.
3703 */
3704 #ifndef KALARMCAL_USE_KRESOURCES
3705 void KAEvent::reinstateFromDisplaying(const KCalCore::Event::Ptr& e, Akonadi::Collection::Id& id, bool& showEdit, bool& showDefer)
3706 #else
3707 void KAEvent::reinstateFromDisplaying(const KCal::Event* e, QString& id, bool& showEdit, bool& showDefer)
3708 #endif
3709 {
3710  d->reinstateFromDisplaying(e, id, showEdit, showDefer);
3711 }
3712 
3713 #ifndef KALARMCAL_USE_KRESOURCES
3714 void KAEvent::Private::reinstateFromDisplaying(const Event::Ptr& kcalEvent, Akonadi::Collection::Id& collectionId, bool& showEdit, bool& showDefer)
3715 #else
3716 void KAEvent::Private::reinstateFromDisplaying(const Event* kcalEvent, QString& resourceID, bool& showEdit, bool& showDefer)
3717 #endif
3718 {
3719  set(kcalEvent);
3720  if (mDisplaying)
3721  {
3722  // Retrieve the original event's unique ID
3723  setCategory(CalEvent::ACTIVE);
3724 #ifndef KALARMCAL_USE_KRESOURCES
3725  collectionId = mCollectionId;
3726  mCollectionId = -1;
3727 #else
3728  resourceID = mOriginalResourceId;
3729  mOriginalResourceId.clear();
3730 #endif
3731  showDefer = mDisplayingDefer;
3732  showEdit = mDisplayingEdit;
3733  mDisplaying = false;
3734  --mAlarmCount;
3735  }
3736 }
3737 
3738 /******************************************************************************
3739 * Return the original alarm which the displaying alarm refers to.
3740 * Note that the caller is responsible for ensuring that the event was a
3741 * displaying event, since this is normally called after
3742 * reinstateFromDisplaying(), which clears mDisplaying.
3743 */
3744 KAAlarm KAEvent::convertDisplayingAlarm() const
3745 {
3746  KAAlarm al = alarm(KAAlarm::DISPLAYING_ALARM);
3747  KAAlarm::Private* const al_d = al.d;
3748  const int displayingFlags = d->mDisplayingFlags;
3749  if (displayingFlags & REPEAT_AT_LOGIN)
3750  {
3751  al_d->mRepeatAtLogin = true;
3752  al_d->mType = KAAlarm::AT_LOGIN_ALARM;
3753  }
3754  else if (displayingFlags & Private::DEFERRAL)
3755  {
3756  al_d->mDeferred = true;
3757  al_d->mTimedDeferral = (displayingFlags & Private::TIMED_FLAG);
3758  al_d->mType = (displayingFlags & Private::REMINDER) ? KAAlarm::DEFERRED_REMINDER_ALARM : KAAlarm::DEFERRED_ALARM;
3759  }
3760  else if (displayingFlags & Private::REMINDER)
3761  al_d->mType = KAAlarm::REMINDER_ALARM;
3762  else
3763  al_d->mType = KAAlarm::MAIN_ALARM;
3764  return al;
3765 }
3766 
3767 bool KAEvent::displaying() const
3768 {
3769  return d->mDisplaying;
3770 }
3771 
3772 /******************************************************************************
3773 * Return the alarm of the specified type.
3774 */
3775 KAAlarm KAEvent::alarm(KAAlarm::Type t) const
3776 {
3777  return d->alarm(t);
3778 }
3779 
3780 KAAlarm KAEvent::Private::alarm(KAAlarm::Type type) const
3781 {
3782  checkRecur(); // ensure recurrence/repetition data is consistent
3783  KAAlarm al; // this sets type to INVALID_ALARM
3784  KAAlarm::Private* const al_d = al.d;
3785  if (mAlarmCount)
3786  {
3787  al_d->mActionType = (KAAlarm::Action)mActionSubType;
3788  al_d->mRepeatAtLogin = false;
3789  al_d->mDeferred = false;
3790  switch (type)
3791  {
3792  case KAAlarm::MAIN_ALARM:
3793  if (!mMainExpired)
3794  {
3795  al_d->mType = KAAlarm::MAIN_ALARM;
3796  al_d->mNextMainDateTime = mNextMainDateTime;
3797  al_d->mRepetition = mRepetition;
3798  al_d->mNextRepeat = mNextRepeat;
3799  }
3800  break;
3801  case KAAlarm::REMINDER_ALARM:
3802  if (mReminderActive == ACTIVE_REMINDER)
3803  {
3804  al_d->mType = KAAlarm::REMINDER_ALARM;
3805  if (mReminderMinutes < 0)
3806  al_d->mNextMainDateTime = mReminderAfterTime;
3807  else if (mReminderOnceOnly)
3808  al_d->mNextMainDateTime = mStartDateTime.addMins(-mReminderMinutes);
3809  else
3810  al_d->mNextMainDateTime = mNextMainDateTime.addMins(-mReminderMinutes);
3811  }
3812  break;
3813  case KAAlarm::DEFERRED_REMINDER_ALARM:
3814  if (mDeferral != REMINDER_DEFERRAL)
3815  break;
3816  // fall through to DEFERRED_ALARM
3817  case KAAlarm::DEFERRED_ALARM:
3818  if (mDeferral != NO_DEFERRAL)
3819  {
3820  al_d->mType = (mDeferral == REMINDER_DEFERRAL) ? KAAlarm::DEFERRED_REMINDER_ALARM : KAAlarm::DEFERRED_ALARM;
3821  al_d->mNextMainDateTime = mDeferralTime;
3822  al_d->mDeferred = true;
3823  al_d->mTimedDeferral = !mDeferralTime.isDateOnly();
3824  }
3825  break;
3826  case KAAlarm::AT_LOGIN_ALARM:
3827  if (mRepeatAtLogin)
3828  {
3829  al_d->mType = KAAlarm::AT_LOGIN_ALARM;
3830  al_d->mNextMainDateTime = mAtLoginDateTime;
3831  al_d->mRepeatAtLogin = true;
3832  }
3833  break;
3834  case KAAlarm::DISPLAYING_ALARM:
3835  if (mDisplaying)
3836  {
3837  al_d->mType = KAAlarm::DISPLAYING_ALARM;
3838  al_d->mNextMainDateTime = mDisplayingTime;
3839  }
3840  break;
3841  case KAAlarm::INVALID_ALARM:
3842  default:
3843  break;
3844  }
3845  }
3846  return al;
3847 }
3848 
3849 /******************************************************************************
3850 * Return the main alarm for the event.
3851 * If the main alarm does not exist, one of the subsidiary ones is returned if
3852 * possible.
3853 * N.B. a repeat-at-login alarm can only be returned if it has been read from/
3854 * written to the calendar file.
3855 */
3856 KAAlarm KAEvent::firstAlarm() const
3857 {
3858  return d->firstAlarm();
3859 }
3860 
3861 KAAlarm KAEvent::Private::firstAlarm() const
3862 {
3863  if (mAlarmCount)
3864  {
3865  if (!mMainExpired)
3866  return alarm(KAAlarm::MAIN_ALARM);
3867  return nextAlarm(KAAlarm::MAIN_ALARM);
3868  }
3869  return KAAlarm();
3870 }
3871 
3872 /******************************************************************************
3873 * Return the next alarm for the event, after the specified alarm.
3874 * N.B. a repeat-at-login alarm can only be returned if it has been read from/
3875 * written to the calendar file.
3876 */
3877 KAAlarm KAEvent::nextAlarm(const KAAlarm& previousAlarm) const
3878 {
3879  return d->nextAlarm(previousAlarm.type());
3880 }
3881 
3882 KAAlarm KAEvent::nextAlarm(KAAlarm::Type previousType) const
3883 {
3884  return d->nextAlarm(previousType);
3885 }
3886 
3887 KAAlarm KAEvent::Private::nextAlarm(KAAlarm::Type previousType) const
3888 {
3889  switch (previousType)
3890  {
3891  case KAAlarm::MAIN_ALARM:
3892  if (mReminderActive == ACTIVE_REMINDER)
3893  return alarm(KAAlarm::REMINDER_ALARM);
3894  // fall through to REMINDER_ALARM
3895  case KAAlarm::REMINDER_ALARM:
3896  // There can only be one deferral alarm
3897  if (mDeferral == REMINDER_DEFERRAL)
3898  return alarm(KAAlarm::DEFERRED_REMINDER_ALARM);
3899  if (mDeferral == NORMAL_DEFERRAL)
3900  return alarm(KAAlarm::DEFERRED_ALARM);
3901  // fall through to DEFERRED_ALARM
3902  case KAAlarm::DEFERRED_REMINDER_ALARM:
3903  case KAAlarm::DEFERRED_ALARM:
3904  if (mRepeatAtLogin)
3905  return alarm(KAAlarm::AT_LOGIN_ALARM);
3906  // fall through to AT_LOGIN_ALARM
3907  case KAAlarm::AT_LOGIN_ALARM:
3908  if (mDisplaying)
3909  return alarm(KAAlarm::DISPLAYING_ALARM);
3910  // fall through to DISPLAYING_ALARM
3911  case KAAlarm::DISPLAYING_ALARM:
3912  // fall through to default
3913  case KAAlarm::INVALID_ALARM:
3914  default:
3915  break;
3916  }
3917  return KAAlarm();
3918 }
3919 
3920 int KAEvent::alarmCount() const
3921 {
3922  return d->mAlarmCount;
3923 }
3924 
3925 /******************************************************************************
3926 * Remove the alarm of the specified type from the event.
3927 * This must only be called to remove an alarm which has expired, not to
3928 * reconfigure the event.
3929 */
3930 void KAEvent::removeExpiredAlarm(KAAlarm::Type type)
3931 {
3932  d->removeExpiredAlarm(type);
3933 }
3934 
3935 void KAEvent::Private::removeExpiredAlarm(KAAlarm::Type type)
3936 {
3937  const int count = mAlarmCount;
3938  switch (type)
3939  {
3940  case KAAlarm::MAIN_ALARM:
3941  if (!mReminderActive || mReminderMinutes > 0)
3942  {
3943  mAlarmCount = 0; // removing main alarm - also remove subsidiary alarms
3944  break;
3945  }
3946  // There is a reminder after the main alarm - retain the
3947  // reminder and remove other subsidiary alarms.
3948  mMainExpired = true; // mark the alarm as expired now
3949  --mAlarmCount;
3950  set_deferral(NO_DEFERRAL);
3951  if (mDisplaying)
3952  {
3953  mDisplaying = false;
3954  --mAlarmCount;
3955  }
3956  // fall through to AT_LOGIN_ALARM
3957  case KAAlarm::AT_LOGIN_ALARM:
3958  if (mRepeatAtLogin)
3959  {
3960  // Remove the at-login alarm, but keep a note of it for archiving purposes
3961  mArchiveRepeatAtLogin = true;
3962  mRepeatAtLogin = false;
3963  --mAlarmCount;
3964  }
3965  break;
3966  case KAAlarm::REMINDER_ALARM:
3967  // Remove any reminder alarm, but keep a note of it for archiving purposes
3968  // and for restoration after the next recurrence.
3969  activate_reminder(false);
3970  break;
3971  case KAAlarm::DEFERRED_REMINDER_ALARM:
3972  case KAAlarm::DEFERRED_ALARM:
3973  set_deferral(NO_DEFERRAL);
3974  break;
3975  case KAAlarm::DISPLAYING_ALARM:
3976  if (mDisplaying)
3977  {
3978  mDisplaying = false;
3979  --mAlarmCount;
3980  }
3981  break;
3982  case KAAlarm::INVALID_ALARM:
3983  default:
3984  break;
3985  }
3986  if (mAlarmCount != count)
3987  mTriggerChanged = true;
3988 }
3989 
3990 void KAEvent::startChanges()
3991 {
3992  d->startChanges();
3993 }
3994 
3995 /******************************************************************************
3996 * Indicate that changes to the instance are complete.
3997 * This allows trigger times to be recalculated if any changes have occurred.
3998 */
3999 void KAEvent::endChanges()
4000 {
4001  d->endChanges();
4002 }
4003 
4004 void KAEvent::Private::endChanges()
4005 {
4006  if (mChangeCount > 0)
4007  --mChangeCount;
4008 }
4009 
4010 #ifndef KALARMCAL_USE_KRESOURCES
4011 /******************************************************************************
4012 * Return a list of pointers to KAEvent objects.
4013 */
4014 KAEvent::List KAEvent::ptrList(QVector<KAEvent>& objList)
4015 {
4016  KAEvent::List ptrs;
4017  for (int i = 0, count = objList.count(); i < count; ++i)
4018  ptrs += &objList[i];
4019  return ptrs;
4020 }
4021 #endif
4022 
4023 void KAEvent::dumpDebug() const
4024 {
4025 #ifndef KDE_NO_DEBUG_OUTPUT
4026  d->dumpDebug();
4027 #endif
4028 }
4029 
4030 #ifndef KDE_NO_DEBUG_OUTPUT
4031 void KAEvent::Private::dumpDebug() const
4032 {
4033  kDebug() << "KAEvent dump:";
4034 #ifdef KALARMCAL_USE_KRESOURCES
4035  if (mResource) { kDebug() << "-- mResource:" << (void*)mResource; }
4036 #endif
4037  kDebug() << "-- mEventID:" << mEventID;
4038  kDebug() << "-- mActionSubType:" << (mActionSubType == MESSAGE ? "MESSAGE" : mActionSubType == FILE ? "FILE" : mActionSubType == COMMAND ? "COMMAND" : mActionSubType == EMAIL ? "EMAIL" : mActionSubType == AUDIO ? "AUDIO" : "??");
4039  kDebug() << "-- mNextMainDateTime:" << mNextMainDateTime.toString();
4040  kDebug() << "-- mCommandError:" << mCommandError;
4041  kDebug() << "-- mAllTrigger:" << mAllTrigger.toString();
4042  kDebug() << "-- mMainTrigger:" << mMainTrigger.toString();
4043  kDebug() << "-- mAllWorkTrigger:" << mAllWorkTrigger.toString();
4044  kDebug() << "-- mMainWorkTrigger:" << mMainWorkTrigger.toString();
4045  kDebug() << "-- mCategory:" << mCategory;
4046  if (!mTemplateName.isEmpty())
4047  {
4048  kDebug() << "-- mTemplateName:" << mTemplateName;
4049  kDebug() << "-- mTemplateAfterTime:" << mTemplateAfterTime;
4050  }
4051  kDebug() << "-- mText:" << mText;
4052  if (mActionSubType == MESSAGE || mActionSubType == FILE)
4053  {
4054  kDebug() << "-- mBgColour:" << mBgColour.name();
4055  kDebug() << "-- mFgColour:" << mFgColour.name();
4056  kDebug() << "-- mUseDefaultFont:" << mUseDefaultFont;
4057  if (!mUseDefaultFont)
4058  kDebug() << "-- mFont:" << mFont.toString();
4059  kDebug() << "-- mSpeak:" << mSpeak;
4060  kDebug() << "-- mAudioFile:" << mAudioFile;
4061  kDebug() << "-- mPreAction:" << mPreAction;
4062  kDebug() << "-- mExecPreActOnDeferral:" << (mExtraActionOptions & ExecPreActOnDeferral);
4063  kDebug() << "-- mCancelOnPreActErr:" << (mExtraActionOptions & CancelOnPreActError);
4064  kDebug() << "-- mDontShowPreActErr:" << (mExtraActionOptions & DontShowPreActError);
4065  kDebug() << "-- mPostAction:" << mPostAction;
4066  kDebug() << "-- mLateCancel:" << mLateCancel;
4067  kDebug() << "-- mAutoClose:" << mAutoClose;
4068  }
4069  else if (mActionSubType == COMMAND)
4070  {
4071  kDebug() << "-- mCommandScript:" << mCommandScript;
4072  kDebug() << "-- mCommandXterm:" << mCommandXterm;
4073  kDebug() << "-- mCommandDisplay:" << mCommandDisplay;
4074  kDebug() << "-- mLogFile:" << mLogFile;
4075  }
4076  else if (mActionSubType == EMAIL)
4077  {
4078  kDebug() << "-- mEmail: FromKMail:" << mEmailFromIdentity;
4079  kDebug() << "-- Addresses:" << mEmailAddresses.join(",");
4080  kDebug() << "-- Subject:" << mEmailSubject;
4081  kDebug() << "-- Attachments:" << mEmailAttachments.join(",");
4082  kDebug() << "-- Bcc:" << mEmailBcc;
4083  }
4084  else if (mActionSubType == AUDIO)
4085  kDebug() << "-- mAudioFile:" << mAudioFile;
4086  kDebug() << "-- mBeep:" << mBeep;
4087  if (mActionSubType == AUDIO || !mAudioFile.isEmpty())
4088  {
4089  if (mSoundVolume >= 0)
4090  {
4091  kDebug() << "-- mSoundVolume:" << mSoundVolume;
4092  if (mFadeVolume >= 0)
4093  {
4094  kDebug() << "-- mFadeVolume:" << mFadeVolume;
4095  kDebug() << "-- mFadeSeconds:" << mFadeSeconds;
4096  }
4097  else
4098  kDebug() << "-- mFadeVolume:-:";
4099  }
4100  else
4101  kDebug() << "-- mSoundVolume:-:";
4102  kDebug() << "-- mRepeatSoundPause:" << mRepeatSoundPause;
4103  }
4104  kDebug() << "-- mKMailSerialNumber:" << mKMailSerialNumber;
4105  kDebug() << "-- mCopyToKOrganizer:" << mCopyToKOrganizer;
4106  kDebug() << "-- mExcludeHolidays:" << (bool)mExcludeHolidays;
4107  kDebug() << "-- mWorkTimeOnly:" << mWorkTimeOnly;
4108  kDebug() << "-- mStartDateTime:" << mStartDateTime.toString();
4109  kDebug() << "-- mCreatedDateTime:" << mCreatedDateTime;
4110  kDebug() << "-- mRepeatAtLogin:" << mRepeatAtLogin;
4111  if (mRepeatAtLogin)
4112  kDebug() << "-- mAtLoginDateTime:" << mAtLoginDateTime;
4113  kDebug() << "-- mArchiveRepeatAtLogin:" << mArchiveRepeatAtLogin;
4114  kDebug() << "-- mConfirmAck:" << mConfirmAck;
4115  kDebug() << "-- mEnabled:" << mEnabled;
4116 #ifndef KALARMCAL_USE_KRESOURCES
4117  kDebug() << "-- mItemId:" << mItemId;
4118  kDebug() << "-- mCollectionId:" << mCollectionId;
4119  kDebug() << "-- mCompatibility:" << mCompatibility;
4120  kDebug() << "-- mReadOnly:" << mReadOnly;
4121 #endif
4122  if (mReminderMinutes)
4123  {
4124  kDebug() << "-- mReminderMinutes:" << mReminderMinutes;
4125  kDebug() << "-- mReminderActive:" << (mReminderActive == ACTIVE_REMINDER ? "active" : mReminderActive == HIDDEN_REMINDER ? "hidden" : "no");
4126  kDebug() << "-- mReminderOnceOnly:" << mReminderOnceOnly;
4127  }
4128  else if (mDeferral > 0)
4129  {
4130  kDebug() << "-- mDeferral:" << (mDeferral == NORMAL_DEFERRAL ? "normal" : "reminder");
4131  kDebug() << "-- mDeferralTime:" << mDeferralTime.toString();
4132  }
4133  kDebug() << "-- mDeferDefaultMinutes:" << mDeferDefaultMinutes;
4134  if (mDeferDefaultMinutes)
4135  kDebug() << "-- mDeferDefaultDateOnly:" << mDeferDefaultDateOnly;
4136  if (mDisplaying)
4137  {
4138  kDebug() << "-- mDisplayingTime:" << mDisplayingTime.toString();
4139  kDebug() << "-- mDisplayingFlags:" << mDisplayingFlags;
4140  kDebug() << "-- mDisplayingDefer:" << mDisplayingDefer;
4141  kDebug() << "-- mDisplayingEdit:" << mDisplayingEdit;
4142  }
4143  kDebug() << "-- mRevision:" << mRevision;
4144  kDebug() << "-- mRecurrence:" << mRecurrence;
4145  if (!mRepetition)
4146  kDebug() << "-- mRepetition: 0";
4147  else if (mRepetition.isDaily())
4148  kDebug() << "-- mRepetition: count:" << mRepetition.count() << ", interval:" << mRepetition.intervalDays() << "days";
4149  else
4150  kDebug() << "-- mRepetition: count:" << mRepetition.count() << ", interval:" << mRepetition.intervalMinutes() << "minutes";
4151  kDebug() << "-- mNextRepeat:" << mNextRepeat;
4152  kDebug() << "-- mAlarmCount:" << mAlarmCount;
4153  kDebug() << "-- mMainExpired:" << mMainExpired;
4154  kDebug() << "-- mDisplaying:" << mDisplaying;
4155  kDebug() << "KAEvent dump end";
4156 }
4157 #endif
4158 
4159 
4160 /******************************************************************************
4161 * Fetch the start and next date/time for a KCal::Event.
4162 * Reply = next main date/time.
4163 */
4164 #ifndef KALARMCAL_USE_KRESOURCES
4165 DateTime KAEvent::Private::readDateTime(const Event::Ptr& event, bool dateOnly, DateTime& start)
4166 #else
4167 DateTime KAEvent::Private::readDateTime(const Event* event, bool dateOnly, DateTime& start)
4168 #endif
4169 {
4170  start = event->dtStart();
4171  if (dateOnly)
4172  {
4173  // A date-only event is indicated by the X-KDE-KALARM-FLAGS:DATE property, not
4174  // by a date-only start date/time (for the reasons given in updateKCalEvent()).
4175  start.setDateOnly(true);
4176  }
4177  DateTime next = start;
4178  QString prop = event->customProperty(KACalendar::APPNAME, Private::NEXT_RECUR_PROPERTY);
4179  if (prop.length() >= 8)
4180  {
4181  // The next due recurrence time is specified
4182  const QDate d(prop.left(4).toInt(), prop.mid(4,2).toInt(), prop.mid(6,2).toInt());
4183  if (d.isValid())
4184  {
4185  if (dateOnly && prop.length() == 8)
4186  next.setDate(d);
4187  else if (!dateOnly && prop.length() == 15 && prop[8] == QChar('T'))
4188  {
4189  const QTime t(prop.mid(9,2).toInt(), prop.mid(11,2).toInt(), prop.mid(13,2).toInt());
4190  if (t.isValid())
4191  {
4192  next.setDate(d);
4193  next.setTime(t);
4194  }
4195  }
4196  if (next < start)
4197  next = start; // ensure next recurrence time is valid
4198  }
4199  }
4200  return next;
4201 }
4202 
4203 /******************************************************************************
4204 * Parse the alarms for a KCal::Event.
4205 * Reply = map of alarm data, indexed by KAAlarm::Type
4206 */
4207 #ifndef KALARMCAL_USE_KRESOURCES
4208 void KAEvent::Private::readAlarms(const Event::Ptr& event, void* almap, bool cmdDisplay)
4209 #else
4210 void KAEvent::Private::readAlarms(const Event* event, void* almap, bool cmdDisplay)
4211 #endif
4212 {
4213  AlarmMap* alarmMap = (AlarmMap*)almap;
4214  Alarm::List alarms = event->alarms();
4215 
4216  // Check if it's an audio event with no display alarm
4217  bool audioOnly = false;
4218  for (int i = 0, end = alarms.count(); i < end; ++i)
4219  {
4220  switch (alarms[i]->type())
4221  {
4222  case Alarm::Display:
4223  case Alarm::Procedure:
4224  audioOnly = false;
4225  i = end; // exit from the 'for' loop
4226  break;
4227  case Alarm::Audio:
4228  audioOnly = true;
4229  break;
4230  default:
4231  break;
4232  }
4233  }
4234 
4235  for (int i = 0, end = alarms.count(); i < end; ++i)
4236  {
4237  // Parse the next alarm's text
4238  AlarmData data;
4239  readAlarm(alarms[i], data, audioOnly, cmdDisplay);
4240  if (data.type != INVALID_ALARM)
4241  alarmMap->insert(data.type, data);
4242  }
4243 }
4244 
4245 /******************************************************************************
4246 * Parse a KCal::Alarm.
4247 * If 'audioMain' is true, the event contains an audio alarm but no display alarm.
4248 * Reply = alarm ID (sequence number)
4249 */
4250 #ifndef KALARMCAL_USE_KRESOURCES
4251 void KAEvent::Private::readAlarm(const Alarm::Ptr& alarm, AlarmData& data, bool audioMain, bool cmdDisplay)
4252 #else
4253 void KAEvent::Private::readAlarm(const Alarm* alarm, AlarmData& data, bool audioMain, bool cmdDisplay)
4254 #endif
4255 {
4256  // Parse the next alarm's text
4257  data.alarm = alarm;
4258  data.displayingFlags = 0;
4259  data.isEmailText = false;
4260  data.speak = false;
4261  data.hiddenReminder = false;
4262  data.timedDeferral = false;
4263  data.nextRepeat = 0;
4264  data.repeatSoundPause = -1;
4265  if (alarm->repeatCount())
4266  {
4267  bool ok;
4268  const QString property = alarm->customProperty(KACalendar::APPNAME, Private::NEXT_REPEAT_PROPERTY);
4269  int n = static_cast<int>(property.toUInt(&ok));
4270  if (ok)
4271  data.nextRepeat = n;
4272  }
4273  QString property = alarm->customProperty(KACalendar::APPNAME, Private::FLAGS_PROPERTY);
4274  const QStringList flags = property.split(Private::SC, QString::SkipEmptyParts);
4275  switch (alarm->type())
4276  {
4277  case Alarm::Procedure:
4278  data.action = KAAlarm::COMMAND;
4279  data.cleanText = alarm->programFile();
4280  data.commandScript = data.cleanText.isEmpty(); // blank command indicates a script
4281  if (!alarm->programArguments().isEmpty())
4282  {
4283  if (!data.commandScript)
4284  data.cleanText += ' ';
4285  data.cleanText += alarm->programArguments();
4286  }
4287  data.extraActionOptions = 0;
4288  if (flags.contains(Private::EXEC_ON_DEFERRAL_FLAG))
4289  data.extraActionOptions |= ExecPreActOnDeferral;
4290  if (flags.contains(Private::CANCEL_ON_ERROR_FLAG))
4291  data.extraActionOptions |= CancelOnPreActError;
4292  if (flags.contains(Private::DONT_SHOW_ERROR_FLAG))
4293  data.extraActionOptions |= DontShowPreActError;
4294  if (!cmdDisplay)
4295  break;
4296  // fall through to Display
4297  case Alarm::Display:
4298  {
4299  if (alarm->type() == Alarm::Display)
4300  {
4301  data.action = KAAlarm::MESSAGE;
4302  data.cleanText = AlarmText::fromCalendarText(alarm->text(), data.isEmailText);
4303  }
4304  const QString property = alarm->customProperty(KACalendar::APPNAME, Private::FONT_COLOUR_PROPERTY);
4305  const QStringList list = property.split(QLatin1Char(';'), QString::KeepEmptyParts);
4306  data.bgColour = QColor(255, 255, 255); // white
4307  data.fgColour = QColor(0, 0, 0); // black
4308  const int n = list.count();
4309  if (n > 0)
4310  {
4311  if (!list[0].isEmpty())
4312  {
4313  QColor c(list[0]);
4314  if (c.isValid())
4315  data.bgColour = c;
4316  }
4317  if (n > 1 && !list[1].isEmpty())
4318  {
4319  QColor c(list[1]);
4320  if (c.isValid())
4321  data.fgColour = c;
4322  }
4323  }
4324  data.defaultFont = (n <= 2 || list[2].isEmpty());
4325  if (!data.defaultFont)
4326  data.font.fromString(list[2]);
4327  break;
4328  }
4329  case Alarm::Email:
4330  {
4331  data.action = KAAlarm::EMAIL;
4332  data.cleanText = alarm->mailText();
4333  const int i = flags.indexOf(Private::EMAIL_ID_FLAG);
4334  data.emailFromId = (i >= 0 && i + 1 < flags.count()) ? flags[i + 1].toUInt() : 0;
4335  break;
4336  }
4337  case Alarm::Audio:
4338  {
4339  data.action = KAAlarm::AUDIO;
4340  data.cleanText = alarm->audioFile();
4341  data.repeatSoundPause = (alarm->repeatCount() == -2) ? alarm->snoozeTime().asSeconds()
4342  : (alarm->repeatCount() == -1) ? 0 : -1;
4343  data.soundVolume = -1;
4344  data.fadeVolume = -1;
4345  data.fadeSeconds = 0;
4346  QString property = alarm->customProperty(KACalendar::APPNAME, Private::VOLUME_PROPERTY);
4347  if (!property.isEmpty())
4348  {
4349  bool ok;
4350  float fadeVolume;
4351  int fadeSecs = 0;
4352  const QStringList list = property.split(QLatin1Char(';'), QString::KeepEmptyParts);
4353  data.soundVolume = list[0].toFloat(&ok);
4354  if (!ok || data.soundVolume > 1.0f)
4355  data.soundVolume = -1;
4356  if (data.soundVolume >= 0 && list.count() >= 3)
4357  {
4358  fadeVolume = list[1].toFloat(&ok);
4359  if (ok)
4360  fadeSecs = static_cast<int>(list[2].toUInt(&ok));
4361  if (ok && fadeVolume >= 0 && fadeVolume <= 1.0f && fadeSecs > 0)
4362  {
4363  data.fadeVolume = fadeVolume;
4364  data.fadeSeconds = fadeSecs;
4365  }
4366  }
4367  }
4368  if (!audioMain)
4369  {
4370  data.type = AUDIO_ALARM;
4371  data.speak = flags.contains(Private::SPEAK_FLAG);
4372  return;
4373  }
4374  break;
4375  }
4376  case Alarm::Invalid:
4377  data.type = INVALID_ALARM;
4378  return;
4379  }
4380 
4381  bool atLogin = false;
4382  bool reminder = false;
4383  bool deferral = false;
4384  bool dateDeferral = false;
4385  bool repeatSound = false;
4386  data.type = MAIN_ALARM;
4387  property = alarm->customProperty(KACalendar::APPNAME, Private::TYPE_PROPERTY);
4388  const QStringList types = property.split(QLatin1Char(','), QString::SkipEmptyParts);
4389  for (int i = 0, end = types.count(); i < end; ++i)
4390  {
4391  const QString type = types[i];
4392  if (type == Private::AT_LOGIN_TYPE)
4393  atLogin = true;
4394  else if (type == Private::FILE_TYPE && data.action == KAAlarm::MESSAGE)
4395  data.action = KAAlarm::FILE;
4396  else if (type == Private::REMINDER_TYPE)
4397  reminder = true;
4398  else if (type == Private::TIME_DEFERRAL_TYPE)
4399  deferral = true;
4400  else if (type == Private::DATE_DEFERRAL_TYPE)
4401  dateDeferral = deferral = true;
4402  else if (type == Private::DISPLAYING_TYPE)
4403  data.type = DISPLAYING_ALARM;
4404  else if (type == Private::PRE_ACTION_TYPE && data.action == KAAlarm::COMMAND)
4405  data.type = PRE_ACTION_ALARM;
4406  else if (type == Private::POST_ACTION_TYPE && data.action == KAAlarm::COMMAND)
4407  data.type = POST_ACTION_ALARM;
4408  else if (type == Private::SOUND_REPEAT_TYPE && data.action == KAAlarm::AUDIO)
4409  repeatSound = true;
4410  }
4411  if (repeatSound && data.repeatSoundPause < 0)
4412  data.repeatSoundPause = 0;
4413  else if (!repeatSound)
4414  data.repeatSoundPause = -1;
4415 
4416  if (reminder)
4417  {
4418  if (data.type == MAIN_ALARM)
4419  {
4420  data.type = deferral ? DEFERRED_REMINDER_ALARM : REMINDER_ALARM;
4421  data.timedDeferral = (deferral && !dateDeferral);
4422  }
4423  else if (data.type == DISPLAYING_ALARM)
4424  data.displayingFlags = dateDeferral ? REMINDER | DATE_DEFERRAL
4425  : deferral ? REMINDER | TIME_DEFERRAL : REMINDER;
4426  else if (data.type == REMINDER_ALARM
4427  && flags.contains(Private::HIDDEN_REMINDER_FLAG))
4428  data.hiddenReminder = true;
4429  }
4430  else if (deferral)
4431  {
4432  if (data.type == MAIN_ALARM)
4433  {
4434  data.type = DEFERRED_ALARM;
4435  data.timedDeferral = !dateDeferral;
4436  }
4437  else if (data.type == DISPLAYING_ALARM)
4438  data.displayingFlags = dateDeferral ? DATE_DEFERRAL : TIME_DEFERRAL;
4439  }
4440  if (atLogin)
4441  {
4442  if (data.type == MAIN_ALARM)
4443  data.type = AT_LOGIN_ALARM;
4444  else if (data.type == DISPLAYING_ALARM)
4445  data.displayingFlags = REPEAT_AT_LOGIN;
4446  }
4447 //kDebug()<<"text="<<alarm->text()<<", time="<<alarm->time().toString()<<", valid time="<<alarm->time().isValid();
4448 }
4449 
4450 /******************************************************************************
4451 * Calculate the next trigger times of the alarm.
4452 * This should only be called when changes have actually occurred which might
4453 * affect the event's trigger times.
4454 * mMainTrigger is set to the next scheduled recurrence/sub-repetition, or the
4455 * deferral time if a deferral is pending.
4456 * mAllTrigger is the same as mMainTrigger, but takes account of reminders.
4457 * mMainWorkTrigger is set to the next scheduled recurrence/sub-repetition
4458 * which occurs in working hours, if working-time-only is set.
4459 * mAllWorkTrigger is the same as mMainWorkTrigger, but takes account of reminders.
4460 */
4461 void KAEvent::Private::calcTriggerTimes() const
4462 {
4463  if (mChangeCount)
4464  return;
4465 #ifdef __GNUC__
4466 #warning May need to set date-only alarms to after start-of-day time in working-time checks
4467 #endif
4468  bool recurs = (checkRecur() != KARecurrence::NO_RECUR);
4469  if ((recurs && mWorkTimeOnly && mWorkTimeOnly != mWorkTimeIndex)
4470  || (recurs && mExcludeHolidays && mExcludeHolidays != mHolidays))
4471  {
4472  // It's a work time alarm, and work days/times have changed, or
4473  // it excludes holidays, and the holidays definition has changed.
4474  mTriggerChanged = true;
4475  }
4476  else if (!mTriggerChanged)
4477  return;
4478  mTriggerChanged = false;
4479  if (recurs && mWorkTimeOnly)
4480  mWorkTimeOnly = mWorkTimeIndex; // note which work time definition was used in calculation
4481  if (recurs && mExcludeHolidays)
4482  mExcludeHolidays = mHolidays; // note which holiday definition was used in calculation
4483 
4484  if (mCategory == CalEvent::ARCHIVED || mCategory == CalEvent::TEMPLATE)
4485  {
4486  // It's a template or archived
4487  mAllTrigger = mMainTrigger = mAllWorkTrigger = mMainWorkTrigger = KDateTime();
4488  }
4489  else if (mDeferral == NORMAL_DEFERRAL)
4490  {
4491  // For a deferred alarm, working time setting is ignored
4492  mAllTrigger = mMainTrigger = mAllWorkTrigger = mMainWorkTrigger = mDeferralTime;
4493  }
4494  else
4495  {
4496  mMainTrigger = mainDateTime(true); // next recurrence or sub-repetition
4497  mAllTrigger = (mDeferral == REMINDER_DEFERRAL) ? mDeferralTime
4498  : (mReminderActive != ACTIVE_REMINDER) ? mMainTrigger
4499  : (mReminderMinutes < 0) ? mReminderAfterTime
4500  : mMainTrigger.addMins(-mReminderMinutes);
4501  // It's not deferred.
4502  // If only-during-working-time is set and it recurs, it won't actually trigger
4503  // unless it falls during working hours.
4504  if ((!mWorkTimeOnly && !mExcludeHolidays)
4505  || !recurs
4506  || isWorkingTime(mMainTrigger.kDateTime()))
4507  {
4508  // It only occurs once, or it complies with any working hours/holiday
4509  // restrictions.
4510  mMainWorkTrigger = mMainTrigger;
4511  mAllWorkTrigger = mAllTrigger;
4512  }
4513  else if (mWorkTimeOnly)
4514  {
4515  // The alarm is restricted to working hours.
4516  // Finding the next occurrence during working hours can sometimes take a long time,
4517  // so mark the next actual trigger as invalid until the calculation completes.
4518  // Note that reminders are only triggered if the main alarm is during working time.
4519  if (!mExcludeHolidays)
4520  {
4521  // There are no holiday restrictions.
4522  calcNextWorkingTime(mMainTrigger);
4523  }
4524  else if (mHolidays)
4525  {
4526  // Holidays are excluded.
4527  DateTime nextTrigger = mMainTrigger;
4528  KDateTime kdt;
4529  for (int i = 0; i < 20; ++i)
4530  {
4531  calcNextWorkingTime(nextTrigger);
4532  if (!mHolidays->isHoliday(mMainWorkTrigger.date()))
4533  return; // found a non-holiday occurrence
4534  kdt = mMainWorkTrigger.effectiveKDateTime();
4535  kdt.setTime(QTime(23,59,59));
4536  const OccurType type = nextOccurrence(kdt, nextTrigger, RETURN_REPETITION);
4537  if (!nextTrigger.isValid())
4538  break;
4539  if (isWorkingTime(nextTrigger.kDateTime()))
4540  {
4541  const int reminder = (mReminderMinutes > 0) ? mReminderMinutes : 0; // only interested in reminders BEFORE the alarm
4542  mMainWorkTrigger = nextTrigger;
4543  mAllWorkTrigger = (type & OCCURRENCE_REPEAT) ? mMainWorkTrigger : mMainWorkTrigger.addMins(-reminder);
4544  return; // found a non-holiday occurrence
4545  }
4546  }
4547  mMainWorkTrigger = mAllWorkTrigger = DateTime();
4548  }
4549  }
4550  else if (mExcludeHolidays && mHolidays)
4551  {
4552  // Holidays are excluded.
4553  DateTime nextTrigger = mMainTrigger;
4554  KDateTime kdt;
4555  for (int i = 0; i < 20; ++i)
4556  {
4557  kdt = nextTrigger.effectiveKDateTime();
4558  kdt.setTime(QTime(23,59,59));
4559  const OccurType type = nextOccurrence(kdt, nextTrigger, RETURN_REPETITION);
4560  if (!nextTrigger.isValid())
4561  break;
4562  if (!mHolidays->isHoliday(nextTrigger.date()))
4563  {
4564  const int reminder = (mReminderMinutes > 0) ? mReminderMinutes : 0; // only interested in reminders BEFORE the alarm
4565  mMainWorkTrigger = nextTrigger;
4566  mAllWorkTrigger = (type & OCCURRENCE_REPEAT) ? mMainWorkTrigger : mMainWorkTrigger.addMins(-reminder);
4567  return; // found a non-holiday occurrence
4568  }
4569  }
4570  mMainWorkTrigger = mAllWorkTrigger = DateTime();
4571  }
4572  }
4573 }
4574 
4575 /******************************************************************************
4576 * Return the time of the next scheduled occurrence of the event during working
4577 * hours, for an alarm which is restricted to working hours.
4578 * On entry, 'nextTrigger' = the next recurrence or repetition (as returned by
4579 * mainDateTime(true) ).
4580 */
4581 void KAEvent::Private::calcNextWorkingTime(const DateTime& nextTrigger) const
4582 {
4583  kDebug() << "next=" << nextTrigger.kDateTime().dateTime();
4584  mMainWorkTrigger = mAllWorkTrigger = DateTime();
4585 
4586  for (int i = 0; ; ++i)
4587  {
4588  if (i >= 7)
4589  return; // no working days are defined
4590  if (mWorkDays.testBit(i))
4591  break;
4592  }
4593  const KARecurrence::Type recurType = checkRecur();
4594  KDateTime kdt = nextTrigger.effectiveKDateTime();
4595  const int reminder = (mReminderMinutes > 0) ? mReminderMinutes : 0; // only interested in reminders BEFORE the alarm
4596  // Check if it always falls on the same day(s) of the week.
4597  const RecurrenceRule* rrule = mRecurrence->defaultRRuleConst();
4598  if (!rrule)
4599  return; // no recurrence rule!
4600  unsigned allDaysMask = 0x7F; // mask bits for all days of week
4601  bool noWorkPos = false; // true if no recurrence day position is working day
4602  const QList<RecurrenceRule::WDayPos> pos = rrule->byDays();
4603  const int nDayPos = pos.count(); // number of day positions
4604  if (nDayPos)
4605  {
4606  noWorkPos = true;
4607  allDaysMask = 0;
4608  for (int i = 0; i < nDayPos; ++i)
4609  {
4610  const int day = pos[i].day() - 1; // Monday = 0
4611  if (mWorkDays.testBit(day))
4612  noWorkPos = false; // found a working day occurrence
4613  allDaysMask |= 1 << day;
4614  }
4615  if (noWorkPos && !mRepetition)
4616  return; // never occurs on a working day
4617  }
4618  DateTime newdt;
4619 
4620  if (mStartDateTime.isDateOnly())
4621  {
4622  // It's a date-only alarm.
4623  // Sub-repetitions also have to be date-only.
4624  const int repeatFreq = mRepetition.intervalDays();
4625  const bool weeklyRepeat = mRepetition && !(repeatFreq % 7);
4626  const Duration interval = mRecurrence->regularInterval();
4627  if ((interval && !(interval.asDays() % 7))
4628  || nDayPos == 1)
4629  {
4630  // It recurs on the same day each week
4631  if (!mRepetition || weeklyRepeat)
4632  return; // any repetitions are also weekly
4633 
4634  // It's a weekly recurrence with a non-weekly sub-repetition.
4635  // Check one cycle of repetitions for the next one that lands
4636  // on a working day.
4637  KDateTime dt(nextTrigger.kDateTime().addDays(1));
4638  dt.setTime(QTime(0,0,0));
4639  previousOccurrence(dt, newdt, false);
4640  if (!newdt.isValid())
4641  return; // this should never happen
4642  kdt = newdt.effectiveKDateTime();
4643  const int day = kdt.date().dayOfWeek() - 1; // Monday = 0
4644  for (int repeatNum = mNextRepeat + 1; ; ++repeatNum)
4645  {
4646  if (repeatNum > mRepetition.count())
4647  repeatNum = 0;
4648  if (repeatNum == mNextRepeat)
4649  break;
4650  if (!repeatNum)
4651  {
4652  nextOccurrence(newdt.kDateTime(), newdt, IGNORE_REPETITION);
4653  if (mWorkDays.testBit(day))
4654  {
4655  mMainWorkTrigger = newdt;
4656  mAllWorkTrigger = mMainWorkTrigger.addMins(-reminder);
4657  return;
4658  }
4659  kdt = newdt.effectiveKDateTime();
4660  }
4661  else
4662  {
4663  const int inc = repeatFreq * repeatNum;
4664  if (mWorkDays.testBit((day + inc) % 7))
4665  {
4666  kdt = kdt.addDays(inc);
4667  kdt.setDateOnly(true);
4668  mMainWorkTrigger = mAllWorkTrigger = kdt;
4669  return;
4670  }
4671  }
4672  }
4673  return;
4674  }
4675  if (!mRepetition || weeklyRepeat)
4676  {
4677  // It's a date-only alarm with either no sub-repetition or a
4678  // sub-repetition which always falls on the same day of the week
4679  // as the recurrence (if any).
4680  unsigned days = 0;
4681  for ( ; ; )
4682  {
4683  kdt.setTime(QTime(23,59,59));
4684  nextOccurrence(kdt, newdt, IGNORE_REPETITION);
4685  if (!newdt.isValid())
4686  return;
4687  kdt = newdt.effectiveKDateTime();
4688  const int day = kdt.date().dayOfWeek() - 1;
4689  if (mWorkDays.testBit(day))
4690  break; // found a working day occurrence
4691  // Prevent indefinite looping (which should never happen anyway)
4692  if ((days & allDaysMask) == allDaysMask)
4693  return; // found a recurrence on every possible day of the week!?!
4694  days |= 1 << day;
4695  }
4696  kdt.setDateOnly(true);
4697  mMainWorkTrigger = kdt;
4698  mAllWorkTrigger = kdt.addSecs(-60 * reminder);
4699  return;
4700  }
4701 
4702  // It's a date-only alarm which recurs on different days of the week,
4703  // as does the sub-repetition.
4704  // Find the previous recurrence (as opposed to sub-repetition)
4705  unsigned days = 1 << (kdt.date().dayOfWeek() - 1);
4706  KDateTime dt(nextTrigger.kDateTime().addDays(1));
4707  dt.setTime(QTime(0,0,0));
4708  previousOccurrence(dt, newdt, false);
4709  if (!newdt.isValid())
4710  return; // this should never happen
4711  kdt = newdt.effectiveKDateTime();
4712  int day = kdt.date().dayOfWeek() - 1; // Monday = 0
4713  for (int repeatNum = mNextRepeat; ; repeatNum = 0)
4714  {
4715  while (++repeatNum <= mRepetition.count())
4716  {
4717  const int inc = repeatFreq * repeatNum;
4718  if (mWorkDays.testBit((day + inc) % 7))
4719  {
4720  kdt = kdt.addDays(inc);
4721  kdt.setDateOnly(true);
4722  mMainWorkTrigger = mAllWorkTrigger = kdt;
4723  return;
4724  }
4725  if ((days & allDaysMask) == allDaysMask)
4726  return; // found an occurrence on every possible day of the week!?!
4727  days |= 1 << day;
4728  }
4729  nextOccurrence(kdt, newdt, IGNORE_REPETITION);
4730  if (!newdt.isValid())
4731  return;
4732  kdt = newdt.effectiveKDateTime();
4733  day = kdt.date().dayOfWeek() - 1;
4734  if (mWorkDays.testBit(day))
4735  {
4736  kdt.setDateOnly(true);
4737  mMainWorkTrigger = kdt;
4738  mAllWorkTrigger = kdt.addSecs(-60 * reminder);
4739  return;
4740  }
4741  if ((days & allDaysMask) == allDaysMask)
4742  return; // found an occurrence on every possible day of the week!?!
4743  days |= 1 << day;
4744  }
4745  return;
4746  }
4747 
4748  // It's a date-time alarm.
4749 
4750  /* Check whether the recurrence or sub-repetition occurs at the same time
4751  * every day. Note that because of seasonal time changes, a recurrence
4752  * defined in terms of minutes will vary its time of day even if its value
4753  * is a multiple of a day (24*60 minutes). Sub-repetitions are considered
4754  * to repeat at the same time of day regardless of time changes if they
4755  * are multiples of a day, which doesn't strictly conform to the iCalendar
4756  * format because this only allows their interval to be recorded in seconds.
4757  */
4758  const bool recurTimeVaries = (recurType == KARecurrence::MINUTELY);
4759  const bool repeatTimeVaries = (mRepetition && !mRepetition.isDaily());
4760 
4761  if (!recurTimeVaries && !repeatTimeVaries)
4762  {
4763  // The alarm always occurs at the same time of day.
4764  // Check whether it can ever occur during working hours.
4765  if (!mayOccurDailyDuringWork(kdt))
4766  return; // never occurs during working hours
4767 
4768  // Find the next working day it occurs on
4769  bool repetition = false;
4770  unsigned days = 0;
4771  for ( ; ; )
4772  {
4773  OccurType type = nextOccurrence(kdt, newdt, RETURN_REPETITION);
4774  if (!newdt.isValid())
4775  return;
4776  repetition = (type & OCCURRENCE_REPEAT);
4777  kdt = newdt.effectiveKDateTime();
4778  const int day = kdt.date().dayOfWeek() - 1;
4779  if (mWorkDays.testBit(day))
4780  break; // found a working day occurrence
4781  // Prevent indefinite looping (which should never happen anyway)
4782  if (!repetition)
4783  {
4784  if ((days & allDaysMask) == allDaysMask)
4785  return; // found a recurrence on every possible day of the week!?!
4786  days |= 1 << day;
4787  }
4788  }
4789  mMainWorkTrigger = nextTrigger;
4790  mMainWorkTrigger.setDate(kdt.date());
4791  mAllWorkTrigger = repetition ? mMainWorkTrigger : mMainWorkTrigger.addMins(-reminder);
4792  return;
4793  }
4794 
4795  // The alarm occurs at different times of day.
4796  // We may need to check for a full annual cycle of seasonal time changes, in
4797  // case it only occurs during working hours after a time change.
4798  KTimeZone tz = kdt.timeZone();
4799  if (tz.isValid() && tz.type() == "KSystemTimeZone")
4800  {
4801  // It's a system time zone, so fetch full transition information
4802  const KTimeZone ktz = KSystemTimeZones::readZone(tz.name());
4803  if (ktz.isValid())
4804  tz = ktz;
4805  }
4806  const QList<KTimeZone::Transition> tzTransitions = tz.transitions();
4807 
4808  if (recurTimeVaries)
4809  {
4810  /* The alarm recurs at regular clock intervals, at different times of day.
4811  * Note that for this type of recurrence, it's necessary to avoid the
4812  * performance overhead of Recurrence class calls since these can in the
4813  * worst case cause the program to hang for a significant length of time.
4814  * In this case, we can calculate the next recurrence by simply adding the
4815  * recurrence interval, since KAlarm offers no facility to regularly miss
4816  * recurrences. (But exception dates/times need to be taken into account.)
4817  */
4818  KDateTime kdtRecur;
4819  int repeatFreq = 0;
4820  int repeatNum = 0;
4821  if (mRepetition)
4822  {
4823  // It's a repetition inside a recurrence, each of which occurs
4824  // at different times of day (bearing in mind that the repetition
4825  // may occur at daily intervals after each recurrence).
4826  // Find the previous recurrence (as opposed to sub-repetition)
4827  repeatFreq = mRepetition.intervalSeconds();
4828  previousOccurrence(kdt.addSecs(1), newdt, false);
4829  if (!newdt.isValid())
4830  return; // this should never happen
4831  kdtRecur = newdt.effectiveKDateTime();
4832  repeatNum = kdtRecur.secsTo(kdt) / repeatFreq;
4833  kdt = kdtRecur.addSecs(repeatNum * repeatFreq);
4834  }
4835  else
4836  {
4837  // There is no sub-repetition.
4838  // (N.B. Sub-repetitions can't exist without a recurrence.)
4839  // Check until the original time wraps round, but ensure that
4840  // if there are seasonal time changes, that all other subsequent
4841  // time offsets within the next year are checked.
4842  // This does not guarantee to find the next working time,
4843  // particularly if there are exceptions, but it's a
4844  // reasonable try.
4845  kdtRecur = kdt;
4846  }
4847  QTime firstTime = kdtRecur.time();
4848  int firstOffset = kdtRecur.utcOffset();
4849  int currentOffset = firstOffset;
4850  int dayRecur = kdtRecur.date().dayOfWeek() - 1; // Monday = 0
4851  int firstDay = dayRecur;
4852  QDate finalDate;
4853  const bool subdaily = (repeatFreq < 24*3600);
4854 // int period = mRecurrence->frequency() % (24*60); // it is by definition a MINUTELY recurrence
4855 // int limit = (24*60 + period - 1) / period; // number of times until recurrence wraps round
4856  int transitionIndex = -1;
4857  for (int n = 0; n < 7*24*60; ++n)
4858  {
4859  if (mRepetition)
4860  {
4861  // Check the sub-repetitions for this recurrence
4862  for ( ; ; )
4863  {
4864  // Find the repeat count to the next start of the working day
4865  const int inc = subdaily ? nextWorkRepetition(kdt) : 1;
4866  repeatNum += inc;
4867  if (repeatNum > mRepetition.count())
4868  break;
4869  kdt = kdt.addSecs(inc * repeatFreq);
4870  const QTime t = kdt.time();
4871  if (t >= mWorkDayStart && t < mWorkDayEnd)
4872  {
4873  if (mWorkDays.testBit(kdt.date().dayOfWeek() - 1))
4874  {
4875  mMainWorkTrigger = mAllWorkTrigger = kdt;
4876  return;
4877  }
4878  }
4879  }
4880  repeatNum = 0;
4881  }
4882  nextOccurrence(kdtRecur, newdt, IGNORE_REPETITION);
4883  if (!newdt.isValid())
4884  return;
4885  kdtRecur = newdt.effectiveKDateTime();
4886  dayRecur = kdtRecur.date().dayOfWeek() - 1; // Monday = 0
4887  const QTime t = kdtRecur.time();
4888  if (t >= mWorkDayStart && t < mWorkDayEnd)
4889  {
4890  if (mWorkDays.testBit(dayRecur))
4891  {
4892  mMainWorkTrigger = kdtRecur;
4893  mAllWorkTrigger = kdtRecur.addSecs(-60 * reminder);
4894  return;
4895  }
4896  }
4897  if (kdtRecur.utcOffset() != currentOffset)
4898  currentOffset = kdtRecur.utcOffset();
4899  if (t == firstTime && dayRecur == firstDay && currentOffset == firstOffset)
4900  {
4901  // We've wrapped round to the starting day and time.
4902  // If there are seasonal time changes, check for up
4903  // to the next year in other time offsets in case the
4904  // alarm occurs inside working hours then.
4905  if (!finalDate.isValid())
4906  finalDate = kdtRecur.date();
4907  const int i = tz.transitionIndex(kdtRecur.toUtc().dateTime());
4908  if (i < 0)
4909  return;
4910  if (i > transitionIndex)
4911  transitionIndex = i;
4912  if (++transitionIndex >= static_cast<int>(tzTransitions.count()))
4913  return;
4914  previousOccurrence(KDateTime(tzTransitions[transitionIndex].time(), KDateTime::UTC), newdt, IGNORE_REPETITION);
4915  kdtRecur = newdt.effectiveKDateTime();
4916  if (finalDate.daysTo(kdtRecur.date()) > 365)
4917  return;
4918  firstTime = kdtRecur.time();
4919  firstOffset = kdtRecur.utcOffset();
4920  currentOffset = firstOffset;
4921  firstDay = kdtRecur.date().dayOfWeek() - 1;
4922  }
4923  kdt = kdtRecur;
4924  }
4925 //kDebug()<<"-----exit loop: count="<<limit<<endl;
4926  return; // too many iterations
4927  }
4928 
4929  if (repeatTimeVaries)
4930  {
4931  /* There's a sub-repetition which occurs at different times of
4932  * day, inside a recurrence which occurs at the same time of day.
4933  * We potentially need to check recurrences starting on each day.
4934  * Then, it is still possible that a working time sub-repetition
4935  * could occur immediately after a seasonal time change.
4936  */
4937  // Find the previous recurrence (as opposed to sub-repetition)
4938  const int repeatFreq = mRepetition.intervalSeconds();
4939  previousOccurrence(kdt.addSecs(1), newdt, false);
4940  if (!newdt.isValid())
4941  return; // this should never happen
4942  KDateTime kdtRecur = newdt.effectiveKDateTime();
4943  const bool recurDuringWork = (kdtRecur.time() >= mWorkDayStart && kdtRecur.time() < mWorkDayEnd);
4944 
4945  // Use the previous recurrence as a base for checking whether
4946  // our tests have wrapped round to the same time/day of week.
4947  const bool subdaily = (repeatFreq < 24*3600);
4948  unsigned days = 0;
4949  bool checkTimeChangeOnly = false;
4950  int transitionIndex = -1;
4951  for (int limit = 10; --limit >= 0; )
4952  {
4953  // Check the next seasonal time change (for an arbitrary 10 times,
4954  // even though that might not guarantee the correct result)
4955  QDate dateRecur = kdtRecur.date();
4956  int dayRecur = dateRecur.dayOfWeek() - 1; // Monday = 0
4957  int repeatNum = kdtRecur.secsTo(kdt) / repeatFreq;
4958  kdt = kdtRecur.addSecs(repeatNum * repeatFreq);
4959 
4960  // Find the next recurrence, which sets the limit on possible sub-repetitions.
4961  // Note that for a monthly recurrence, for example, a sub-repetition could
4962  // be defined which is longer than the recurrence interval in short months.
4963  // In these cases, the sub-repetition is truncated by the following
4964  // recurrence.
4965  nextOccurrence(kdtRecur, newdt, IGNORE_REPETITION);
4966  KDateTime kdtNextRecur = newdt.effectiveKDateTime();
4967 
4968  int repeatsToCheck = mRepetition.count();
4969  int repeatsDuringWork = 0; // 0=unknown, 1=does, -1=never
4970  for ( ; ; )
4971  {
4972  // Check the sub-repetitions for this recurrence
4973  if (repeatsDuringWork >= 0)
4974  {
4975  for ( ; ; )
4976  {
4977  // Find the repeat count to the next start of the working day
4978  int inc = subdaily ? nextWorkRepetition(kdt) : 1;
4979  repeatNum += inc;
4980  const bool pastEnd = (repeatNum > mRepetition.count());
4981  if (pastEnd)
4982  inc -= repeatNum - mRepetition.count();
4983  repeatsToCheck -= inc;
4984  kdt = kdt.addSecs(inc * repeatFreq);
4985  if (kdtNextRecur.isValid() && kdt >= kdtNextRecur)
4986  {
4987  // This sub-repetition is past the next recurrence,
4988  // so start the check again from the next recurrence.
4989  repeatsToCheck = mRepetition.count();
4990  break;
4991  }
4992  if (pastEnd)
4993  break;
4994  const QTime t = kdt.time();
4995  if (t >= mWorkDayStart && t < mWorkDayEnd)
4996  {
4997  if (mWorkDays.testBit(kdt.date().dayOfWeek() - 1))
4998  {
4999  mMainWorkTrigger = mAllWorkTrigger = kdt;
5000  return;
5001  }
5002  repeatsDuringWork = 1;
5003  }
5004  else if (!repeatsDuringWork && repeatsToCheck <= 0)
5005  {
5006  // Sub-repetitions never occur during working hours
5007  repeatsDuringWork = -1;
5008  break;
5009  }
5010  }
5011  }
5012  repeatNum = 0;
5013  if (repeatsDuringWork < 0 && !recurDuringWork)
5014  break; // it never occurs during working hours
5015 
5016  // Check the next recurrence
5017  if (!kdtNextRecur.isValid())
5018  return;
5019  if (checkTimeChangeOnly || (days & allDaysMask) == allDaysMask)
5020  break; // found a recurrence on every possible day of the week!?!
5021  kdtRecur = kdtNextRecur;
5022  nextOccurrence(kdtRecur, newdt, IGNORE_REPETITION);
5023  kdtNextRecur = newdt.effectiveKDateTime();
5024  dateRecur = kdtRecur.date();
5025  dayRecur = dateRecur.dayOfWeek() - 1;
5026  if (recurDuringWork && mWorkDays.testBit(dayRecur))
5027  {
5028  mMainWorkTrigger = kdtRecur;
5029  mAllWorkTrigger = kdtRecur.addSecs(-60 * reminder);
5030  return;
5031  }
5032  days |= 1 << dayRecur;
5033  kdt = kdtRecur;
5034  }
5035 
5036  // Find the next recurrence before a seasonal time change,
5037  // and ensure the time change is after the last one processed.
5038  checkTimeChangeOnly = true;
5039  const int i = tz.transitionIndex(kdtRecur.toUtc().dateTime());
5040  if (i < 0)
5041  return;
5042  if (i > transitionIndex)
5043  transitionIndex = i;
5044  if (++transitionIndex >= static_cast<int>(tzTransitions.count()))
5045  return;
5046  kdt = KDateTime(tzTransitions[transitionIndex].time(), KDateTime::UTC);
5047  previousOccurrence(kdt, newdt, IGNORE_REPETITION);
5048  kdtRecur = newdt.effectiveKDateTime();
5049  }
5050  return; // not found - give up
5051  }
5052 }
5053 
5054 /******************************************************************************
5055 * Find the repeat count to the next start of a working day.
5056 * This allows for possible daylight saving time changes during the repetition.
5057 * Use for repetitions which occur at different times of day.
5058 */
5059 int KAEvent::Private::nextWorkRepetition(const KDateTime& pre) const
5060 {
5061  KDateTime nextWork(pre);
5062  if (pre.time() < mWorkDayStart)
5063  nextWork.setTime(mWorkDayStart);
5064  else
5065  {
5066  const int preDay = pre.date().dayOfWeek() - 1; // Monday = 0
5067  for (int n = 1; ; ++n)
5068  {
5069  if (n >= 7)
5070  return mRepetition.count() + 1; // should never happen
5071  if (mWorkDays.testBit((preDay + n) % 7))
5072  {
5073  nextWork = nextWork.addDays(n);
5074  nextWork.setTime(mWorkDayStart);
5075  break;
5076  }
5077  }
5078  }
5079  return (pre.secsTo(nextWork) - 1) / mRepetition.intervalSeconds() + 1;
5080 }
5081 
5082 /******************************************************************************
5083 * Check whether an alarm which recurs at the same time of day can possibly
5084 * occur during working hours.
5085 * This does not determine whether it actually does, but rather whether it could
5086 * potentially given enough repetitions.
5087 * Reply = false if it can never occur during working hours, true if it might.
5088 */
5089 bool KAEvent::Private::mayOccurDailyDuringWork(const KDateTime& kdt) const
5090 {
5091  if (!kdt.isDateOnly()
5092  && (kdt.time() < mWorkDayStart || kdt.time() >= mWorkDayEnd))
5093  return false; // its time is outside working hours
5094  // Check if it always occurs on the same day of the week
5095  const Duration interval = mRecurrence->regularInterval();
5096  if (interval && interval.isDaily() && !(interval.asDays() % 7))
5097  {
5098  // It recurs weekly
5099  if (!mRepetition || (mRepetition.isDaily() && !(mRepetition.intervalDays() % 7)))
5100  return false; // any repetitions are also weekly
5101  // Repetitions are daily. Check if any occur on working days
5102  // by checking the first recurrence and up to 6 repetitions.
5103  int day = mRecurrence->startDateTime().date().dayOfWeek() - 1; // Monday = 0
5104  const int repeatDays = mRepetition.intervalDays();
5105  const int maxRepeat = (mRepetition.count() < 6) ? mRepetition.count() : 6;
5106  for (int i = 0; !mWorkDays.testBit(day); ++i, day = (day + repeatDays) % 7)
5107  {
5108  if (i >= maxRepeat)
5109  return false; // no working day occurrences
5110  }
5111  }
5112  return true;
5113 }
5114 
5115 /******************************************************************************
5116 * Set the specified alarm to be an audio alarm with the given file name.
5117 */
5118 #ifndef KALARMCAL_USE_KRESOURCES
5119 void KAEvent::Private::setAudioAlarm(const Alarm::Ptr& alarm) const
5120 #else
5121 void KAEvent::Private::setAudioAlarm(Alarm* alarm) const
5122 #endif
5123 {
5124  alarm->setAudioAlarm(mAudioFile); // empty for a beep or for speaking
5125  if (mSoundVolume >= 0)
5126  alarm->setCustomProperty(KACalendar::APPNAME, VOLUME_PROPERTY,
5127  QString::fromLatin1("%1;%2;%3;%4").arg(QString::number(mSoundVolume, 'f', 2))
5128  .arg(QString::number(mFadeVolume, 'f', 2))
5129  .arg(mFadeSeconds));
5130 }
5131 
5132 /******************************************************************************
5133 * Get the date/time of the next recurrence of the event, after the specified
5134 * date/time.
5135 * 'result' = date/time of next occurrence, or invalid date/time if none.
5136 */
5137 KAEvent::OccurType KAEvent::Private::nextRecurrence(const KDateTime& preDateTime, DateTime& result) const
5138 {
5139  const KDateTime recurStart = mRecurrence->startDateTime();
5140  KDateTime pre = preDateTime.toTimeSpec(mStartDateTime.timeSpec());
5141  if (mStartDateTime.isDateOnly() && !pre.isDateOnly() && pre.time() < DateTime::startOfDay())
5142  {
5143  pre = pre.addDays(-1); // today's recurrence (if today recurs) is still to come
5144  pre.setTime(DateTime::startOfDay());
5145  }
5146  const KDateTime dt = mRecurrence->getNextDateTime(pre);
5147  result = dt;
5148  result.setDateOnly(mStartDateTime.isDateOnly());
5149  if (!dt.isValid())
5150  return NO_OCCURRENCE;
5151  if (dt == recurStart)
5152  return FIRST_OR_ONLY_OCCURRENCE;
5153  if (mRecurrence->duration() >= 0 && dt == mRecurrence->endDateTime())
5154  return LAST_RECURRENCE;
5155  return result.isDateOnly() ? RECURRENCE_DATE : RECURRENCE_DATE_TIME;
5156 }
5157 
5158 /******************************************************************************
5159 * Validate the event's recurrence data, correcting any inconsistencies (which
5160 * should never occur!).
5161 * Reply = recurrence period type.
5162 */
5163 KARecurrence::Type KAEvent::Private::checkRecur() const
5164 {
5165  if (mRecurrence)
5166  {
5167  KARecurrence::Type type = mRecurrence->type();
5168  switch (type)
5169  {
5170  case KARecurrence::MINUTELY: // hourly
5171  case KARecurrence::DAILY: // daily
5172  case KARecurrence::WEEKLY: // weekly on multiple days of week
5173  case KARecurrence::MONTHLY_DAY: // monthly on multiple dates in month
5174  case KARecurrence::MONTHLY_POS: // monthly on multiple nth day of week
5175  case KARecurrence::ANNUAL_DATE: // annually on multiple months (day of month = start date)
5176  case KARecurrence::ANNUAL_POS: // annually on multiple nth day of week in multiple months
5177  return type;
5178  default:
5179  if (mRecurrence)
5180  const_cast<KAEvent::Private*>(this)->clearRecur(); // this shouldn't ever be necessary!!
5181  break;
5182  }
5183  }
5184  if (mRepetition) // can't have a repetition without a recurrence
5185  const_cast<KAEvent::Private*>(this)->clearRecur(); // this shouldn't ever be necessary!!
5186  return KARecurrence::NO_RECUR;
5187 }
5188 
5189 /******************************************************************************
5190 * If the calendar was written by a previous version of KAlarm, do any
5191 * necessary format conversions on the events to ensure that when the calendar
5192 * is saved, no information is lost or corrupted.
5193 * Reply = true if any conversions were done.
5194 */
5195 #ifndef KALARMCAL_USE_KRESOURCES
5196 bool KAEvent::convertKCalEvents(const Calendar::Ptr& calendar, int calendarVersion)
5197 #else
5198 bool KAEvent::convertKCalEvents(CalendarLocal& calendar, int calendarVersion)
5199 #endif
5200 {
5201  // KAlarm pre-0.9 codes held in the alarm's DESCRIPTION property
5202  static const QChar SEPARATOR = QLatin1Char(';');
5203  static const QChar LATE_CANCEL_CODE = QLatin1Char('C');
5204  static const QChar AT_LOGIN_CODE = QLatin1Char('L'); // subsidiary alarm at every login
5205  static const QChar DEFERRAL_CODE = QLatin1Char('D'); // extra deferred alarm
5206  static const QString TEXT_PREFIX = QLatin1String("TEXT:");
5207  static const QString FILE_PREFIX = QLatin1String("FILE:");
5208  static const QString COMMAND_PREFIX = QLatin1String("CMD:");
5209 
5210  // KAlarm pre-0.9.2 codes held in the event's CATEGORY property
5211  static const QString BEEP_CATEGORY = QLatin1String("BEEP");
5212 
5213  // KAlarm pre-1.1.1 LATECANCEL category with no parameter
5214  static const QString LATE_CANCEL_CAT = QLatin1String("LATECANCEL");
5215 
5216  // KAlarm pre-1.3.0 TMPLDEFTIME category with no parameter
5217  static const QString TEMPL_DEF_TIME_CAT = QLatin1String("TMPLDEFTIME");
5218 
5219  // KAlarm pre-1.3.1 XTERM category
5220  static const QString EXEC_IN_XTERM_CAT = QLatin1String("XTERM");
5221 
5222  // KAlarm pre-1.9.0 categories
5223  static const QString DATE_ONLY_CATEGORY = QLatin1String("DATE");
5224  static const QString EMAIL_BCC_CATEGORY = QLatin1String("BCC");
5225  static const QString CONFIRM_ACK_CATEGORY = QLatin1String("ACKCONF");
5226  static const QString KORGANIZER_CATEGORY = QLatin1String("KORG");
5227  static const QString DEFER_CATEGORY = QLatin1String("DEFER;");
5228  static const QString ARCHIVE_CATEGORY = QLatin1String("SAVE");
5229  static const QString ARCHIVE_CATEGORIES = QLatin1String("SAVE:");
5230  static const QString LATE_CANCEL_CATEGORY = QLatin1String("LATECANCEL;");
5231  static const QString AUTO_CLOSE_CATEGORY = QLatin1String("LATECLOSE;");
5232  static const QString TEMPL_AFTER_TIME_CATEGORY = QLatin1String("TMPLAFTTIME;");
5233  static const QString KMAIL_SERNUM_CATEGORY = QLatin1String("KMAIL:");
5234  static const QString LOG_CATEGORY = QLatin1String("LOG:");
5235 
5236  // KAlarm pre-1.5.0/1.9.9 properties
5237  static const QByteArray KMAIL_ID_PROPERTY("KMAILID"); // X-KDE-KALARM-KMAILID property
5238 
5239  // KAlarm pre-2.6.0 properties
5240  static const QByteArray ARCHIVE_PROPERTY("ARCHIVE"); // X-KDE-KALARM-ARCHIVE property
5241  static const QString ARCHIVE_REMINDER_ONCE_TYPE = QLatin1String("ONCE");
5242  static const QString REMINDER_ONCE_TYPE = QLatin1String("REMINDER_ONCE");
5243  static const QByteArray EMAIL_ID_PROPERTY("EMAILID"); // X-KDE-KALARM-EMAILID property
5244  static const QByteArray SPEAK_PROPERTY("SPEAK"); // X-KDE-KALARM-SPEAK property
5245  static const QByteArray CANCEL_ON_ERROR_PROPERTY("ERRCANCEL");// X-KDE-KALARM-ERRCANCEL property
5246  static const QByteArray DONT_SHOW_ERROR_PROPERTY("ERRNOSHOW");// X-KDE-KALARM-ERRNOSHOW property
5247 
5248  bool adjustSummerTime = false;
5249  if (calendarVersion == -Version(0,5,7))
5250  {
5251  // The calendar file was written by the KDE 3.0.0 version of KAlarm 0.5.7.
5252  // Summer time was ignored when converting to UTC.
5253  calendarVersion = -calendarVersion;
5254  adjustSummerTime = true;
5255  }
5256 
5257  if (calendarVersion >= currentCalendarVersion())
5258  return false;
5259 
5260  kDebug() << "Adjusting version" << calendarVersion;
5261  const bool pre_0_7 = (calendarVersion < Version(0,7,0));
5262  const bool pre_0_9 = (calendarVersion < Version(0,9,0));
5263  const bool pre_0_9_2 = (calendarVersion < Version(0,9,2));
5264  const bool pre_1_1_1 = (calendarVersion < Version(1,1,1));
5265  const bool pre_1_2_1 = (calendarVersion < Version(1,2,1));
5266  const bool pre_1_3_0 = (calendarVersion < Version(1,3,0));
5267  const bool pre_1_3_1 = (calendarVersion < Version(1,3,1));
5268  const bool pre_1_4_14 = (calendarVersion < Version(1,4,14));
5269  const bool pre_1_5_0 = (calendarVersion < Version(1,5,0));
5270  const bool pre_1_9_0 = (calendarVersion < Version(1,9,0));
5271  const bool pre_1_9_2 = (calendarVersion < Version(1,9,2));
5272  const bool pre_1_9_7 = (calendarVersion < Version(1,9,7));
5273  const bool pre_1_9_9 = (calendarVersion < Version(1,9,9));
5274  const bool pre_1_9_10 = (calendarVersion < Version(1,9,10));
5275  const bool pre_2_2_9 = (calendarVersion < Version(2,2,9));
5276  const bool pre_2_3_0 = (calendarVersion < Version(2,3,0));
5277  const bool pre_2_3_2 = (calendarVersion < Version(2,3,2));
5278  const bool pre_2_7_0 = (calendarVersion < Version(2,7,0));
5279  Q_ASSERT(currentCalendarVersion() == Version(2,7,0));
5280 
5281  KTimeZone localZone;
5282  if (pre_1_9_2)
5283  localZone = KSystemTimeZones::local();
5284 
5285  bool converted = false;
5286 #ifndef KALARMCAL_USE_KRESOURCES
5287  const Event::List events = calendar->rawEvents();
5288 #else
5289  const Event::List events = calendar.rawEvents();
5290 #endif
5291  for (int ei = 0, eend = events.count(); ei < eend; ++ei)
5292  {
5293 #ifndef KALARMCAL_USE_KRESOURCES
5294  Event::Ptr event = events[ei];
5295 #else
5296  Event* event = events[ei];
5297 #endif
5298  const Alarm::List alarms = event->alarms();
5299  if (alarms.isEmpty())
5300  continue; // KAlarm isn't interested in events without alarms
5301  event->startUpdates(); // prevent multiple update notifications
5302  const bool readOnly = event->isReadOnly();
5303  if (readOnly)
5304  event->setReadOnly(false);
5305  QStringList cats = event->categories();
5306  bool addLateCancel = false;
5307  QStringList flags;
5308 
5309  if (pre_0_7 && event->allDay())
5310  {
5311  // It's a KAlarm pre-0.7 calendar file.
5312  // Ensure that when the calendar is saved, the alarm time isn't lost.
5313  event->setAllDay(false);
5314  }
5315 
5316  if (pre_0_9)
5317  {
5318  /*
5319  * It's a KAlarm pre-0.9 calendar file.
5320  * All alarms were of type DISPLAY. Instead of the X-KDE-KALARM-TYPE
5321  * alarm property, characteristics were stored as a prefix to the
5322  * alarm DESCRIPTION property, as follows:
5323  * SEQNO;[FLAGS];TYPE:TEXT
5324  * where
5325  * SEQNO = sequence number of alarm within the event
5326  * FLAGS = C for late-cancel, L for repeat-at-login, D for deferral
5327  * TYPE = TEXT or FILE or CMD
5328  * TEXT = message text, file name/URL or command
5329  */
5330  for (int ai = 0, aend = alarms.count(); ai < aend; ++ai)
5331  {
5332 #ifndef KALARMCAL_USE_KRESOURCES
5333  Alarm::Ptr alarm = alarms[ai];
5334 #else
5335  Alarm* alarm = alarms[ai];
5336 #endif
5337  bool atLogin = false;
5338  bool deferral = false;
5339  bool lateCancel = false;
5340  KAAlarm::Action action = KAAlarm::MESSAGE;
5341  QString txt = alarm->text();
5342  const int length = txt.length();
5343  int i = 0;
5344  if (txt[0].isDigit())
5345  {
5346  while (++i < length && txt[i].isDigit()) ;
5347  if (i < length && txt[i++] == SEPARATOR)
5348  {
5349  while (i < length)
5350  {
5351  const QChar ch = txt[i++];
5352  if (ch == SEPARATOR)
5353  break;
5354  if (ch == LATE_CANCEL_CODE)
5355  lateCancel = true;
5356  else if (ch == AT_LOGIN_CODE)
5357  atLogin = true;
5358  else if (ch == DEFERRAL_CODE)
5359  deferral = true;
5360  }
5361  }
5362  else
5363  i = 0; // invalid prefix
5364  }
5365  if (txt.indexOf(TEXT_PREFIX, i) == i)
5366  i += TEXT_PREFIX.length();
5367  else if (txt.indexOf(FILE_PREFIX, i) == i)
5368  {
5369  action = KAAlarm::FILE;
5370  i += FILE_PREFIX.length();
5371  }
5372  else if (txt.indexOf(COMMAND_PREFIX, i) == i)
5373  {
5374  action = KAAlarm::COMMAND;
5375  i += COMMAND_PREFIX.length();
5376  }
5377  else
5378  i = 0;
5379  txt = txt.mid(i);
5380 
5381  QStringList types;
5382  switch (action)
5383  {
5384  case KAAlarm::FILE:
5385  types += Private::FILE_TYPE;
5386  // fall through to MESSAGE
5387  case KAAlarm::MESSAGE:
5388  alarm->setDisplayAlarm(txt);
5389  break;
5390  case KAAlarm::COMMAND:
5391  setProcedureAlarm(alarm, txt);
5392  break;
5393  case KAAlarm::EMAIL: // email alarms were introduced in KAlarm 0.9
5394  case KAAlarm::AUDIO: // audio alarms (with no display) were introduced in KAlarm 2.3.2
5395  break;
5396  }
5397  if (atLogin)
5398  {
5399  types += Private::AT_LOGIN_TYPE;
5400  lateCancel = false;
5401  }
5402  else if (deferral)
5403  types += Private::TIME_DEFERRAL_TYPE;
5404  if (lateCancel)
5405  addLateCancel = true;
5406  if (types.count() > 0)
5407  alarm->setCustomProperty(KACalendar::APPNAME, Private::TYPE_PROPERTY, types.join(","));
5408 
5409  if (pre_0_7 && alarm->repeatCount() > 0 && alarm->snoozeTime().value() > 0)
5410  {
5411  // It's a KAlarm pre-0.7 calendar file.
5412  // Minutely recurrences were stored differently.
5413  Recurrence* recur = event->recurrence();
5414  if (recur && recur->recurs())
5415  {
5416  recur->setMinutely(alarm->snoozeTime().asSeconds() / 60);
5417  recur->setDuration(alarm->repeatCount() + 1);
5418  alarm->setRepeatCount(0);
5419  alarm->setSnoozeTime(0);
5420  }
5421  }
5422 
5423  if (adjustSummerTime)
5424  {
5425  // The calendar file was written by the KDE 3.0.0 version of KAlarm 0.5.7.
5426  // Summer time was ignored when converting to UTC.
5427  KDateTime dt = alarm->time();
5428  const time_t t = dt.toTime_t();
5429  const struct tm* dtm = localtime(&t);
5430  if (dtm->tm_isdst)
5431  {
5432  dt = dt.addSecs(-3600);
5433  alarm->setTime(dt);
5434  }
5435  }
5436  }
5437  }
5438 
5439  if (pre_0_9_2)
5440  {
5441  /*
5442  * It's a KAlarm pre-0.9.2 calendar file.
5443  * For the archive calendar, set the CREATED time to the DTEND value.
5444  * Convert date-only DTSTART to date/time, and add category "DATE".
5445  * Set the DTEND time to the DTSTART time.
5446  * Convert all alarm times to DTSTART offsets.
5447  * For display alarms, convert the first unlabelled category to an
5448  * X-KDE-KALARM-FONTCOLOUR property.
5449  * Convert BEEP category into an audio alarm with no audio file.
5450  */
5451  if (CalEvent::status(event) == CalEvent::ARCHIVED)
5452  event->setCreated(event->dtEnd());
5453  KDateTime start = event->dtStart();
5454  if (event->allDay())
5455  {
5456  event->setAllDay(false);
5457  start.setTime(QTime(0, 0));
5458  flags += Private::DATE_ONLY_FLAG;
5459  }
5460  event->setHasEndDate(false);
5461 
5462  for (int ai = 0, aend = alarms.count(); ai < aend; ++ai)
5463  {
5464 #ifndef KALARMCAL_USE_KRESOURCES
5465  Alarm::Ptr alarm = alarms[ai];
5466 #else
5467  Alarm* alarm = alarms[ai];
5468 #endif
5469  alarm->setStartOffset(start.secsTo(alarm->time()));
5470  }
5471 
5472  if (!cats.isEmpty())
5473  {
5474  for (int ai = 0, aend = alarms.count(); ai < aend; ++ai)
5475  {
5476 #ifndef KALARMCAL_USE_KRESOURCES
5477  Alarm::Ptr alarm = alarms[ai];
5478 #else
5479  Alarm* alarm = alarms[ai];
5480 #endif
5481  if (alarm->type() == Alarm::Display)
5482  alarm->setCustomProperty(KACalendar::APPNAME, Private::FONT_COLOUR_PROPERTY,
5483  QString::fromLatin1("%1;;").arg(cats[0]));
5484  }
5485  cats.removeAt(0);
5486  }
5487 
5488  for (int i = 0, end = cats.count(); i < end; ++i)
5489  {
5490  if (cats[i] == BEEP_CATEGORY)
5491  {
5492  cats.removeAt(i);
5493 
5494 #ifndef KALARMCAL_USE_KRESOURCES
5495  Alarm::Ptr alarm = event->newAlarm();
5496 #else
5497  Alarm* alarm = event->newAlarm();
5498 #endif
5499  alarm->setEnabled(true);
5500  alarm->setAudioAlarm();
5501  KDateTime dt = event->dtStart(); // default
5502 
5503  // Parse and order the alarms to know which one's date/time to use
5504  Private::AlarmMap alarmMap;
5505  Private::readAlarms(event, &alarmMap);
5506  Private::AlarmMap::ConstIterator it = alarmMap.constBegin();
5507  if (it != alarmMap.constEnd())
5508  {
5509  dt = it.value().alarm->time();
5510  break;
5511  }
5512  alarm->setStartOffset(start.secsTo(dt));
5513  break;
5514  }
5515  }
5516  }
5517 
5518  if (pre_1_1_1)
5519  {
5520  /*
5521  * It's a KAlarm pre-1.1.1 calendar file.
5522  * Convert simple LATECANCEL category to LATECANCEL:n where n = minutes late.
5523  */
5524  int i;
5525  while ((i = cats.indexOf(LATE_CANCEL_CAT)) >= 0)
5526  {
5527  cats.removeAt(i);
5528  addLateCancel = true;
5529  }
5530  }
5531 
5532  if (pre_1_2_1)
5533  {
5534  /*
5535  * It's a KAlarm pre-1.2.1 calendar file.
5536  * Convert email display alarms from translated to untranslated header prefixes.
5537  */
5538  for (int ai = 0, aend = alarms.count(); ai < aend; ++ai)
5539  {
5540 #ifndef KALARMCAL_USE_KRESOURCES
5541  Alarm::Ptr alarm = alarms[ai];
5542 #else
5543  Alarm* alarm = alarms[ai];
5544 #endif
5545  if (alarm->type() == Alarm::Display)
5546  {
5547  const QString oldtext = alarm->text();
5548  const QString newtext = AlarmText::toCalendarText(oldtext);
5549  if (oldtext != newtext)
5550  alarm->setDisplayAlarm(newtext);
5551  }
5552  }
5553  }
5554 
5555  if (pre_1_3_0)
5556  {
5557  /*
5558  * It's a KAlarm pre-1.3.0 calendar file.
5559  * Convert simple TMPLDEFTIME category to TMPLAFTTIME:n where n = minutes after.
5560  */
5561  int i;
5562  while ((i = cats.indexOf(TEMPL_DEF_TIME_CAT)) >= 0)
5563  {
5564  cats.removeAt(i);
5565  (flags += Private::TEMPL_AFTER_TIME_FLAG) += QLatin1String("0");
5566  }
5567  }
5568 
5569  if (pre_1_3_1)
5570  {
5571  /*
5572  * It's a KAlarm pre-1.3.1 calendar file.
5573  * Convert simple XTERM category to LOG:xterm:
5574  */
5575  int i;
5576  while ((i = cats.indexOf(EXEC_IN_XTERM_CAT)) >= 0)
5577  {
5578  cats.removeAt(i);
5579  event->setCustomProperty(KACalendar::APPNAME, Private::LOG_PROPERTY, Private::xtermURL);
5580  }
5581  }
5582 
5583  if (pre_1_9_0)
5584  {
5585  /*
5586  * It's a KAlarm pre-1.9 calendar file.
5587  * Add the X-KDE-KALARM-STATUS custom property.
5588  * Convert KAlarm categories to custom fields.
5589  */
5590  CalEvent::setStatus(event, CalEvent::status(event));
5591  for (int i = 0; i < cats.count(); )
5592  {
5593  QString cat = cats[i];
5594  if (cat == DATE_ONLY_CATEGORY)
5595  flags += Private::DATE_ONLY_FLAG;
5596  else if (cat == CONFIRM_ACK_CATEGORY)
5597  flags += Private::CONFIRM_ACK_FLAG;
5598  else if (cat == EMAIL_BCC_CATEGORY)
5599  flags += Private::EMAIL_BCC_FLAG;
5600  else if (cat == KORGANIZER_CATEGORY)
5601  flags += Private::KORGANIZER_FLAG;
5602  else if (cat.startsWith(DEFER_CATEGORY))
5603  (flags += Private::DEFER_FLAG) += cat.mid(DEFER_CATEGORY.length());
5604  else if (cat.startsWith(TEMPL_AFTER_TIME_CATEGORY))
5605  (flags += Private::TEMPL_AFTER_TIME_FLAG) += cat.mid(TEMPL_AFTER_TIME_CATEGORY.length());
5606  else if (cat.startsWith(LATE_CANCEL_CATEGORY))
5607  (flags += Private::LATE_CANCEL_FLAG) += cat.mid(LATE_CANCEL_CATEGORY.length());
5608  else if (cat.startsWith(AUTO_CLOSE_CATEGORY))
5609  (flags += Private::AUTO_CLOSE_FLAG) += cat.mid(AUTO_CLOSE_CATEGORY.length());
5610  else if (cat.startsWith(KMAIL_SERNUM_CATEGORY))
5611  (flags += Private::KMAIL_SERNUM_FLAG) += cat.mid(KMAIL_SERNUM_CATEGORY.length());
5612  else if (cat == ARCHIVE_CATEGORY)
5613  event->setCustomProperty(KACalendar::APPNAME, ARCHIVE_PROPERTY, QLatin1String("0"));
5614  else if (cat.startsWith(ARCHIVE_CATEGORIES))
5615  event->setCustomProperty(KACalendar::APPNAME, ARCHIVE_PROPERTY, cat.mid(ARCHIVE_CATEGORIES.length()));
5616  else if (cat.startsWith(LOG_CATEGORY))
5617  event->setCustomProperty(KACalendar::APPNAME, Private::LOG_PROPERTY, cat.mid(LOG_CATEGORY.length()));
5618  else
5619  {
5620  ++i; // Not a KAlarm category, so leave it
5621  continue;
5622  }
5623  cats.removeAt(i);
5624  }
5625  }
5626 
5627  if (pre_1_9_2)
5628  {
5629  /*
5630  * It's a KAlarm pre-1.9.2 calendar file.
5631  * Convert from clock time to the local system time zone.
5632  */
5633  event->shiftTimes(KDateTime::ClockTime, localZone);
5634  converted = true;
5635  }
5636 
5637  if (addLateCancel)
5638  (flags += Private::LATE_CANCEL_FLAG) += QLatin1String("1");
5639  if (!flags.isEmpty())
5640  event->setCustomProperty(KACalendar::APPNAME, Private::FLAGS_PROPERTY, flags.join(Private::SC));
5641  event->setCategories(cats);
5642 
5643 
5644  if ((pre_1_4_14 || (pre_1_9_7 && !pre_1_9_0))
5645  && event->recurrence() && event->recurrence()->recurs())
5646  {
5647  /*
5648  * It's a KAlarm pre-1.4.14 or KAlarm 1.9 series pre-1.9.7 calendar file.
5649  * For recurring events, convert the main alarm offset to an absolute
5650  * time in the X-KDE-KALARM-NEXTRECUR property, and set main alarm
5651  * offsets to zero, and convert deferral alarm offsets to be relative to
5652  * the next recurrence.
5653  */
5654  const QStringList flags = event->customProperty(KACalendar::APPNAME, Private::FLAGS_PROPERTY).split(Private::SC, QString::SkipEmptyParts);
5655  const bool dateOnly = flags.contains(Private::DATE_ONLY_FLAG);
5656  KDateTime startDateTime = event->dtStart();
5657  if (dateOnly)
5658  startDateTime.setDateOnly(true);
5659  // Convert the main alarm and get the next main trigger time from it
5660  KDateTime nextMainDateTime;
5661  bool mainExpired = true;
5662  for (int i = 0, alend = alarms.count(); i < alend; ++i)
5663  {
5664 #ifndef KALARMCAL_USE_KRESOURCES
5665  Alarm::Ptr alarm = alarms[i];
5666 #else
5667  Alarm* alarm = alarms[i];
5668 #endif
5669  if (!alarm->hasStartOffset())
5670  continue;
5671  // Find whether the alarm triggers at the same time as the main
5672  // alarm, in which case its offset needs to be set to 0. The
5673  // following trigger with the main alarm:
5674  // - Additional audio alarm
5675  // - PRE_ACTION_TYPE
5676  // - POST_ACTION_TYPE
5677  // - DISPLAYING_TYPE
5678  bool mainAlarm = true;
5679  QString property = alarm->customProperty(KACalendar::APPNAME, Private::TYPE_PROPERTY);
5680  QStringList types = property.split(QChar(','), QString::SkipEmptyParts);
5681  for (int t = 0; t < types.count(); ++t)
5682  {
5683  QString type = types[t];
5684  if (type == Private::AT_LOGIN_TYPE
5685  || type == Private::TIME_DEFERRAL_TYPE
5686  || type == Private::DATE_DEFERRAL_TYPE
5687  || type == Private::REMINDER_TYPE
5688  || type == REMINDER_ONCE_TYPE)
5689  {
5690  mainAlarm = false;
5691  break;
5692  }
5693  }
5694  if (mainAlarm)
5695  {
5696  if (mainExpired)
5697  {
5698  // All main alarms are supposed to be at the same time, so
5699  // don't readjust the event's time for subsequent main alarms.
5700  mainExpired = false;
5701  nextMainDateTime = alarm->time();
5702  nextMainDateTime.setDateOnly(dateOnly);
5703  nextMainDateTime = nextMainDateTime.toTimeSpec(startDateTime);
5704  if (nextMainDateTime != startDateTime)
5705  {
5706  QDateTime dt = nextMainDateTime.dateTime();
5707  event->setCustomProperty(KACalendar::APPNAME, Private::NEXT_RECUR_PROPERTY,
5708  dt.toString(dateOnly ? "yyyyMMdd" : "yyyyMMddThhmmss"));
5709  }
5710  }
5711  alarm->setStartOffset(0);
5712  converted = true;
5713  }
5714  }
5715  int adjustment;
5716  if (mainExpired)
5717  {
5718  // It's an expired recurrence.
5719  // Set the alarm offset relative to the first actual occurrence
5720  // (taking account of possible exceptions).
5721  KDateTime dt = event->recurrence()->getNextDateTime(startDateTime.addDays(-1));
5722  dt.setDateOnly(dateOnly);
5723  adjustment = startDateTime.secsTo(dt);
5724  }
5725  else
5726  adjustment = startDateTime.secsTo(nextMainDateTime);
5727  if (adjustment)
5728  {
5729  // Convert deferred alarms
5730  for (int i = 0, alend = alarms.count(); i < alend; ++i)
5731  {
5732 #ifndef KALARMCAL_USE_KRESOURCES
5733  Alarm::Ptr alarm = alarms[i];
5734 #else
5735  Alarm* alarm = alarms[i];
5736 #endif
5737  if (!alarm->hasStartOffset())
5738  continue;
5739  const QString property = alarm->customProperty(KACalendar::APPNAME, Private::TYPE_PROPERTY);
5740  const QStringList types = property.split(QChar(','), QString::SkipEmptyParts);
5741  for (int t = 0; t < types.count(); ++t)
5742  {
5743  const QString type = types[t];
5744  if (type == Private::TIME_DEFERRAL_TYPE
5745  || type == Private::DATE_DEFERRAL_TYPE)
5746  {
5747  alarm->setStartOffset(alarm->startOffset().asSeconds() - adjustment);
5748  converted = true;
5749  break;
5750  }
5751  }
5752  }
5753  }
5754  }
5755 
5756  if (pre_1_5_0 || (pre_1_9_9 && !pre_1_9_0))
5757  {
5758  /*
5759  * It's a KAlarm pre-1.5.0 or KAlarm 1.9 series pre-1.9.9 calendar file.
5760  * Convert email identity names to uoids.
5761  */
5762  for (int i = 0, alend = alarms.count(); i < alend; ++i)
5763  {
5764 #ifndef KALARMCAL_USE_KRESOURCES
5765  Alarm::Ptr alarm = alarms[i];
5766 #else
5767  Alarm* alarm = alarms[i];
5768 #endif
5769  const QString name = alarm->customProperty(KACalendar::APPNAME, KMAIL_ID_PROPERTY);
5770  if (name.isEmpty())
5771  continue;
5772  const uint id = Identities::identityUoid(name);
5773  if (id)
5774  alarm->setCustomProperty(KACalendar::APPNAME, EMAIL_ID_PROPERTY, QString::number(id));
5775  alarm->removeCustomProperty(KACalendar::APPNAME, KMAIL_ID_PROPERTY);
5776  converted = true;
5777  }
5778  }
5779 
5780  if (pre_1_9_10)
5781  {
5782  /*
5783  * It's a KAlarm pre-1.9.10 calendar file.
5784  * Convert simple repetitions without a recurrence, to a recurrence.
5785  */
5786  if (Private::convertRepetition(event))
5787  converted = true;
5788  }
5789 
5790  if (pre_2_2_9 || (pre_2_3_2 && !pre_2_3_0))
5791  {
5792  /*
5793  * It's a KAlarm pre-2.2.9 or KAlarm 2.3 series pre-2.3.2 calendar file.
5794  * Set the time in the calendar for all date-only alarms to 00:00.
5795  */
5796  if (Private::convertStartOfDay(event))
5797  converted = true;
5798  }
5799 
5800  if (pre_2_7_0)
5801  {
5802  /*
5803  * It's a KAlarm pre-2.7.0 calendar file.
5804  * Archive and at-login flags were stored in event's ARCHIVE property when the main alarm had expired.
5805  * Reminder parameters were stored in event's ARCHIVE property when no reminder was pending.
5806  * Negative reminder periods (i.e. alarm offset > 0) were invalid, so convert to 0.
5807  * Now store reminder information in FLAGS property, whether reminder is pending or not.
5808  * Move EMAILID, SPEAK, ERRCANCEL and ERRNOSHOW alarm properties into new FLAGS property.
5809  */
5810  bool flagsValid = false;
5811  QStringList flags;
5812  QString reminder;
5813  bool reminderOnce = false;
5814  const QString prop = event->customProperty(KACalendar::APPNAME, ARCHIVE_PROPERTY);
5815  if (!prop.isEmpty())
5816  {
5817  // Convert the event's ARCHIVE property to parameters in the FLAGS property
5818  flags = event->customProperty(KACalendar::APPNAME, Private::FLAGS_PROPERTY).split(Private::SC, QString::SkipEmptyParts);
5819  flags << Private::ARCHIVE_FLAG;
5820  flagsValid = true;
5821  if (prop != QLatin1String("0")) // "0" was a dummy parameter if no others were present
5822  {
5823  // It's the archive property containing a reminder time and/or repeat-at-login flag.
5824  // This was present when no reminder/at-login alarm was pending.
5825  const QStringList list = prop.split(Private::SC, QString::SkipEmptyParts);
5826  for (int i = 0; i < list.count(); ++i)
5827  {
5828  if (list[i] == Private::AT_LOGIN_TYPE)
5829  flags << Private::AT_LOGIN_TYPE;
5830  else if (list[i] == ARCHIVE_REMINDER_ONCE_TYPE)
5831  reminderOnce = true;
5832  else if (!list[i].isEmpty() && !list[i].startsWith(QChar::fromLatin1('-')))
5833  reminder = list[i];
5834  }
5835  }
5836  event->setCustomProperty(KACalendar::APPNAME, Private::FLAGS_PROPERTY, flags.join(Private::SC));
5837  event->removeCustomProperty(KACalendar::APPNAME, ARCHIVE_PROPERTY);
5838  }
5839 
5840  for (int i = 0, alend = alarms.count(); i < alend; ++i)
5841  {
5842 #ifndef KALARMCAL_USE_KRESOURCES
5843  Alarm::Ptr alarm = alarms[i];
5844 #else
5845  Alarm* alarm = alarms[i];
5846 #endif
5847  // Convert EMAILID, SPEAK, ERRCANCEL, ERRNOSHOW properties
5848  QStringList flags;
5849  QString property = alarm->customProperty(KACalendar::APPNAME, EMAIL_ID_PROPERTY);
5850  if (!property.isEmpty())
5851  {
5852  flags << Private::EMAIL_ID_FLAG << property;
5853  alarm->removeCustomProperty(KACalendar::APPNAME, EMAIL_ID_PROPERTY);
5854  }
5855  if (!alarm->customProperty(KACalendar::APPNAME, SPEAK_PROPERTY).isEmpty())
5856  {
5857  flags << Private::SPEAK_FLAG;
5858  alarm->removeCustomProperty(KACalendar::APPNAME, SPEAK_PROPERTY);
5859  }
5860  if (!alarm->customProperty(KACalendar::APPNAME, CANCEL_ON_ERROR_PROPERTY).isEmpty())
5861  {
5862  flags << Private::CANCEL_ON_ERROR_FLAG;
5863  alarm->removeCustomProperty(KACalendar::APPNAME, CANCEL_ON_ERROR_PROPERTY);
5864  }
5865  if (!alarm->customProperty(KACalendar::APPNAME, DONT_SHOW_ERROR_PROPERTY).isEmpty())
5866  {
5867  flags << Private::DONT_SHOW_ERROR_FLAG;
5868  alarm->removeCustomProperty(KACalendar::APPNAME, DONT_SHOW_ERROR_PROPERTY);
5869  }
5870  if (!flags.isEmpty())
5871  alarm->setCustomProperty(KACalendar::APPNAME, Private::FLAGS_PROPERTY, flags.join(Private::SC));
5872 
5873  // Invalidate negative reminder periods in alarms
5874  if (!alarm->hasStartOffset())
5875  continue;
5876  property = alarm->customProperty(KACalendar::APPNAME, Private::TYPE_PROPERTY);
5877  QStringList types = property.split(QChar::fromLatin1(','), QString::SkipEmptyParts);
5878  const int r = types.indexOf(REMINDER_ONCE_TYPE);
5879  if (r >= 0)
5880  {
5881  // Move reminder-once indicator from the alarm to the event's FLAGS property
5882  types[r] = Private::REMINDER_TYPE;
5883  alarm->setCustomProperty(KACalendar::APPNAME, Private::TYPE_PROPERTY, types.join(QChar::fromLatin1(',')));
5884  reminderOnce = true;
5885  }
5886  if (r >= 0 || types.contains(Private::REMINDER_TYPE))
5887  {
5888  // The alarm is a reminder alarm
5889  const int offset = alarm->startOffset().asSeconds();
5890  if (offset > 0)
5891  {
5892  alarm->setStartOffset(0);
5893  converted = true;
5894  }
5895  else if (offset < 0)
5896  reminder = reminderToString(offset / 60);
5897  }
5898  }
5899  if (!reminder.isEmpty())
5900  {
5901  // Write reminder parameters into the event's FLAGS property
5902  if (!flagsValid)
5903  flags = event->customProperty(KACalendar::APPNAME, Private::FLAGS_PROPERTY).split(Private::SC, QString::SkipEmptyParts);
5904  if (flags.indexOf(Private::REMINDER_TYPE) < 0)
5905  {
5906  flags += Private::REMINDER_TYPE;
5907  if (reminderOnce)
5908  flags += Private::REMINDER_ONCE_FLAG;
5909  flags += reminder;
5910  }
5911  }
5912  }
5913 
5914  if (readOnly)
5915  event->setReadOnly(true);
5916  event->endUpdates(); // finally issue an update notification
5917  }
5918  return converted;
5919 }
5920 
5921 /******************************************************************************
5922 * Set the time for a date-only event to 00:00.
5923 * Reply = true if the event was updated.
5924 */
5925 #ifndef KALARMCAL_USE_KRESOURCES
5926 bool KAEvent::Private::convertStartOfDay(const Event::Ptr& event)
5927 #else
5928 bool KAEvent::Private::convertStartOfDay(Event* event)
5929 #endif
5930 {
5931  bool changed = false;
5932  const QTime midnight(0, 0);
5933  const QStringList flags = event->customProperty(KACalendar::APPNAME, Private::FLAGS_PROPERTY).split(Private::SC, QString::SkipEmptyParts);
5934  if (flags.indexOf(Private::DATE_ONLY_FLAG) >= 0)
5935  {
5936  // It's an untimed event, so fix it
5937  const KDateTime oldDt = event->dtStart();
5938  const int adjustment = oldDt.time().secsTo(midnight);
5939  if (adjustment)
5940  {
5941  event->setDtStart(KDateTime(oldDt.date(), midnight, oldDt.timeSpec()));
5942  int deferralOffset = 0;
5943  AlarmMap alarmMap;
5944  readAlarms(event, &alarmMap);
5945  for (AlarmMap::ConstIterator it = alarmMap.constBegin(); it != alarmMap.constEnd(); ++it)
5946  {
5947  const AlarmData& data = it.value();
5948  if (!data.alarm->hasStartOffset())
5949  continue;
5950  if (data.timedDeferral)
5951  {
5952  // Found a timed deferral alarm, so adjust the offset
5953  deferralOffset = data.alarm->startOffset().asSeconds();
5954 #ifndef KALARMCAL_USE_KRESOURCES
5955  const_cast<Alarm*>(data.alarm.data())->setStartOffset(deferralOffset - adjustment);
5956 #else
5957  const_cast<Alarm*>(data.alarm)->setStartOffset(deferralOffset - adjustment);
5958 #endif
5959  }
5960  else if (data.type == AUDIO_ALARM
5961  && data.alarm->startOffset().asSeconds() == deferralOffset)
5962  {
5963  // Audio alarm is set for the same time as the above deferral alarm
5964 #ifndef KALARMCAL_USE_KRESOURCES
5965  const_cast<Alarm*>(data.alarm.data())->setStartOffset(deferralOffset - adjustment);
5966 #else
5967  const_cast<Alarm*>(data.alarm)->setStartOffset(deferralOffset - adjustment);
5968 #endif
5969  }
5970  }
5971  changed = true;
5972  }
5973  }
5974  else
5975  {
5976  // It's a timed event. Fix any untimed alarms.
5977  bool foundDeferral = false;
5978  int deferralOffset = 0;
5979  int newDeferralOffset = 0;
5980  DateTime start;
5981  const KDateTime nextMainDateTime = readDateTime(event, false, start).kDateTime();
5982  AlarmMap alarmMap;
5983  readAlarms(event, &alarmMap);
5984  for (AlarmMap::ConstIterator it = alarmMap.constBegin(); it != alarmMap.constEnd(); ++it)
5985  {
5986  const AlarmData& data = it.value();
5987  if (!data.alarm->hasStartOffset())
5988  continue;
5989  if ((data.type & DEFERRED_ALARM) && !data.timedDeferral)
5990  {
5991  // Found a date-only deferral alarm, so adjust its time
5992  KDateTime altime = data.alarm->startOffset().end(nextMainDateTime);
5993  altime.setTime(midnight);
5994  deferralOffset = data.alarm->startOffset().asSeconds();
5995  newDeferralOffset = event->dtStart().secsTo(altime);
5996 #ifndef KALARMCAL_USE_KRESOURCES
5997  const_cast<Alarm*>(data.alarm.data())->setStartOffset(newDeferralOffset);
5998 #else
5999  const_cast<Alarm*>(data.alarm)->setStartOffset(newDeferralOffset);
6000 #endif
6001  foundDeferral = true;
6002  changed = true;
6003  }
6004  else if (foundDeferral
6005  && data.type == AUDIO_ALARM
6006  && data.alarm->startOffset().asSeconds() == deferralOffset)
6007  {
6008  // Audio alarm is set for the same time as the above deferral alarm
6009 #ifndef KALARMCAL_USE_KRESOURCES
6010  const_cast<Alarm*>(data.alarm.data())->setStartOffset(newDeferralOffset);
6011 #else
6012  const_cast<Alarm*>(data.alarm)->setStartOffset(newDeferralOffset);
6013 #endif
6014  changed = true;
6015  }
6016  }
6017  }
6018  return changed;
6019 }
6020 
6021 /******************************************************************************
6022 * Convert simple repetitions in an event without a recurrence, to a
6023 * recurrence. Repetitions which are an exact multiple of 24 hours are converted
6024 * to daily recurrences; else they are converted to minutely recurrences. Note
6025 * that daily and minutely recurrences produce different results when they span
6026 * a daylight saving time change.
6027 * Reply = true if any conversions were done.
6028 */
6029 #ifndef KALARMCAL_USE_KRESOURCES
6030 bool KAEvent::Private::convertRepetition(const Event::Ptr& event)
6031 #else
6032 bool KAEvent::Private::convertRepetition(Event* event)
6033 #endif
6034 {
6035  const Alarm::List alarms = event->alarms();
6036  if (alarms.isEmpty())
6037  return false;
6038  Recurrence* recur = event->recurrence(); // guaranteed to return non-null
6039  if (recur->recurs())
6040  return false;
6041  bool converted = false;
6042  const bool readOnly = event->isReadOnly();
6043  for (int ai = 0, aend = alarms.count(); ai < aend; ++ai)
6044  {
6045 #ifndef KALARMCAL_USE_KRESOURCES
6046  Alarm::Ptr alarm = alarms[ai];
6047 #else
6048  Alarm* alarm = alarms[ai];
6049 #endif
6050  if (alarm->repeatCount() > 0 && alarm->snoozeTime().value() > 0)
6051  {
6052  if (!converted)
6053  {
6054  event->startUpdates(); // prevent multiple update notifications
6055  if (readOnly)
6056  event->setReadOnly(false);
6057  if ((alarm->snoozeTime().asSeconds() % (24*3600)) != 0)
6058  recur->setMinutely(alarm->snoozeTime().asSeconds() / 60);
6059  else
6060  recur->setDaily(alarm->snoozeTime().asDays());
6061  recur->setDuration(alarm->repeatCount() + 1);
6062  converted = true;
6063  }
6064  alarm->setRepeatCount(0);
6065  alarm->setSnoozeTime(0);
6066  }
6067  }
6068  if (converted)
6069  {
6070  if (readOnly)
6071  event->setReadOnly(true);
6072  event->endUpdates(); // finally issue an update notification
6073  }
6074  return converted;
6075 }
6076 
6077 
6078 
6079 /*=============================================================================
6080 = Class KAAlarm
6081 = Corresponds to a single KCal::Alarm instance.
6082 =============================================================================*/
6083 
6084 KAAlarm::KAAlarm()
6085  : d(new Private)
6086 {
6087 }
6088 
6089 KAAlarm::Private::Private()
6090  : mType(INVALID_ALARM),
6091  mNextRepeat(0),
6092  mRepeatAtLogin(false),
6093  mDeferred(false)
6094 {
6095 }
6096 
6097 KAAlarm::KAAlarm(const KAAlarm& other)
6098  : d(new Private(*other.d))
6099 {
6100 }
6101 
6102 KAAlarm::~KAAlarm()
6103 {
6104  delete d;
6105 }
6106 
6107 KAAlarm& KAAlarm::operator=(const KAAlarm& other)
6108 {
6109  if (&other != this)
6110  *d = *other.d;
6111  return *this;
6112 }
6113 
6114 KAAlarm::Action KAAlarm::action() const
6115 {
6116  return d->mActionType;
6117 }
6118 
6119 bool KAAlarm::isValid() const
6120 {
6121  return d->mType != INVALID_ALARM;
6122 }
6123 
6124 KAAlarm::Type KAAlarm::type() const
6125 {
6126  return d->mType;
6127 }
6128 
6129 DateTime KAAlarm::dateTime(bool withRepeats) const
6130 {
6131  return (withRepeats && d->mNextRepeat && d->mRepetition)
6132  ? d->mRepetition.duration(d->mNextRepeat).end(d->mNextMainDateTime.kDateTime())
6133  : d->mNextMainDateTime;
6134 }
6135 
6136 QDate KAAlarm::date() const
6137 {
6138  return d->mNextMainDateTime.date();
6139 }
6140 
6141 QTime KAAlarm::time() const
6142 {
6143  return d->mNextMainDateTime.effectiveTime();
6144 }
6145 
6146 bool KAAlarm::repeatAtLogin() const
6147 {
6148  return d->mRepeatAtLogin;
6149 }
6150 
6151 bool KAAlarm::isReminder() const
6152 {
6153  return d->mType == REMINDER_ALARM;
6154 }
6155 
6156 bool KAAlarm::deferred() const
6157 {
6158  return d->mDeferred;
6159 }
6160 
6161 bool KAAlarm::timedDeferral() const
6162 {
6163  return d->mDeferred && d->mTimedDeferral;
6164 }
6165 
6166 void KAAlarm::setTime(const DateTime& dt)
6167 {
6168  d->mNextMainDateTime = dt;
6169 }
6170 
6171 void KAAlarm::setTime(const KDateTime& dt)
6172 {
6173  d->mNextMainDateTime = dt;
6174 }
6175 
6176 #ifdef KDE_NO_DEBUG_OUTPUT
6177 const char* KAAlarm::debugType(Type) { return ""; }
6178 #else
6179 const char* KAAlarm::debugType(Type type)
6180 {
6181  switch (type)
6182  {
6183  case MAIN_ALARM: return "MAIN";
6184  case REMINDER_ALARM: return "REMINDER";
6185  case DEFERRED_ALARM: return "DEFERRED";
6186  case DEFERRED_REMINDER_ALARM: return "DEFERRED_REMINDER";
6187  case AT_LOGIN_ALARM: return "LOGIN";
6188  case DISPLAYING_ALARM: return "DISPLAYING";
6189  default: return "INVALID";
6190  }
6191 }
6192 #endif
6193 
6194 
6195 /*=============================================================================
6196 = Class EmailAddressList
6197 =============================================================================*/
6198 
6199 /******************************************************************************
6200 * Sets the list of email addresses, removing any empty addresses.
6201 * Reply = false if empty addresses were found.
6202 */
6203 #ifndef KALARMCAL_USE_KRESOURCES
6204 EmailAddressList& EmailAddressList::operator=(const Person::List& addresses)
6205 #else
6206 EmailAddressList& EmailAddressList::operator=(const QList<Person>& addresses)
6207 #endif
6208 {
6209  clear();
6210  for (int p = 0, end = addresses.count(); p < end; ++p)
6211  {
6212 #ifndef KALARMCAL_USE_KRESOURCES
6213  if (!addresses[p]->email().isEmpty())
6214 #else
6215  if (!addresses[p].email().isEmpty())
6216 #endif
6217  append(addresses[p]);
6218  }
6219  return *this;
6220 }
6221 
6222 /******************************************************************************
6223 * Return the email address list as a string list of email addresses.
6224 */
6225 EmailAddressList::operator QStringList() const
6226 {
6227  QStringList list;
6228  for (int p = 0, end = count(); p < end; ++p)
6229  list += address(p);
6230  return list;
6231 }
6232 
6233 /******************************************************************************
6234 * Return the email address list as a string, each address being delimited by
6235 * the specified separator string.
6236 */
6237 QString EmailAddressList::join(const QString& separator) const
6238 {
6239  QString result;
6240  bool first = true;
6241  for (int p = 0, end = count(); p < end; ++p)
6242  {
6243  if (first)
6244  first = false;
6245  else
6246  result += separator;
6247  result += address(p);
6248  }
6249  return result;
6250 }
6251 
6252 /******************************************************************************
6253 * Convert one item into an email address, including name.
6254 */
6255 QString EmailAddressList::address(int index) const
6256 {
6257  if (index < 0 || index > count())
6258  return QString();
6259  QString result;
6260  bool quote = false;
6261 #ifndef KALARMCAL_USE_KRESOURCES
6262  const Person::Ptr person = (*this)[index];
6263  const QString name = person->name();
6264 #else
6265  const Person person = (*this)[index];
6266  const QString name = person.name();
6267 #endif
6268  if (!name.isEmpty())
6269  {
6270  // Need to enclose the name in quotes if it has any special characters
6271  for (int i = 0, len = name.length(); i < len; ++i)
6272  {
6273  const QChar ch = name[i];
6274  if (!ch.isLetterOrNumber())
6275  {
6276  quote = true;
6277  result += '\"';
6278  break;
6279  }
6280  }
6281 #ifndef KALARMCAL_USE_KRESOURCES
6282  result += (*this)[index]->name();
6283 #else
6284  result += (*this)[index].name();
6285 #endif
6286  result += (quote ? "\" <" : " <");
6287  quote = true; // need angle brackets round email address
6288  }
6289 
6290 #ifndef KALARMCAL_USE_KRESOURCES
6291  result += person->email();
6292 #else
6293  result += person.email();
6294 #endif
6295  if (quote)
6296  result += '>';
6297  return result;
6298 }
6299 
6300 /******************************************************************************
6301 * Return a list of the pure email addresses, excluding names.
6302 */
6303 QStringList EmailAddressList::pureAddresses() const
6304 {
6305  QStringList list;
6306  for (int p = 0, end = count(); p < end; ++p)
6307 #ifndef KALARMCAL_USE_KRESOURCES
6308  list += at(p)->email();
6309 #else
6310  list += at(p).email();
6311 #endif
6312  return list;
6313 }
6314 
6315 /******************************************************************************
6316 * Return a list of the pure email addresses, excluding names, as a string.
6317 */
6318 QString EmailAddressList::pureAddresses(const QString& separator) const
6319 {
6320  QString result;
6321  bool first = true;
6322  for (int p = 0, end = count(); p < end; ++p)
6323  {
6324  if (first)
6325  first = false;
6326  else
6327  result += separator;
6328 #ifndef KALARMCAL_USE_KRESOURCES
6329  result += at(p)->email();
6330 #else
6331  result += at(p).email();
6332 #endif
6333  }
6334  return result;
6335 }
6336 
6337 
6338 /*=============================================================================
6339 = Static functions
6340 =============================================================================*/
6341 
6342 /******************************************************************************
6343 * Set the specified alarm to be a procedure alarm with the given command line.
6344 * The command line is first split into its program file and arguments before
6345 * initialising the alarm.
6346 */
6347 #ifndef KALARMCAL_USE_KRESOURCES
6348 static void setProcedureAlarm(const Alarm::Ptr& alarm, const QString& commandLine)
6349 #else
6350 static void setProcedureAlarm(Alarm* alarm, const QString& commandLine)
6351 #endif
6352 {
6353  QString command;
6354  QString arguments;
6355  QChar quoteChar;
6356  bool quoted = false;
6357  const uint posMax = commandLine.length();
6358  uint pos;
6359  for (pos = 0; pos < posMax; ++pos)
6360  {
6361  const QChar ch = commandLine[pos];
6362  if (quoted)
6363  {
6364  if (ch == quoteChar)
6365  {
6366  ++pos; // omit the quote character
6367  break;
6368  }
6369  command += ch;
6370  }
6371  else
6372  {
6373  bool done = false;
6374  switch (ch.toAscii())
6375  {
6376  case ' ':
6377  case ';':
6378  case '|':
6379  case '<':
6380  case '>':
6381  done = !command.isEmpty();
6382  break;
6383  case '\'':
6384  case '"':
6385  if (command.isEmpty())
6386  {
6387  // Start of a quoted string. Omit the quote character.
6388  quoted = true;
6389  quoteChar = ch;
6390  break;
6391  }
6392  // fall through to default
6393  default:
6394  command += ch;
6395  break;
6396  }
6397  if (done)
6398  break;
6399  }
6400  }
6401 
6402  // Skip any spaces after the command
6403  for ( ; pos < posMax && commandLine[pos] == QLatin1Char(' '); ++pos) ;
6404  arguments = commandLine.mid(pos);
6405 
6406  alarm->setProcedureAlarm(command, arguments);
6407 }
6408 
6409 /******************************************************************************
6410 * Converts a reminder interval into a parameter string for the
6411 * X-KDE-KALARM-FLAGS property.
6412 */
6413 QString reminderToString(int minutes)
6414 {
6415  char unit = 'M';
6416  int count = abs(minutes);
6417  if (count % 1440 == 0)
6418  {
6419  unit = 'D';
6420  count /= 1440;
6421  }
6422  else if (count % 60 == 0)
6423  {
6424  unit = 'H';
6425  count /= 60;
6426  }
6427  if (minutes < 0)
6428  count = -count;
6429  return QString("%1%2").arg(count).arg(unit);
6430 }
6431 
6432 } // namespace KAlarmCal
6433 
6434 // vim: et sw=4:
This file is part of the KDE documentation.
Documentation copyright © 1996-2012 The KDE developers.
Generated on Tue Dec 11 2012 12:16:42 by doxygen 1.8.1.2 written by Dimitri van Heesch, © 1997-2006

KDE's Doxygen guidelines are available online.

KAlarm Library

Skip menu "KAlarm Library"
  • Main Page
  • Namespace List
  • Namespace Members
  • Alphabetical List
  • Class List
  • Class Hierarchy
  • Class Members
  • File List
  • Related Pages

kdepimlibs-4.9.4 API Reference

Skip menu "kdepimlibs-4.9.4 API Reference"
  • akonadi
  •   contact
  •   kmime
  • kabc
  • kalarmcal
  • kblog
  • kcal
  • kcalcore
  • kcalutils
  • kholidays
  • kimap
  • kioslave
  •   imap4
  •   mbox
  •   nntp
  • kldap
  • kmbox
  • kmime
  • kontactinterface
  • kpimidentities
  • kpimtextedit
  •   richtextbuilders
  • kpimutils
  • kresources
  • ktnef
  • kxmlrpcclient
  • mailtransport
  • microblog
  • qgpgme
  • syndication
  •   atom
  •   rdf
  •   rss2
Report problems with this website to our bug tracking system.
Contact the specific authors with questions and comments about the page contents.

KDE® and the K Desktop Environment® logo are registered trademarks of KDE e.V. | Legal