KAlarmCal

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