diff --git a/autotests/testrecurrenceexception.cpp b/autotests/testrecurrenceexception.cpp index c09e7ae2e..88962029c 100644 --- a/autotests/testrecurrenceexception.cpp +++ b/autotests/testrecurrenceexception.cpp @@ -1,46 +1,46 @@ /* * Copyright (C) 2013 Christian Mollekopf * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see . */ #include "testrecurrenceexception.h" #include "memorycalendar.h" #include QTEST_MAIN(TestRecurrenceException) void TestRecurrenceException::testCreateTodoException() { const QDateTime dtstart(QDate(2013, 03, 10), QTime(10, 0, 0), Qt::UTC); const QDateTime dtdue(QDate(2013, 03, 10), QTime(11, 0, 0), Qt::UTC); const QDateTime recurrenceId(QDateTime(dtstart).addDays(1)); KCalCore::Todo::Ptr todo(new KCalCore::Todo()); todo->setUid(QStringLiteral("todo")); todo->setDtStart(dtstart); todo->setDtDue(dtdue); todo->recurrence()->setDaily(1); todo->recurrence()->setDuration(3); const KCalCore::Todo::Ptr exception = KCalCore::MemoryCalendar::createException(todo, recurrenceId, false).staticCast(); QCOMPARE(exception->dtStart(), recurrenceId); QCOMPARE(exception->dtDue(), QDateTime(dtdue).addDays(1)); //FIXME should be done on clearing the recurrence, but we can't due to BC. //Probably not that important as long as dtRecurrence is ignored if the todo is not recurring - //QCOMPARE(exception->dtRecurrence(), KDateTime()); + //QCOMPARE(exception->dtRecurrence(), QDateTime()); //TODO dtCompleted } diff --git a/autotests/testrecurtodo.cpp b/autotests/testrecurtodo.cpp index 03d484873..d2a4226bc 100644 --- a/autotests/testrecurtodo.cpp +++ b/autotests/testrecurtodo.cpp @@ -1,262 +1,262 @@ /* This file is part of the kcalcore library. Copyright (c) 2011 Sérgio Martins This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "testrecurtodo.h" #include "todo.h" #include "utils.h" #include QTEST_MAIN(RecurTodoTest) using namespace KCalCore; void RecurTodoTest::testAllDay() { qputenv("TZ", "GMT"); const QDate currentDate = QDate::currentDate(); const QDateTime currentUtcDateTime = QDateTime::currentDateTimeUtc(); const QDate dueDate(QDate::currentDate()); Todo *todo = new Todo(); todo->setDtStart(QDateTime(dueDate.addDays(-1), {})); todo->setDtDue(QDateTime(dueDate, {})); todo->setSummary(QStringLiteral("All day event")); todo->setAllDay(true); QCOMPARE(todo->dtStart().daysTo(todo->dtDue()), 1); Recurrence *recurrence = todo->recurrence(); recurrence->unsetRecurs(); recurrence->setDaily(1); QCOMPARE(todo->dtDue(), QDateTime(dueDate, {})); todo->setCompleted(currentUtcDateTime); QVERIFY(todo->recurs()); QVERIFY(todo->percentComplete() == 0); const QDate newStartDate = todo->dtStart().date(); const QDate newDueDate = todo->dtDue().date(); QCOMPARE(newStartDate, currentDate); QCOMPARE(newStartDate.daysTo(newDueDate), 1); todo->setCompleted(currentUtcDateTime); QCOMPARE(newDueDate, currentDate.addDays(1)); QCOMPARE(todo->dtDue(true /*first ocurrence*/).date(), dueDate); } void RecurTodoTest::testRecurrenceStart() { qputenv("TZ", "GMT"); const QDateTime currentDateTime = QDateTime::currentDateTime(); const QDate currentDate = currentDateTime.date(); const QTime currentTimeWithMS = currentDateTime.time(); const QDate fourDaysAgo(currentDate.addDays(-4)); const QDate treeDaysAgo(currentDate.addDays(-3)); const QTime currentTime(currentTimeWithMS.hour(), currentTimeWithMS.minute(), currentTimeWithMS.second()); Todo *todo = new Todo(); Recurrence *recurrence = todo->recurrence(); recurrence->unsetRecurs(); recurrence->setDaily(1); todo->setDtStart(QDateTime(fourDaysAgo, currentTime)); const QDateTime originalDtDue(treeDaysAgo, currentTime); todo->setDtDue(originalDtDue); todo->setSummary(QStringLiteral("Not an all day event")); QVERIFY(!todo->allDay()); QVERIFY(recurrence->startDateTime().isValid()); } void RecurTodoTest::testNonAllDay() { qputenv("TZ", "GMT"); const QDateTime currentDateTime = QDateTime::currentDateTime(); const QDate currentDate = currentDateTime.date(); const QTime currentTimeWithMS = currentDateTime.time(); const QDate fourDaysAgo(currentDate.addDays(-4)); const QDate treeDaysAgo(currentDate.addDays(-3)); const QTime currentTime(currentTimeWithMS.hour(), currentTimeWithMS.minute(), currentTimeWithMS.second()); Todo *todo = new Todo(); todo->setDtStart(QDateTime(fourDaysAgo, currentTime)); const QDateTime originalDtDue(treeDaysAgo, currentTime); todo->setDtDue(originalDtDue); todo->setSummary(QStringLiteral("Not an all day event")); QVERIFY(!todo->allDay()); Recurrence *recurrence = todo->recurrence(); recurrence->unsetRecurs(); recurrence->setDaily(1); QVERIFY(recurrence->startDateTime().isValid()); QCOMPARE(todo->dtDue(), originalDtDue); todo->setCompleted(QDateTime::currentDateTimeUtc()); QVERIFY(todo->recurs()); QVERIFY(todo->percentComplete() == 0); const bool equal = todo->dtStart() == QDateTime(currentDate, currentTime, todo->dtStart().timeZone()).addDays(1); if (!equal) { qDebug() << "Test Failed. dtDue = " << todo->dtDue().toString() << "OriginalDtDue:" << originalDtDue.toString() - << "KDateTime:" + << "QDateTime:" << QDateTime(currentDate, currentTime, todo->dtDue().timeZone()).addDays(1).toString(); } QVERIFY(equal); todo->setCompleted(QDateTime::currentDateTimeUtc()); QCOMPARE(todo->dtStart(), QDateTime(currentDate, currentTime, todo->dtStart().timeZone()).addDays(2)); QCOMPARE(todo->dtDue(true /*first ocurrence*/), QDateTime(treeDaysAgo, currentTime)); } void RecurTodoTest::testIsAllDay() { ; KCalCore::Todo::Ptr todo(new KCalCore::Todo()); todo->setUid(QStringLiteral("todo")); todo->setDtStart(QDateTime(QDate(2013, 03, 10), QTime(10, 0, 0), Qt::UTC)); todo->setDtDue(QDateTime(QDate(2013, 03, 10), QTime(10, 0, 0), Qt::UTC)); todo->recurrence()->setDaily(1); todo->recurrence()->setDuration(2); QCOMPARE(todo->allDay(), false); QCOMPARE(todo->recurrence()->allDay(), false); KCalCore::Todo::Ptr allDay(new KCalCore::Todo()); allDay->setUid(QStringLiteral("todo")); allDay->setDtStart(QDateTime(QDate(2013, 03, 10), {}, Qt::UTC)); allDay->setDtDue(QDateTime(QDate(2013, 03, 10), {}, Qt::UTC)); allDay->setAllDay(true); allDay->recurrence()->setDaily(1); allDay->recurrence()->setDuration(2); QCOMPARE(allDay->allDay(), true); QCOMPARE(allDay->recurrence()->allDay(), true); } void RecurTodoTest::testHasDueDate() { KCalCore::Todo::Ptr todo(new KCalCore::Todo()); todo->setUid(QStringLiteral("todo")); todo->setDtStart(QDateTime(QDate(2013, 03, 10), QTime(10, 0, 0), Qt::UTC)); todo->recurrence()->setDaily(1); todo->recurrence()->setDuration(2); QVERIFY(!todo->hasDueDate()); } void RecurTodoTest::testRecurTodo_data() { QTest::addColumn("dtstart"); QTest::addColumn("dtdue"); // Can't use QDateTime::currentDateTimeUtc() due to milliseconds mismatching const QDateTime today = QDateTime::fromSecsSinceEpoch(QDateTime::currentSecsSinceEpoch(), Qt::UTC); const QDateTime tomorrow = today.addDays(1); const QDateTime invalid; QTest::newRow("valid dtstart") << today << invalid; QTest::newRow("valid dtstart and dtdue") << today << tomorrow; QTest::newRow("valid dtdue") << invalid << today; } void RecurTodoTest::testRecurTodo() { QFETCH(QDateTime, dtstart); QFETCH(QDateTime, dtdue); KCalCore::Todo::Ptr todo(new KCalCore::Todo()); todo->setUid(QStringLiteral("todo")); todo->setDtStart(dtstart); todo->setDtDue(dtdue); todo->recurrence()->setDaily(1); const bool legacyMode = !dtstart.isValid(); QCOMPARE(todo->percentComplete(), 0); // Recur it todo->setCompleted(QDateTime::currentDateTimeUtc()); QCOMPARE(todo->percentComplete(), 0); if (legacyMode) { QVERIFY(todo->dtDue().isValid()); QVERIFY(!todo->dtStart().isValid()); QCOMPARE(todo->dtDue(), dtdue.addDays(1)); QCOMPARE(todo->dtDue(/**first=*/true), dtdue); } else { QVERIFY(todo->dtStart().isValid()); QVERIFY(!(todo->dtDue().isValid() ^ dtdue.isValid())); QCOMPARE(todo->dtStart(), dtstart.addDays(1)); if (dtdue.isValid()) { const int delta = dtstart.daysTo(dtdue); QCOMPARE(todo->dtStart().daysTo(todo->dtDue()), delta); } QCOMPARE(todo->dtStart(/**first=*/true), dtstart); } } void RecurTodoTest::testDtStart() { QDateTime start(QDate(2013, 03, 10), QTime(10, 0, 0), Qt::UTC); KCalCore::Todo::Ptr todo(new KCalCore::Todo()); todo->setUid(QStringLiteral("todo")); todo->setDtStart(start); todo->recurrence()->setDaily(1); todo->recurrence()->setDuration(2); QCOMPARE(todo->dtStart(), start); KCalCore::Todo::Ptr todoWithDue(new KCalCore::Todo()); todoWithDue->setUid(QStringLiteral("todoWithDue")); todoWithDue->setDtStart(start); todoWithDue->setDtDue(QDateTime(start).addSecs(60)); todoWithDue->recurrence()->setDaily(1); todoWithDue->recurrence()->setDuration(2); QCOMPARE(todoWithDue->dtStart(), start); } void RecurTodoTest::testRecurrenceBasedOnDtStart() { const QDateTime dtstart(QDate(2013, 03, 10), QTime(10, 0, 0), Qt::UTC); const QDateTime dtdue(QDate(2013, 03, 10), QTime(11, 0, 0), Qt::UTC); KCalCore::Todo::Ptr todo(new KCalCore::Todo()); todo->setUid(QStringLiteral("todo")); todo->setDtStart(dtstart); todo->setDtDue(dtdue); todo->recurrence()->setDaily(1); todo->recurrence()->setDuration(3); QCOMPARE(todo->recurrence()->getNextDateTime(dtstart), dtstart.addDays(1)); QCOMPARE(todo->recurrence()->getNextDateTime(dtstart.addDays(1)), dtstart.addDays(2)); QCOMPARE(todo->recurrence()->getNextDateTime(dtstart.addDays(2)), QDateTime()); } //For backwards compatibility only void RecurTodoTest::testRecurrenceBasedOnDue() { const QDateTime dtdue(QDate(2013, 03, 10), QTime(11, 0, 0), Qt::UTC); KCalCore::Todo::Ptr todo(new KCalCore::Todo()); todo->setUid(QStringLiteral("todo")); todo->setDtDue(dtdue); todo->recurrence()->setDaily(1); todo->recurrence()->setDuration(3); QCOMPARE(todo->recurrence()->getNextDateTime(dtdue), dtdue.addDays(1)); QCOMPARE(todo->recurrence()->getNextDateTime(dtdue.addDays(1)), dtdue.addDays(2)); QCOMPARE(todo->recurrence()->getNextDateTime(dtdue.addDays(2)), QDateTime()); } diff --git a/src/calendar.cpp b/src/calendar.cpp index 71875fbbc..fa4b5a6bb 100644 --- a/src/calendar.cpp +++ b/src/calendar.cpp @@ -1,1465 +1,1464 @@ /* This file is part of the kcalcore library. Copyright (c) 1998 Preston Brown Copyright (c) 2000-2004 Cornelius Schumacher Copyright (C) 2003-2004 Reinhold Kainhofer Copyright (c) 2006 David Jarvie This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /** @file This file is part of the API for handling calendar data and defines the Calendar class. @brief Represents the main calendar class. @author Preston Brown \ @author Cornelius Schumacher \ @author Reinhold Kainhofer \ @author David Jarvie \ */ #include "calendar.h" #include "calfilter.h" #include "icaltimezones.h" #include "sorting.h" #include "visitor.h" #include "utils.h" #include "kcalcore_debug.h" #include extern "C" { #include } #include // for std::remove() using namespace KCalCore; /** Private class that helps to provide binary compatibility between releases. @internal */ //@cond PRIVATE class Q_DECL_HIDDEN KCalCore::Calendar::Private { public: Private() : mTimeZones(new ICalTimeZones), mModified(false), mNewObserver(false), mObserversEnabled(true), mDefaultFilter(new CalFilter), batchAddingInProgress(false), mDeletionTracking(true) { // Setup default filter, which does nothing mFilter = mDefaultFilter; mFilter->setEnabled(false); mOwner = Person::Ptr(new Person()); mOwner->setName(QStringLiteral("Unknown Name")); mOwner->setEmail(QStringLiteral("unknown@nowhere")); } ~Private() { delete mTimeZones; mTimeZones = nullptr; if (mFilter != mDefaultFilter) { delete mFilter; } delete mDefaultFilter; } QTimeZone timeZoneIdSpec(const QByteArray &timeZoneId); QString mProductId; Person::Ptr mOwner; ICalTimeZones *mTimeZones = nullptr; // collection of time zones used in this calendar ICalTimeZone mBuiltInTimeZone; // cached time zone lookup QTimeZone mTimeZone; bool mModified = false; bool mNewObserver = false; bool mObserversEnabled = false; QList mObservers; CalFilter *mDefaultFilter = nullptr; CalFilter *mFilter = nullptr; // These lists are used to put together related To-dos QMultiHash mOrphans; QMultiHash mOrphanUids; // Lists for associating incidences to notebooks QMultiHash mNotebookIncidences; QHash mUidToNotebook; QHash mNotebooks; // name to visibility QHash mIncidenceVisibility; // incidence -> visibility QString mDefaultNotebook; // uid of default notebook QMap mIncidenceRelations; bool batchAddingInProgress = false; bool mDeletionTracking = false; }; /** Make a QHash::value that returns a QVector. */ template QVector values(const QMultiHash &c) { QVector v; v.reserve(c.size()); for (typename QMultiHash::const_iterator it = c.begin(), end = c.end(); it != end; ++it) { v.push_back(it.value()); } return v; } template QVector values(const QMultiHash &c, const K &x) { QVector v; typename QMultiHash::const_iterator it = c.find(x); while (it != c.end() && it.key() == x) { v.push_back(it.value()); ++it; } return v; } /** Template for a class that implements a visitor for adding an Incidence to a resource supporting addEvent(), addTodo() and addJournal() calls. */ template class AddVisitor : public Visitor { public: AddVisitor(T *r) : mResource(r) {} bool visit(const Event::Ptr &e) override { return mResource->addEvent(e); } bool visit(const Todo::Ptr &t) override { return mResource->addTodo(t); } bool visit(const Journal::Ptr &j) override { return mResource->addJournal(j); } bool visit(const FreeBusy::Ptr &) override { return false; } private: T *mResource; }; /** Template for a class that implements a visitor for deleting an Incidence from a resource supporting deleteEvent(), deleteTodo() and deleteJournal() calls. */ template class DeleteVisitor : public Visitor { public: DeleteVisitor(T *r) : mResource(r) {} bool visit(const Event::Ptr &e) override { mResource->deleteEvent(e); return true; } bool visit(const Todo::Ptr &t) override { mResource->deleteTodo(t); return true; } bool visit(const Journal::Ptr &j) override { mResource->deleteJournal(j); return true; } bool visit(const FreeBusy::Ptr &) override { return false; } private: T *mResource; }; //@endcond Calendar::Calendar(const QTimeZone &timeZone) : d(new KCalCore::Calendar::Private) { d->mTimeZone = timeZone; } Calendar::Calendar(const QByteArray &timeZoneId) : d(new KCalCore::Calendar::Private) { setTimeZoneId(timeZoneId); } Calendar::~Calendar() { delete d; } Person::Ptr Calendar::owner() const { return d->mOwner; } void Calendar::setOwner(const Person::Ptr &owner) { Q_ASSERT(owner); d->mOwner = owner; setModified(true); } void Calendar::setTimeZone(const QTimeZone &timeZone) { d->mTimeZone = timeZone; d->mBuiltInTimeZone = ICalTimeZone(); doSetTimeZone(d->mTimeZone); } QTimeZone Calendar::timeZone() const { return d->mTimeZone; } void Calendar::setTimeZoneId(const QByteArray &timeZoneId) { d->mTimeZone = d->timeZoneIdSpec(timeZoneId); doSetTimeZone(d->mTimeZone); } //@cond PRIVATE QTimeZone Calendar::Private::timeZoneIdSpec(const QByteArray &timeZoneId) { mBuiltInTimeZone = ICalTimeZone(); if (timeZoneId == QByteArrayLiteral("UTC")) { return QTimeZone::utc(); } auto tz = QTimeZone(timeZoneId); if (tz.isValid()) return tz; return QTimeZone::systemTimeZone(); } //@endcond QByteArray Calendar::timeZoneId() const { return d->mTimeZone.id(); } ICalTimeZones *Calendar::timeZones() const { return d->mTimeZones; } void Calendar::setTimeZones(ICalTimeZones *zones) { if (!zones) { return; } if (d->mTimeZones && (d->mTimeZones != zones)) { delete d->mTimeZones; d->mTimeZones = nullptr; } d->mTimeZones = zones; } void Calendar::shiftTimes(const QTimeZone &oldZone, const QTimeZone &newZone) { setTimeZone(newZone); int i, end; Event::List ev = events(); for (i = 0, end = ev.count(); i < end; ++i) { ev[i]->shiftTimes(oldZone, newZone); } Todo::List to = todos(); for (i = 0, end = to.count(); i < end; ++i) { to[i]->shiftTimes(oldZone, newZone); } Journal::List jo = journals(); for (i = 0, end = jo.count(); i < end; ++i) { jo[i]->shiftTimes(oldZone, newZone); } } void Calendar::setFilter(CalFilter *filter) { if (filter) { d->mFilter = filter; } else { d->mFilter = d->mDefaultFilter; } emit filterChanged(); } CalFilter *Calendar::filter() const { return d->mFilter; } QStringList Calendar::categories() const { Incidence::List rawInc(rawIncidences()); QStringList cats, thisCats; // @TODO: For now just iterate over all incidences. In the future, // the list of categories should be built when reading the file. for (Incidence::List::ConstIterator i = rawInc.constBegin(); i != rawInc.constEnd(); ++i) { thisCats = (*i)->categories(); for (QStringList::ConstIterator si = thisCats.constBegin(); si != thisCats.constEnd(); ++si) { if (!cats.contains(*si)) { cats.append(*si); } } } return cats; } Incidence::List Calendar::incidences(const QDate &date) const { return mergeIncidenceList(events(date), todos(date), journals(date)); } Incidence::List Calendar::incidences() const { return mergeIncidenceList(events(), todos(), journals()); } Incidence::List Calendar::rawIncidences() const { return mergeIncidenceList(rawEvents(), rawTodos(), rawJournals()); } Incidence::List Calendar::instances(const Incidence::Ptr &incidence) const { if (incidence) { Event::List elist; Todo::List tlist; Journal::List jlist; if (incidence->type() == Incidence::TypeEvent) { elist = eventInstances(incidence); } else if (incidence->type() == Incidence::TypeTodo) { tlist = todoInstances(incidence); } else if (incidence->type() == Incidence::TypeJournal) { jlist = journalInstances(incidence); } return mergeIncidenceList(elist, tlist, jlist); } else { return Incidence::List(); } } Incidence::List Calendar::duplicates(const Incidence::Ptr &incidence) { if (incidence) { Incidence::List list; Incidence::List vals = values(d->mNotebookIncidences); Incidence::List::const_iterator it; for (it = vals.constBegin(); it != vals.constEnd(); ++it) { if (((incidence->dtStart() == (*it)->dtStart()) || (!incidence->dtStart().isValid() && !(*it)->dtStart().isValid())) && (incidence->summary() == (*it)->summary())) { list.append(*it); } } return list; } else { return Incidence::List(); } } bool Calendar::addNotebook(const QString ¬ebook, bool isVisible) { if (d->mNotebooks.contains(notebook)) { return false; } else { d->mNotebooks.insert(notebook, isVisible); return true; } } bool Calendar::updateNotebook(const QString ¬ebook, bool isVisible) { if (!d->mNotebooks.contains(notebook)) { return false; } else { d->mNotebooks.insert(notebook, isVisible); return true; } } bool Calendar::deleteNotebook(const QString ¬ebook) { if (!d->mNotebooks.contains(notebook)) { return false; } else { return d->mNotebooks.remove(notebook); } } bool Calendar::setDefaultNotebook(const QString ¬ebook) { if (!d->mNotebooks.contains(notebook)) { return false; } else { d->mDefaultNotebook = notebook; return true; } } QString Calendar::defaultNotebook() const { return d->mDefaultNotebook; } bool Calendar::hasValidNotebook(const QString ¬ebook) const { return d->mNotebooks.contains(notebook); } bool Calendar::isVisible(const Incidence::Ptr &incidence) const { if (d->mIncidenceVisibility.contains(incidence)) { return d->mIncidenceVisibility[incidence]; } const QString nuid = notebook(incidence); bool rv; if (d->mNotebooks.contains(nuid)) { rv = d->mNotebooks.value(nuid); } else { // NOTE returns true also for nonexisting notebooks for compatibility rv = true; } d->mIncidenceVisibility[incidence] = rv; return rv; } void Calendar::clearNotebookAssociations() { d->mNotebookIncidences.clear(); d->mUidToNotebook.clear(); d->mIncidenceVisibility.clear(); } bool Calendar::setNotebook(const Incidence::Ptr &inc, const QString ¬ebook) { if (!inc) { return false; } if (!notebook.isEmpty() && !incidence(inc->uid(), inc->recurrenceId())) { qCWarning(KCALCORE_LOG) << "cannot set notebook until incidence has been added"; return false; } if (d->mUidToNotebook.contains(inc->uid())) { QString old = d->mUidToNotebook.value(inc->uid()); if (!old.isEmpty() && notebook != old) { if (inc->hasRecurrenceId()) { qCWarning(KCALCORE_LOG) << "cannot set notebook for child incidences"; return false; } // Move all possible children also. Incidence::List list = instances(inc); Incidence::List::Iterator it; for (it = list.begin(); it != list.end(); ++it) { d->mNotebookIncidences.remove(old, *it); d->mNotebookIncidences.insert(notebook, *it); } notifyIncidenceChanged(inc); // for removing from old notebook // don not remove from mUidToNotebook to keep deleted incidences d->mNotebookIncidences.remove(old, inc); } } if (!notebook.isEmpty()) { d->mUidToNotebook.insert(inc->uid(), notebook); d->mNotebookIncidences.insert(notebook, inc); qCDebug(KCALCORE_LOG) << "setting notebook" << notebook << "for" << inc->uid(); notifyIncidenceChanged(inc); // for inserting into new notebook } return true; } QString Calendar::notebook(const Incidence::Ptr &incidence) const { if (incidence) { return d->mUidToNotebook.value(incidence->uid()); } else { return QString(); } } QString Calendar::notebook(const QString &uid) const { return d->mUidToNotebook.value(uid); } QStringList Calendar::notebooks() const { return d->mNotebookIncidences.uniqueKeys(); } Incidence::List Calendar::incidences(const QString ¬ebook) const { if (notebook.isEmpty()) { return values(d->mNotebookIncidences); } else { return values(d->mNotebookIncidences, notebook); } } /** static */ Event::List Calendar::sortEvents(const Event::List &eventList, EventSortField sortField, SortDirection sortDirection) { if (eventList.isEmpty()) { return Event::List(); } Event::List eventListSorted; // Notice we alphabetically presort Summaries first. // We do this so comparison "ties" stay in a nice order. eventListSorted = eventList; switch (sortField) { case EventSortUnsorted: break; case EventSortStartDate: if (sortDirection == SortDirectionAscending) { std::sort(eventListSorted.begin(), eventListSorted.end(), Events::startDateLessThan); } else { std::sort(eventListSorted.begin(), eventListSorted.end(), Events::startDateMoreThan); } break; case EventSortEndDate: if (sortDirection == SortDirectionAscending) { std::sort(eventListSorted.begin(), eventListSorted.end(), Events::endDateLessThan); } else { std::sort(eventListSorted.begin(), eventListSorted.end(), Events::endDateMoreThan); } break; case EventSortSummary: if (sortDirection == SortDirectionAscending) { std::sort(eventListSorted.begin(), eventListSorted.end(), Events::summaryLessThan); } else { std::sort(eventListSorted.begin(), eventListSorted.end(), Events::summaryMoreThan); } break; } return eventListSorted; } Event::List Calendar::events(const QDate &date, const QTimeZone &timeZone, EventSortField sortField, SortDirection sortDirection) const { Event::List el = rawEventsForDate(date, timeZone, sortField, sortDirection); d->mFilter->apply(&el); return el; } Event::List Calendar::events(const QDateTime &dt) const { Event::List el = rawEventsForDate(dt); d->mFilter->apply(&el); return el; } Event::List Calendar::events(const QDate &start, const QDate &end, const QTimeZone &timeZone, bool inclusive) const { Event::List el = rawEvents(start, end, timeZone, inclusive); d->mFilter->apply(&el); return el; } Event::List Calendar::events(EventSortField sortField, SortDirection sortDirection) const { Event::List el = rawEvents(sortField, sortDirection); d->mFilter->apply(&el); return el; } bool Calendar::addIncidence(const Incidence::Ptr &incidence) { if (!incidence) { return false; } AddVisitor v(this); return incidence->accept(v, incidence); } bool Calendar::deleteIncidence(const Incidence::Ptr &incidence) { if (!incidence) { return false; } if (beginChange(incidence)) { DeleteVisitor v(this); const bool result = incidence->accept(v, incidence); endChange(incidence); return result; } else { return false; } } Incidence::Ptr Calendar::createException(const Incidence::Ptr &incidence, const QDateTime &recurrenceId, bool thisAndFuture) { Q_ASSERT(recurrenceId.isValid()); if (!incidence || !incidence->recurs() || !recurrenceId.isValid()) { return Incidence::Ptr(); } Incidence::Ptr newInc(incidence->clone()); newInc->setCreated(QDateTime::currentDateTimeUtc()); newInc->setRevision(0); //Recurring exceptions are not support for now newInc->clearRecurrence(); newInc->setRecurrenceId(recurrenceId); newInc->setThisAndFuture(thisAndFuture); newInc->setDtStart(recurrenceId); // Calculate and set the new end of the incidence QDateTime end = incidence->dateTime(IncidenceBase::RoleEnd); if (end.isValid()) { if (incidence->allDay()) { int offset = incidence->dtStart().daysTo(recurrenceId); end = end.addDays(offset); } else { qint64 offset = incidence->dtStart().secsTo(recurrenceId); end = end.addSecs(offset); } newInc->setDateTime(end, IncidenceBase::RoleEnd); } return newInc; } Incidence::Ptr Calendar::incidence(const QString &uid, const QDateTime &recurrenceId) const { Incidence::Ptr i = event(uid, recurrenceId); if (i) { return i; } i = todo(uid, recurrenceId); if (i) { return i; } i = journal(uid, recurrenceId); return i; } Incidence::Ptr Calendar::deleted(const QString &uid, const QDateTime &recurrenceId) const { Incidence::Ptr i = deletedEvent(uid, recurrenceId); if (i) { return i; } i = deletedTodo(uid, recurrenceId); if (i) { return i; } i = deletedJournal(uid, recurrenceId); return i; } Incidence::List Calendar::incidencesFromSchedulingID(const QString &sid) const { Incidence::List result; const Incidence::List incidences = rawIncidences(); Incidence::List::const_iterator it = incidences.begin(); for (; it != incidences.end(); ++it) { if ((*it)->schedulingID() == sid) { result.append(*it); } } return result; } Incidence::Ptr Calendar::incidenceFromSchedulingID(const QString &uid) const { const Incidence::List incidences = rawIncidences(); Incidence::List::const_iterator it = incidences.begin(); for (; it != incidences.end(); ++it) { if ((*it)->schedulingID() == uid) { // Touchdown, and the crowd goes wild return *it; } } // Not found return Incidence::Ptr(); } /** static */ Todo::List Calendar::sortTodos(const Todo::List &todoList, TodoSortField sortField, SortDirection sortDirection) { if (todoList.isEmpty()) { return Todo::List(); } Todo::List todoListSorted; // Notice we alphabetically presort Summaries first. // We do this so comparison "ties" stay in a nice order. // Note that To-dos may not have Start DateTimes nor due DateTimes. todoListSorted = todoList; switch (sortField) { case TodoSortUnsorted: break; case TodoSortStartDate: if (sortDirection == SortDirectionAscending) { std::sort(todoListSorted.begin(), todoListSorted.end(), Todos::startDateLessThan); } else { std::sort(todoListSorted.begin(), todoListSorted.end(), Todos::startDateMoreThan); } break; case TodoSortDueDate: if (sortDirection == SortDirectionAscending) { std::sort(todoListSorted.begin(), todoListSorted.end(), Todos::dueDateLessThan); } else { std::sort(todoListSorted.begin(), todoListSorted.end(), Todos::dueDateMoreThan); } break; case TodoSortPriority: if (sortDirection == SortDirectionAscending) { std::sort(todoListSorted.begin(), todoListSorted.end(), Todos::priorityLessThan); } else { std::sort(todoListSorted.begin(), todoListSorted.end(), Todos::priorityMoreThan); } break; case TodoSortPercentComplete: if (sortDirection == SortDirectionAscending) { std::sort(todoListSorted.begin(), todoListSorted.end(), Todos::percentLessThan); } else { std::sort(todoListSorted.begin(), todoListSorted.end(), Todos::percentMoreThan); } break; case TodoSortSummary: if (sortDirection == SortDirectionAscending) { std::sort(todoListSorted.begin(), todoListSorted.end(), Todos::summaryLessThan); } else { std::sort(todoListSorted.begin(), todoListSorted.end(), Todos::summaryMoreThan); } break; case TodoSortCreated: if (sortDirection == SortDirectionAscending) { std::sort(todoListSorted.begin(), todoListSorted.end(), Todos::createdLessThan); } else { std::sort(todoListSorted.begin(), todoListSorted.end(), Todos::createdMoreThan); } break; } return todoListSorted; } Todo::List Calendar::todos(TodoSortField sortField, SortDirection sortDirection) const { Todo::List tl = rawTodos(sortField, sortDirection); d->mFilter->apply(&tl); return tl; } Todo::List Calendar::todos(const QDate &date) const { Todo::List el = rawTodosForDate(date); d->mFilter->apply(&el); return el; } Todo::List Calendar::todos(const QDate &start, const QDate &end, const QTimeZone &timeZone, bool inclusive) const { Todo::List tl = rawTodos(start, end, timeZone, inclusive); d->mFilter->apply(&tl); return tl; } /** static */ Journal::List Calendar::sortJournals(const Journal::List &journalList, JournalSortField sortField, SortDirection sortDirection) { if (journalList.isEmpty()) { return Journal::List(); } Journal::List journalListSorted = journalList; switch (sortField) { case JournalSortUnsorted: break; case JournalSortDate: if (sortDirection == SortDirectionAscending) { std::sort(journalListSorted.begin(), journalListSorted.end(), Journals::dateLessThan); } else { std::sort(journalListSorted.begin(), journalListSorted.end(), Journals::dateMoreThan); } break; case JournalSortSummary: if (sortDirection == SortDirectionAscending) { std::sort(journalListSorted.begin(), journalListSorted.end(), Journals::summaryLessThan); } else { std::sort(journalListSorted.begin(), journalListSorted.end(), Journals::summaryMoreThan); } break; } return journalListSorted; } Journal::List Calendar::journals(JournalSortField sortField, SortDirection sortDirection) const { Journal::List jl = rawJournals(sortField, sortDirection); d->mFilter->apply(&jl); return jl; } Journal::List Calendar::journals(const QDate &date) const { Journal::List el = rawJournalsForDate(date); d->mFilter->apply(&el); return el; } // When this is called, the to-dos have already been added to the calendar. // This method is only about linking related to-dos. void Calendar::setupRelations(const Incidence::Ptr &forincidence) { if (!forincidence) { return; } const QString uid = forincidence->uid(); // First, go over the list of orphans and see if this is their parent Incidence::List l = values(d->mOrphans, uid); d->mOrphans.remove(uid); if (!l.isEmpty()) { Incidence::List &relations = d->mIncidenceRelations[uid]; relations.reserve(relations.count() + l.count()); for (int i = 0, end = l.count(); i < end; ++i) { relations.append(l[i]); d->mOrphanUids.remove(l[i]->uid()); } } // Now see about this incidences parent if (forincidence->relatedTo().isEmpty() && !forincidence->relatedTo().isEmpty()) { // Incidence has a uid it is related to but is not registered to it yet. // Try to find it Incidence::Ptr parent = incidence(forincidence->relatedTo()); if (parent) { // Found it // look for hierarchy loops if (isAncestorOf(forincidence, parent)) { forincidence->setRelatedTo(QString()); qCWarning(KCALCORE_LOG) << "hierarchy loop beetween " << forincidence->uid() << " and " << parent->uid(); } else { d->mIncidenceRelations[parent->uid()].append(forincidence); } } else { // Not found, put this in the mOrphans list // Note that the mOrphans dict might contain multiple entries with the // same key! which are multiple children that wait for the parent // incidence to be inserted. d->mOrphans.insert(forincidence->relatedTo(), forincidence); d->mOrphanUids.insert(forincidence->uid(), forincidence); } } } // If a to-do with sub-to-dos is deleted, move it's sub-to-dos to the orphan list void Calendar::removeRelations(const Incidence::Ptr &incidence) { if (!incidence) { qCDebug(KCALCORE_LOG) << "Warning: incidence is 0"; return; } const QString uid = incidence->uid(); foreach (const Incidence::Ptr &i, d->mIncidenceRelations[uid]) { if (!d->mOrphanUids.contains(i->uid())) { d->mOrphans.insert(uid, i); d->mOrphanUids.insert(i->uid(), i); i->setRelatedTo(uid); } } const QString parentUid = incidence->relatedTo(); // If this incidence is related to something else, tell that about it if (!parentUid.isEmpty()) { Incidence::List &relations = d->mIncidenceRelations[parentUid]; relations.erase( std::remove(relations.begin(), relations.end(), incidence), relations.end()); } // Remove this one from the orphans list if (d->mOrphanUids.remove(uid)) { // This incidence is located in the orphans list - it should be removed // Since the mOrphans dict might contain the same key (with different // child incidence pointers!) multiple times, take care that we remove // the correct one. So we need to remove all items with the given // parent UID, and readd those that are not for this item. Also, there // might be other entries with differnet UID that point to this // incidence (this might happen when the relatedTo of the item is // changed before its parent is inserted. This might happen with // groupware servers....). Remove them, too QStringList relatedToUids; // First, create a list of all keys in the mOrphans list which point // to the removed item relatedToUids << incidence->relatedTo(); for (QMultiHash::Iterator it = d->mOrphans.begin(); it != d->mOrphans.end(); ++it) { if (it.value()->uid() == uid) { relatedToUids << it.key(); } } // now go through all uids that have one entry that point to the incidence for (QStringList::const_iterator uidit = relatedToUids.constBegin(); uidit != relatedToUids.constEnd(); ++uidit) { Incidence::List tempList; // Remove all to get access to the remaining entries const Incidence::List l = values(d->mOrphans, *uidit); d->mOrphans.remove(*uidit); for (const Incidence::Ptr &i : l) { if (i != incidence) { tempList.append(i); } } // Readd those that point to a different orphan incidence for (Incidence::List::Iterator incit = tempList.begin(); incit != tempList.end(); ++incit) { d->mOrphans.insert(*uidit, *incit); } } } // Make sure the deleted incidence doesn't relate to a non-deleted incidence, // since that would cause trouble in MemoryCalendar::close(), as the deleted // incidences are destroyed after the non-deleted incidences. The destructor // of the deleted incidences would then try to access the already destroyed // non-deleted incidence, which would segfault. // // So in short: Make sure dead incidences don't point to alive incidences // via the relation. // // This crash is tested in MemoryCalendarTest::testRelationsCrash(). // incidence->setRelatedTo( Incidence::Ptr() ); } bool Calendar::isAncestorOf(const Incidence::Ptr &ancestor, const Incidence::Ptr &incidence) const { if (!incidence || incidence->relatedTo().isEmpty()) { return false; } else if (incidence->relatedTo() == ancestor->uid()) { return true; } else { return isAncestorOf(ancestor, this->incidence(incidence->relatedTo())); } } Incidence::List Calendar::relations(const QString &uid) const { return d->mIncidenceRelations[uid]; } Calendar::CalendarObserver::~CalendarObserver() { } void Calendar::CalendarObserver::calendarModified(bool modified, Calendar *calendar) { Q_UNUSED(modified); Q_UNUSED(calendar); } void Calendar::CalendarObserver::calendarIncidenceAdded(const Incidence::Ptr &incidence) { Q_UNUSED(incidence); } void Calendar::CalendarObserver::calendarIncidenceChanged(const Incidence::Ptr &incidence) { Q_UNUSED(incidence); } void Calendar::CalendarObserver::calendarIncidenceAboutToBeDeleted(const Incidence::Ptr &incidence) { Q_UNUSED(incidence); } void Calendar::CalendarObserver::calendarIncidenceDeleted(const Incidence::Ptr &incidence) { Q_UNUSED(incidence); } void Calendar::CalendarObserver::calendarIncidenceDeleted(const Incidence::Ptr &incidence, const Calendar *calendar) { Q_UNUSED(incidence); Q_UNUSED(calendar); } void Calendar::CalendarObserver::calendarIncidenceAdditionCanceled(const Incidence::Ptr &incidence) { Q_UNUSED(incidence); } void Calendar::registerObserver(CalendarObserver *observer) { if (!observer) { return; } if (!d->mObservers.contains(observer)) { d->mObservers.append(observer); } else { d->mNewObserver = true; } } void Calendar::unregisterObserver(CalendarObserver *observer) { if (!observer) { return; } else { d->mObservers.removeAll(observer); } } bool Calendar::isSaving() const { return false; } void Calendar::setModified(bool modified) { if (modified != d->mModified || d->mNewObserver) { d->mNewObserver = false; for (CalendarObserver *observer : qAsConst(d->mObservers)) { observer->calendarModified(modified, this); } d->mModified = modified; } } bool Calendar::isModified() const { return d->mModified; } bool Calendar::save() { return true; } bool Calendar::reload() { return true; } void Calendar::incidenceUpdated(const QString &uid, const QDateTime &recurrenceId) { Incidence::Ptr inc = incidence(uid, recurrenceId); if (!inc) { return; } inc->setLastModified(QDateTime::currentDateTimeUtc()); // we should probably update the revision number here, // or internally in the Event itself when certain things change. // need to verify with ical documentation. notifyIncidenceChanged(inc); setModified(true); } void Calendar::doSetTimeZone(const QTimeZone &timeZone) { Q_UNUSED(timeZone); } void Calendar::notifyIncidenceAdded(const Incidence::Ptr &incidence) { if (!incidence) { return; } if (!d->mObserversEnabled) { return; } for (CalendarObserver *observer : qAsConst(d->mObservers)) { observer->calendarIncidenceAdded(incidence); } } void Calendar::notifyIncidenceChanged(const Incidence::Ptr &incidence) { if (!incidence) { return; } if (!d->mObserversEnabled) { return; } for (CalendarObserver *observer : qAsConst(d->mObservers)) { observer->calendarIncidenceChanged(incidence); } } void Calendar::notifyIncidenceAboutToBeDeleted(const Incidence::Ptr &incidence) { if (!incidence) { return; } if (!d->mObserversEnabled) { return; } for (CalendarObserver *observer : qAsConst(d->mObservers)) { observer->calendarIncidenceAboutToBeDeleted(incidence); } } void Calendar::notifyIncidenceDeletedOld(const Incidence::Ptr &incidence) { if (!incidence) { return; } if (!d->mObserversEnabled) { return; } for (CalendarObserver *observer : qAsConst(d->mObservers)) { observer->calendarIncidenceDeleted(incidence); } } void Calendar::notifyIncidenceDeleted(const Incidence::Ptr &incidence) { if (!incidence) { return; } if (!d->mObserversEnabled) { return; } for (CalendarObserver *observer : qAsConst(d->mObservers)) { observer->calendarIncidenceDeleted(incidence, this); } } void Calendar::notifyIncidenceAdditionCanceled(const Incidence::Ptr &incidence) { if (!incidence) { return; } if (!d->mObserversEnabled) { return; } for (CalendarObserver *observer : qAsConst(d->mObservers)) { observer->calendarIncidenceAdditionCanceled(incidence); } } void Calendar::customPropertyUpdated() { setModified(true); } void Calendar::setProductId(const QString &id) { d->mProductId = id; } QString Calendar::productId() const { return d->mProductId; } /** static */ Incidence::List Calendar::mergeIncidenceList(const Event::List &events, const Todo::List &todos, const Journal::List &journals) { Incidence::List incidences; incidences.reserve(events.count() + todos.count() + journals.count()); int i, end; for (i = 0, end = events.count(); i < end; ++i) { incidences.append(events[i]); } for (i = 0, end = todos.count(); i < end; ++i) { incidences.append(todos[i]); } for (i = 0, end = journals.count(); i < end; ++i) { incidences.append(journals[i]); } return incidences; } bool Calendar::beginChange(const Incidence::Ptr &incidence) { Q_UNUSED(incidence); return true; } bool Calendar::endChange(const Incidence::Ptr &incidence) { Q_UNUSED(incidence); return true; } void Calendar::setObserversEnabled(bool enabled) { d->mObserversEnabled = enabled; } void Calendar::appendAlarms(Alarm::List &alarms, const Incidence::Ptr &incidence, const QDateTime &from, const QDateTime &to) const { QDateTime preTime = from.addSecs(-1); Alarm::List alarmlist = incidence->alarms(); for (int i = 0, iend = alarmlist.count(); i < iend; ++i) { if (alarmlist[i]->enabled()) { QDateTime dt = alarmlist[i]->nextRepetition(preTime); if (dt.isValid() && dt <= to) { qCDebug(KCALCORE_LOG) << incidence->summary() << "':" << dt.toString(); alarms.append(alarmlist[i]); } } } } void Calendar::appendRecurringAlarms(Alarm::List &alarms, const Incidence::Ptr &incidence, const QDateTime &from, const QDateTime &to) const { QDateTime dt; bool endOffsetValid = false; Duration endOffset(0); Duration period(from, to); Alarm::List alarmlist = incidence->alarms(); for (int i = 0, iend = alarmlist.count(); i < iend; ++i) { Alarm::Ptr a = alarmlist[i]; if (a->enabled()) { if (a->hasTime()) { // The alarm time is defined as an absolute date/time dt = a->nextRepetition(from.addSecs(-1)); if (!dt.isValid() || dt > to) { continue; } } else { // Alarm time is defined by an offset from the event start or end time. // Find the offset from the event start time, which is also used as the // offset from the recurrence time. Duration offset(0); if (a->hasStartOffset()) { offset = a->startOffset(); } else if (a->hasEndOffset()) { offset = a->endOffset(); if (!endOffsetValid) { endOffset = Duration(incidence->dtStart(), incidence->dateTime(Incidence::RoleAlarmEndOffset)); endOffsetValid = true; } } // Find the incidence's earliest alarm QDateTime alarmStart = offset.end(a->hasEndOffset() ? incidence->dateTime(Incidence::RoleAlarmEndOffset) : incidence->dtStart()); -// KDateTime alarmStart = incidence->dtStart().addSecs( offset ); if (alarmStart > to) { continue; } QDateTime baseStart = incidence->dtStart(); if (from > alarmStart) { alarmStart = from; // don't look earlier than the earliest alarm baseStart = (-offset).end((-endOffset).end(alarmStart)); } // Adjust the 'alarmStart' date/time and find the next recurrence at or after it. // Treate the two offsets separately in case one is daily and the other not. dt = incidence->recurrence()->getNextDateTime(baseStart.addSecs(-1)); if (!dt.isValid() || (dt = endOffset.end(offset.end(dt))) > to) { // adjust 'dt' to get the alarm time // The next recurrence is too late. if (!a->repeatCount()) { continue; } // The alarm has repetitions, so check whether repetitions of previous // recurrences fall within the time period. bool found = false; Duration alarmDuration = a->duration(); for (QDateTime base = baseStart; (dt = incidence->recurrence()->getPreviousDateTime(base)).isValid(); base = dt) { if (a->duration().end(dt) < base) { break; // this recurrence's last repetition is too early, so give up } // The last repetition of this recurrence is at or after 'alarmStart' time. // Check if a repetition occurs between 'alarmStart' and 'to'. int snooze = a->snoozeTime().value(); // in seconds or days if (a->snoozeTime().isDaily()) { Duration toFromDuration(dt, base); int toFrom = toFromDuration.asDays(); if (a->snoozeTime().end(from) <= to || (toFromDuration.isDaily() && toFrom % snooze == 0) || (toFrom / snooze + 1) * snooze <= toFrom + period.asDays()) { found = true; #ifndef NDEBUG // for debug output dt = offset.end(dt).addDays(((toFrom - 1) / snooze + 1) * snooze); #endif break; } } else { int toFrom = dt.secsTo(base); if (period.asSeconds() >= snooze || toFrom % snooze == 0 || (toFrom / snooze + 1) * snooze <= toFrom + period.asSeconds()) { found = true; #ifndef NDEBUG // for debug output dt = offset.end(dt).addSecs(((toFrom - 1) / snooze + 1) * snooze); #endif break; } } } if (!found) { continue; } } } qCDebug(KCALCORE_LOG) << incidence->summary() << "':" << dt.toString(); alarms.append(a); } } } void Calendar::startBatchAdding() { d->batchAddingInProgress = true; } void Calendar::endBatchAdding() { d->batchAddingInProgress = false; } bool Calendar::batchAdding() const { return d->batchAddingInProgress; } void Calendar::setDeletionTracking(bool enable) { d->mDeletionTracking = enable; } bool Calendar::deletionTracking() const { return d->mDeletionTracking; } void Calendar::virtual_hook(int id, void *data) { Q_UNUSED(id); Q_UNUSED(data); Q_ASSERT(false); } diff --git a/src/recurrence.cpp b/src/recurrence.cpp index d31dd4563..bd9f1188b 100644 --- a/src/recurrence.cpp +++ b/src/recurrence.cpp @@ -1,1575 +1,1575 @@ /* This file is part of kcalcore library. Copyright (c) 1998 Preston Brown Copyright (c) 2001 Cornelius Schumacher Copyright (c) 2002,2006 David Jarvie Copyright (C) 2005 Reinhold Kainhofer This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "recurrence.h" #include "sortablelist.h" #include "utils.h" #include "kcalcore_debug.h" #include #include #include using namespace KCalCore; //@cond PRIVATE class Q_DECL_HIDDEN KCalCore::Recurrence::Private { public: Private() : mCachedType(rMax), mAllDay(false), mRecurReadOnly(false) { } Private(const Private &p) : mRDateTimes(p.mRDateTimes), mRDates(p.mRDates), mExDateTimes(p.mExDateTimes), mExDates(p.mExDates), mStartDateTime(p.mStartDateTime), mCachedType(p.mCachedType), mAllDay(p.mAllDay), mRecurReadOnly(p.mRecurReadOnly) { } bool operator==(const Private &p) const; RecurrenceRule::List mExRules; RecurrenceRule::List mRRules; SortableList mRDateTimes; DateList mRDates; SortableList mExDateTimes; DateList mExDates; QDateTime mStartDateTime; // date/time of first recurrence QList mObservers; // Cache the type of the recurrence with the old system (e.g. MonthlyPos) mutable ushort mCachedType; bool mAllDay = false; // the recurrence has no time, just a date bool mRecurReadOnly = false; }; bool Recurrence::Private::operator==(const Recurrence::Private &p) const { // qCDebug(KCALCORE_LOG) << mStartDateTime << p.mStartDateTime; if ((mStartDateTime != p.mStartDateTime && (mStartDateTime.isValid() || p.mStartDateTime.isValid())) || mAllDay != p.mAllDay || mRecurReadOnly != p.mRecurReadOnly || mExDates != p.mExDates || mExDateTimes != p.mExDateTimes || mRDates != p.mRDates || mRDateTimes != p.mRDateTimes) { return false; } // Compare the rrules, exrules! Assume they have the same order... This only // matters if we have more than one rule (which shouldn't be the default anyway) int i; int end = mRRules.count(); if (end != p.mRRules.count()) { return false; } for (i = 0; i < end; ++i) { if (*mRRules[i] != *p.mRRules[i]) { return false; } } end = mExRules.count(); if (end != p.mExRules.count()) { return false; } for (i = 0; i < end; ++i) { if (*mExRules[i] != *p.mExRules[i]) { return false; } } return true; } //@endcond Recurrence::Recurrence() : d(new KCalCore::Recurrence::Private()) { } Recurrence::Recurrence(const Recurrence &r) : RecurrenceRule::RuleObserver(), d(new KCalCore::Recurrence::Private(*r.d)) { int i, end; d->mRRules.reserve(r.d->mRRules.count()); for (i = 0, end = r.d->mRRules.count(); i < end; ++i) { RecurrenceRule *rule = new RecurrenceRule(*r.d->mRRules[i]); d->mRRules.append(rule); rule->addObserver(this); } d->mExRules.reserve(r.d->mExRules.count()); for (i = 0, end = r.d->mExRules.count(); i < end; ++i) { RecurrenceRule *rule = new RecurrenceRule(*r.d->mExRules[i]); d->mExRules.append(rule); rule->addObserver(this); } } Recurrence::~Recurrence() { qDeleteAll(d->mExRules); qDeleteAll(d->mRRules); delete d; } bool Recurrence::operator==(const Recurrence &recurrence) const { return *d == *recurrence.d; } Recurrence &Recurrence::operator=(const Recurrence &recurrence) { // check for self assignment if (&recurrence == this) { return *this; } *d = *recurrence.d; return *this; } void Recurrence::addObserver(RecurrenceObserver *observer) { if (!d->mObservers.contains(observer)) { d->mObservers.append(observer); } } void Recurrence::removeObserver(RecurrenceObserver *observer) { d->mObservers.removeAll(observer); } QDateTime Recurrence::startDateTime() const { return d->mStartDateTime; } bool Recurrence::allDay() const { return d->mAllDay; } void Recurrence::setAllDay(bool allDay) { if (d->mRecurReadOnly || allDay == d->mAllDay) { return; } d->mAllDay = allDay; for (int i = 0, end = d->mRRules.count(); i < end; ++i) { d->mRRules[i]->setAllDay(allDay); } for (int i = 0, end = d->mExRules.count(); i < end; ++i) { d->mExRules[i]->setAllDay(allDay); } updated(); } RecurrenceRule *Recurrence::defaultRRule(bool create) const { if (d->mRRules.isEmpty()) { if (!create || d->mRecurReadOnly) { return nullptr; } RecurrenceRule *rrule = new RecurrenceRule(); rrule->setStartDt(startDateTime()); const_cast(this)->addRRule(rrule); return rrule; } else { return d->mRRules[0]; } } RecurrenceRule *Recurrence::defaultRRuleConst() const { return d->mRRules.isEmpty() ? nullptr : d->mRRules[0]; } void Recurrence::updated() { // recurrenceType() re-calculates the type if it's rMax d->mCachedType = rMax; for (int i = 0, end = d->mObservers.count(); i < end; ++i) { if (d->mObservers[i]) { d->mObservers[i]->recurrenceUpdated(this); } } } bool Recurrence::recurs() const { return !d->mRRules.isEmpty() || !d->mRDates.isEmpty() || !d->mRDateTimes.isEmpty(); } ushort Recurrence::recurrenceType() const { if (d->mCachedType == rMax) { d->mCachedType = recurrenceType(defaultRRuleConst()); } return d->mCachedType; } ushort Recurrence::recurrenceType(const RecurrenceRule *rrule) { if (!rrule) { return rNone; } RecurrenceRule::PeriodType type = rrule->recurrenceType(); // BYSETPOS, BYWEEKNUMBER and BYSECOND were not supported in old versions if (!rrule->bySetPos().isEmpty() || !rrule->bySeconds().isEmpty() || !rrule->byWeekNumbers().isEmpty()) { return rOther; } // It wasn't possible to set BYMINUTES, BYHOUR etc. by the old code. So if // it's set, it's none of the old types if (!rrule->byMinutes().isEmpty() || !rrule->byHours().isEmpty()) { return rOther; } // Possible combinations were: // BYDAY: with WEEKLY, MONTHLY, YEARLY // BYMONTHDAY: with MONTHLY, YEARLY // BYMONTH: with YEARLY // BYYEARDAY: with YEARLY if ((!rrule->byYearDays().isEmpty() && type != RecurrenceRule::rYearly) || (!rrule->byMonths().isEmpty() && type != RecurrenceRule::rYearly)) { return rOther; } if (!rrule->byDays().isEmpty()) { if (type != RecurrenceRule::rYearly && type != RecurrenceRule::rMonthly && type != RecurrenceRule::rWeekly) { return rOther; } } switch (type) { case RecurrenceRule::rNone: return rNone; case RecurrenceRule::rMinutely: return rMinutely; case RecurrenceRule::rHourly: return rHourly; case RecurrenceRule::rDaily: return rDaily; case RecurrenceRule::rWeekly: return rWeekly; case RecurrenceRule::rMonthly: { if (rrule->byDays().isEmpty()) { return rMonthlyDay; } else if (rrule->byMonthDays().isEmpty()) { return rMonthlyPos; } else { return rOther; // both position and date specified } } case RecurrenceRule::rYearly: { // Possible combinations: // rYearlyMonth: [BYMONTH &] BYMONTHDAY // rYearlyDay: BYYEARDAY // rYearlyPos: [BYMONTH &] BYDAY if (!rrule->byDays().isEmpty()) { // can only by rYearlyPos if (rrule->byMonthDays().isEmpty() && rrule->byYearDays().isEmpty()) { return rYearlyPos; } else { return rOther; } } else if (!rrule->byYearDays().isEmpty()) { // Can only be rYearlyDay if (rrule->byMonths().isEmpty() && rrule->byMonthDays().isEmpty()) { return rYearlyDay; } else { return rOther; } } else { return rYearlyMonth; } break; } default: return rOther; } return rOther; } bool Recurrence::recursOn(const QDate &qd, const QTimeZone &timeZone) const { // Don't waste time if date is before the start of the recurrence if (QDateTime(qd, QTime(23, 59, 59), timeZone) < d->mStartDateTime) { return false; } // First handle dates. Exrules override if (d->mExDates.containsSorted(qd)) { return false; } int i, end; TimeList tms; // For all-day events a matching exrule excludes the whole day // since exclusions take precedence over inclusions, we know it can't occur on that day. if (allDay()) { for (i = 0, end = d->mExRules.count(); i < end; ++i) { if (d->mExRules[i]->recursOn(qd, timeZone)) { return false; } } } if (d->mRDates.containsSorted(qd)) { return true; } // Check if it might recur today at all. bool recurs = (startDate() == qd); for (i = 0, end = d->mRDateTimes.count(); i < end && !recurs; ++i) { recurs = (d->mRDateTimes[i].toTimeZone(timeZone).date() == qd); } for (i = 0, end = d->mRRules.count(); i < end && !recurs; ++i) { recurs = d->mRRules[i]->recursOn(qd, timeZone); } // If the event wouldn't recur at all, simply return false, don't check ex* if (!recurs) { return false; } // Check if there are any times for this day excluded, either by exdate or exrule: bool exon = false; for (i = 0, end = d->mExDateTimes.count(); i < end && !exon; ++i) { exon = (d->mExDateTimes[i].toTimeZone(timeZone).date() == qd); } if (!allDay()) { // we have already checked all-day times above for (i = 0, end = d->mExRules.count(); i < end && !exon; ++i) { exon = d->mExRules[i]->recursOn(qd, timeZone); } } if (!exon) { // Simple case, nothing on that day excluded, return the value from before return recurs; } else { // Harder part: I don't think there is any way other than to calculate the // whole list of items for that day. //TODO: consider whether it would be more efficient to call // Rule::recurTimesOn() instead of Rule::recursOn() from the start TimeList timesForDay(recurTimesOn(qd, timeZone)); return !timesForDay.isEmpty(); } } bool Recurrence::recursAt(const QDateTime &dt) const { // Convert to recurrence's time zone for date comparisons, and for more efficient time comparisons const auto dtrecur = dt.toTimeZone(d->mStartDateTime.timeZone()); // if it's excluded anyway, don't bother to check if it recurs at all. if (d->mExDateTimes.containsSorted(dtrecur) || d->mExDates.containsSorted(dtrecur.date())) { return false; } int i, end; for (i = 0, end = d->mExRules.count(); i < end; ++i) { if (d->mExRules[i]->recursAt(dtrecur)) { return false; } } // Check explicit recurrences, then rrules. if (startDateTime() == dtrecur || d->mRDateTimes.containsSorted(dtrecur)) { return true; } for (i = 0, end = d->mRRules.count(); i < end; ++i) { if (d->mRRules[i]->recursAt(dtrecur)) { return true; } } return false; } /** Calculates the cumulative end of the whole recurrence (rdates and rrules). If any rrule is infinite, or the recurrence doesn't have any rrules or rdates, an invalid date is returned. */ QDateTime Recurrence::endDateTime() const { SortableList dts; dts << startDateTime(); if (!d->mRDates.isEmpty()) { dts << QDateTime(d->mRDates.last(), QTime(0, 0, 0), d->mStartDateTime.timeZone()); } if (!d->mRDateTimes.isEmpty()) { dts << d->mRDateTimes.last(); } for (int i = 0, end = d->mRRules.count(); i < end; ++i) { auto rl = d->mRRules[i]->endDt(); // if any of the rules is infinite, the whole recurrence is if (!rl.isValid()) { return QDateTime(); } dts << rl; } dts.sortUnique(); return dts.isEmpty() ? QDateTime() : dts.last(); } /** Calculates the cumulative end of the whole recurrence (rdates and rrules). If any rrule is infinite, or the recurrence doesn't have any rrules or rdates, an invalid date is returned. */ QDate Recurrence::endDate() const { QDateTime end(endDateTime()); return end.isValid() ? end.date() : QDate(); } void Recurrence::setEndDate(const QDate &date) { QDateTime dt(date, d->mStartDateTime.time(), d->mStartDateTime.timeZone()); if (allDay()) { dt.setTime(QTime(23, 59, 59)); } setEndDateTime(dt); } void Recurrence::setEndDateTime(const QDateTime &dateTime) { if (d->mRecurReadOnly) { return; } RecurrenceRule *rrule = defaultRRule(true); if (!rrule) { return; } // If the recurrence rule has a duration, and we're trying to set an invalid end date, // we have to skip setting it to avoid setting the field dirty. // The end date is already invalid since the duration is set and end date/duration // are mutually exclusive. // We can't use inequality check below, because endDt() also returns a valid date // for a duration (it is calculated from the duration). if (rrule->duration() > 0 && !dateTime.isValid()) { return; } if (dateTime != rrule->endDt()) { rrule->setEndDt(dateTime); updated(); } } int Recurrence::duration() const { RecurrenceRule *rrule = defaultRRuleConst(); return rrule ? rrule->duration() : 0; } int Recurrence::durationTo(const QDateTime &datetime) const { // Emulate old behavior: This is just an interface to the first rule! RecurrenceRule *rrule = defaultRRuleConst(); return rrule ? rrule->durationTo(datetime) : 0; } int Recurrence::durationTo(const QDate &date) const { return durationTo(QDateTime(date, QTime(23, 59, 59), d->mStartDateTime.timeZone())); } void Recurrence::setDuration(int duration) { if (d->mRecurReadOnly) { return; } RecurrenceRule *rrule = defaultRRule(true); if (!rrule) { return; } if (duration != rrule->duration()) { rrule->setDuration(duration); updated(); } } void Recurrence::shiftTimes(const QTimeZone &oldTz, const QTimeZone &newTz) { if (d->mRecurReadOnly) { return; } d->mStartDateTime = d->mStartDateTime.toTimeZone(oldTz); d->mStartDateTime.setTimeZone(newTz); int i, end; for (i = 0, end = d->mRDateTimes.count(); i < end; ++i) { d->mRDateTimes[i] = d->mRDateTimes[i].toTimeZone(oldTz); d->mRDateTimes[i].setTimeZone(newTz); } for (i = 0, end = d->mExDateTimes.count(); i < end; ++i) { d->mExDateTimes[i] = d->mExDateTimes[i].toTimeZone(oldTz); d->mExDateTimes[i].setTimeZone(newTz); } for (i = 0, end = d->mRRules.count(); i < end; ++i) { d->mRRules[i]->shiftTimes(oldTz, newTz); } for (i = 0, end = d->mExRules.count(); i < end; ++i) { d->mExRules[i]->shiftTimes(oldTz, newTz); } } void Recurrence::unsetRecurs() { if (d->mRecurReadOnly) { return; } qDeleteAll(d->mRRules); d->mRRules.clear(); updated(); } void Recurrence::clear() { if (d->mRecurReadOnly) { return; } qDeleteAll(d->mRRules); d->mRRules.clear(); qDeleteAll(d->mExRules); d->mExRules.clear(); d->mRDates.clear(); d->mRDateTimes.clear(); d->mExDates.clear(); d->mExDateTimes.clear(); d->mCachedType = rMax; updated(); } void Recurrence::setRecurReadOnly(bool readOnly) { d->mRecurReadOnly = readOnly; } bool Recurrence::recurReadOnly() const { return d->mRecurReadOnly; } QDate Recurrence::startDate() const { return d->mStartDateTime.date(); } void Recurrence::setStartDateTime(const QDateTime &start, bool isAllDay) { if (d->mRecurReadOnly) { return; } d->mStartDateTime = start; setAllDay(isAllDay); // set all RRULEs and EXRULEs int i, end; for (i = 0, end = d->mRRules.count(); i < end; ++i) { d->mRRules[i]->setStartDt(start); } for (i = 0, end = d->mExRules.count(); i < end; ++i) { d->mExRules[i]->setStartDt(start); } updated(); } int Recurrence::frequency() const { RecurrenceRule *rrule = defaultRRuleConst(); return rrule ? rrule->frequency() : 0; } // Emulate the old behaviour. Make this methods just an interface to the // first rrule void Recurrence::setFrequency(int freq) { if (d->mRecurReadOnly || freq <= 0) { return; } RecurrenceRule *rrule = defaultRRule(true); if (rrule) { rrule->setFrequency(freq); } updated(); } // WEEKLY int Recurrence::weekStart() const { RecurrenceRule *rrule = defaultRRuleConst(); return rrule ? rrule->weekStart() : 1; } // Emulate the old behavior QBitArray Recurrence::days() const { QBitArray days(7); days.fill(0); RecurrenceRule *rrule = defaultRRuleConst(); if (rrule) { QList bydays = rrule->byDays(); for (int i = 0; i < bydays.size(); ++i) { if (bydays.at(i).pos() == 0) { days.setBit(bydays.at(i).day() - 1); } } } return days; } // MONTHLY // Emulate the old behavior QList Recurrence::monthDays() const { RecurrenceRule *rrule = defaultRRuleConst(); if (rrule) { return rrule->byMonthDays(); } else { return QList(); } } // Emulate the old behavior QList Recurrence::monthPositions() const { RecurrenceRule *rrule = defaultRRuleConst(); return rrule ? rrule->byDays() : QList(); } // YEARLY QList Recurrence::yearDays() const { RecurrenceRule *rrule = defaultRRuleConst(); return rrule ? rrule->byYearDays() : QList(); } QList Recurrence::yearDates() const { return monthDays(); } QList Recurrence::yearMonths() const { RecurrenceRule *rrule = defaultRRuleConst(); return rrule ? rrule->byMonths() : QList(); } QList Recurrence::yearPositions() const { return monthPositions(); } RecurrenceRule *Recurrence::setNewRecurrenceType(RecurrenceRule::PeriodType type, int freq) { if (d->mRecurReadOnly || freq <= 0) { return nullptr; } // Ignore the call if nothing has change if (defaultRRuleConst() && defaultRRuleConst()->recurrenceType() == type && frequency() == freq) { return nullptr; } qDeleteAll(d->mRRules); d->mRRules.clear(); updated(); RecurrenceRule *rrule = defaultRRule(true); if (!rrule) { return nullptr; } rrule->setRecurrenceType(type); rrule->setFrequency(freq); rrule->setDuration(-1); return rrule; } void Recurrence::setMinutely(int _rFreq) { if (setNewRecurrenceType(RecurrenceRule::rMinutely, _rFreq)) { updated(); } } void Recurrence::setHourly(int _rFreq) { if (setNewRecurrenceType(RecurrenceRule::rHourly, _rFreq)) { updated(); } } void Recurrence::setDaily(int _rFreq) { if (setNewRecurrenceType(RecurrenceRule::rDaily, _rFreq)) { updated(); } } void Recurrence::setWeekly(int freq, int weekStart) { RecurrenceRule *rrule = setNewRecurrenceType(RecurrenceRule::rWeekly, freq); if (!rrule) { return; } rrule->setWeekStart(weekStart); updated(); } void Recurrence::setWeekly(int freq, const QBitArray &days, int weekStart) { setWeekly(freq, weekStart); addMonthlyPos(0, days); } void Recurrence::addWeeklyDays(const QBitArray &days) { addMonthlyPos(0, days); } void Recurrence::setMonthly(int freq) { if (setNewRecurrenceType(RecurrenceRule::rMonthly, freq)) { updated(); } } void Recurrence::addMonthlyPos(short pos, const QBitArray &days) { // Allow 53 for yearly! if (d->mRecurReadOnly || pos > 53 || pos < -53) { return; } RecurrenceRule *rrule = defaultRRule(false); if (!rrule) { return; } bool changed = false; QList positions = rrule->byDays(); for (int i = 0; i < 7; ++i) { if (days.testBit(i)) { RecurrenceRule::WDayPos p(pos, i + 1); if (!positions.contains(p)) { changed = true; positions.append(p); } } } if (changed) { rrule->setByDays(positions); updated(); } } void Recurrence::addMonthlyPos(short pos, ushort day) { // Allow 53 for yearly! if (d->mRecurReadOnly || pos > 53 || pos < -53) { return; } RecurrenceRule *rrule = defaultRRule(false); if (!rrule) { return; } QList positions = rrule->byDays(); RecurrenceRule::WDayPos p(pos, day); if (!positions.contains(p)) { positions.append(p); setMonthlyPos(positions); } } void Recurrence::setMonthlyPos(const QList &monthlyDays) { if (d->mRecurReadOnly) { return; } RecurrenceRule *rrule = defaultRRule(true); if (!rrule) { return; } //TODO: sort lists // the position inside the list has no meaning, so sort the list before testing if it changed if (monthlyDays != rrule->byDays()) { rrule->setByDays(monthlyDays); updated(); } } void Recurrence::addMonthlyDate(short day) { if (d->mRecurReadOnly || day > 31 || day < -31) { return; } RecurrenceRule *rrule = defaultRRule(true); if (!rrule) { return; } QList monthDays = rrule->byMonthDays(); if (!monthDays.contains(day)) { monthDays.append(day); setMonthlyDate(monthDays); } } void Recurrence::setMonthlyDate(const QList< int > &monthlyDays) { if (d->mRecurReadOnly) { return; } RecurrenceRule *rrule = defaultRRule(true); if (!rrule) { return; } SortableList mD(monthlyDays); SortableList rbD(rrule->byMonthDays()); mD.sortUnique(); rbD.sortUnique(); if (mD != rbD) { rrule->setByMonthDays(monthlyDays); updated(); } } void Recurrence::setYearly(int freq) { if (setNewRecurrenceType(RecurrenceRule::rYearly, freq)) { updated(); } } // Daynumber within year void Recurrence::addYearlyDay(int day) { RecurrenceRule *rrule = defaultRRule(false); // It must already exist! if (!rrule) { return; } QList days = rrule->byYearDays(); if (!days.contains(day)) { days << day; setYearlyDay(days); } } void Recurrence::setYearlyDay(const QList &days) { RecurrenceRule *rrule = defaultRRule(false); // It must already exist! if (!rrule) { return; } SortableList d(days); SortableList bYD(rrule->byYearDays()); d.sortUnique(); bYD.sortUnique(); if (d != bYD) { rrule->setByYearDays(days); updated(); } } // day part of date within year void Recurrence::addYearlyDate(int day) { addMonthlyDate(day); } void Recurrence::setYearlyDate(const QList &dates) { setMonthlyDate(dates); } // day part of date within year, given as position (n-th weekday) void Recurrence::addYearlyPos(short pos, const QBitArray &days) { addMonthlyPos(pos, days); } void Recurrence::setYearlyPos(const QList &days) { setMonthlyPos(days); } // month part of date within year void Recurrence::addYearlyMonth(short month) { if (d->mRecurReadOnly || month < 1 || month > 12) { return; } RecurrenceRule *rrule = defaultRRule(false); if (!rrule) { return; } QList months = rrule->byMonths(); if (!months.contains(month)) { months << month; setYearlyMonth(months); } } void Recurrence::setYearlyMonth(const QList &months) { if (d->mRecurReadOnly) { return; } RecurrenceRule *rrule = defaultRRule(false); if (!rrule) { return; } SortableList m(months); SortableList bM(rrule->byMonths()); m.sortUnique(); bM.sortUnique(); if (m != bM) { rrule->setByMonths(months); updated(); } } TimeList Recurrence::recurTimesOn(const QDate &date, const QTimeZone &timeZone) const { // qCDebug(KCALCORE_LOG) << "recurTimesOn(" << date << ")"; int i, end; TimeList times; // The whole day is excepted if (d->mExDates.containsSorted(date)) { return times; } // EXRULE takes precedence over RDATE entries, so for all-day events, // a matching excule also excludes the whole day automatically if (allDay()) { for (i = 0, end = d->mExRules.count(); i < end; ++i) { if (d->mExRules[i]->recursOn(date, timeZone)) { return times; } } } QDateTime dt = startDateTime().toTimeZone(timeZone); if (dt.date() == date) { times << dt.time(); } bool foundDate = false; for (i = 0, end = d->mRDateTimes.count(); i < end; ++i) { dt = d->mRDateTimes[i].toTimeZone(timeZone); if (dt.date() == date) { times << dt.time(); foundDate = true; } else if (foundDate) { break; // <= Assume that the rdatetime list is sorted } } for (i = 0, end = d->mRRules.count(); i < end; ++i) { times += d->mRRules[i]->recurTimesOn(date, timeZone); } times.sortUnique(); foundDate = false; TimeList extimes; for (i = 0, end = d->mExDateTimes.count(); i < end; ++i) { dt = d->mExDateTimes[i].toTimeZone(timeZone); if (dt.date() == date) { extimes << dt.time(); foundDate = true; } else if (foundDate) { break; } } if (!allDay()) { // we have already checked all-day times above for (i = 0, end = d->mExRules.count(); i < end; ++i) { extimes += d->mExRules[i]->recurTimesOn(date, timeZone); } } extimes.sortUnique(); int st = 0; for (i = 0, end = extimes.count(); i < end; ++i) { int j = times.removeSorted(extimes[i], st); if (j >= 0) { st = j; } } return times; } SortableList Recurrence::timesInInterval(const QDateTime &start, const QDateTime &end) const { int i, count; SortableList times; for (i = 0, count = d->mRRules.count(); i < count; ++i) { times += d->mRRules[i]->timesInInterval(start, end); } // add rdatetimes that fit in the interval for (i = 0, count = d->mRDateTimes.count(); i < count; ++i) { if (d->mRDateTimes[i] >= start && d->mRDateTimes[i] <= end) { times += d->mRDateTimes[i]; } } // add rdates that fit in the interval QDateTime kdt = d->mStartDateTime; for (i = 0, count = d->mRDates.count(); i < count; ++i) { kdt.setDate(d->mRDates[i]); if (kdt >= start && kdt <= end) { times += kdt; } } // Recurrence::timesInInterval(...) doesn't explicitly add mStartDateTime to the list // of times to be returned. It calls mRRules[i]->timesInInterval(...) which include // mStartDateTime. // So, If we have rdates/rdatetimes but don't have any rrule we must explicitly // add mStartDateTime to the list, otherwise we won't see the first occurrence. if ((!d->mRDates.isEmpty() || !d->mRDateTimes.isEmpty()) && d->mRRules.isEmpty() && start <= d->mStartDateTime && end >= d->mStartDateTime) { times += d->mStartDateTime; } times.sortUnique(); // Remove excluded times int idt = 0; int enddt = times.count(); for (i = 0, count = d->mExDates.count(); i < count && idt < enddt; ++i) { while (idt < enddt && times[idt].date() < d->mExDates[i]) { ++idt; } while (idt < enddt && times[idt].date() == d->mExDates[i]) { times.removeAt(idt); --enddt; } } SortableList extimes; for (i = 0, count = d->mExRules.count(); i < count; ++i) { extimes += d->mExRules[i]->timesInInterval(start, end); } extimes += d->mExDateTimes; extimes.sortUnique(); int st = 0; for (i = 0, count = extimes.count(); i < count; ++i) { int j = times.removeSorted(extimes[i], st); if (j >= 0) { st = j; } } return times; } QDateTime Recurrence::getNextDateTime(const QDateTime &preDateTime) const { QDateTime nextDT = preDateTime; // prevent infinite loops, e.g. when an exrule extinguishes an rrule (e.g. // the exrule is identical to the rrule). If an occurrence is found, break // out of the loop by returning that QDateTime // TODO_Recurrence: Is a loop counter of 1000 really okay? I mean for secondly // recurrence, an exdate might exclude more than 1000 intervals! int loop = 0; while (loop < 1000) { // Outline of the algo: // 1) Find the next date/time after preDateTime when the event could recur // 1.0) Add the start date if it's after preDateTime // 1.1) Use the next occurrence from the explicit RDATE lists // 1.2) Add the next recurrence for each of the RRULEs - // 2) Take the earliest recurrence of these = KDateTime nextDT + // 2) Take the earliest recurrence of these = QDateTime nextDT // 3) If that date/time is not excluded, either explicitly by an EXDATE or // by an EXRULE, return nextDT as the next date/time of the recurrence // 4) If it's excluded, start all at 1), but starting at nextDT (instead // of preDateTime). Loop at most 1000 times. ++loop; // First, get the next recurrence from the RDate lists SortableList dates; if (nextDT < startDateTime()) { dates << startDateTime(); } int end; // Assume that the rdatetime list is sorted int i = d->mRDateTimes.findGT(nextDT); if (i >= 0) { dates << d->mRDateTimes[i]; } QDateTime kdt(startDateTime()); for (i = 0, end = d->mRDates.count(); i < end; ++i) { kdt.setDate(d->mRDates[i]); if (kdt > nextDT) { dates << kdt; break; } } // Add the next occurrences from all RRULEs. for (i = 0, end = d->mRRules.count(); i < end; ++i) { QDateTime dt = d->mRRules[i]->getNextDate(nextDT); if (dt.isValid()) { dates << dt; } } // Take the first of these (all others can't be used later on) dates.sortUnique(); if (dates.isEmpty()) { return QDateTime(); } nextDT = dates.first(); // Check if that date/time is excluded explicitly or by an exrule: if (!d->mExDates.containsSorted(nextDT.date()) && !d->mExDateTimes.containsSorted(nextDT)) { bool allowed = true; for (i = 0, end = d->mExRules.count(); i < end; ++i) { allowed = allowed && !(d->mExRules[i]->recursAt(nextDT)); } if (allowed) { return nextDT; } } } // Couldn't find a valid occurrences in 1000 loops, something is wrong! return QDateTime(); } QDateTime Recurrence::getPreviousDateTime(const QDateTime &afterDateTime) const { QDateTime prevDT = afterDateTime; // prevent infinite loops, e.g. when an exrule extinguishes an rrule (e.g. // the exrule is identical to the rrule). If an occurrence is found, break - // out of the loop by returning that KDateTime + // out of the loop by returning that QDateTime int loop = 0; while (loop < 1000) { // Outline of the algo: // 1) Find the next date/time after preDateTime when the event could recur // 1.1) Use the next occurrence from the explicit RDATE lists // 1.2) Add the next recurrence for each of the RRULEs - // 2) Take the earliest recurrence of these = KDateTime nextDT + // 2) Take the earliest recurrence of these = QDateTime nextDT // 3) If that date/time is not excluded, either explicitly by an EXDATE or // by an EXRULE, return nextDT as the next date/time of the recurrence // 4) If it's excluded, start all at 1), but starting at nextDT (instead // of preDateTime). Loop at most 1000 times. ++loop; // First, get the next recurrence from the RDate lists SortableList dates; if (prevDT > startDateTime()) { dates << startDateTime(); } int i = d->mRDateTimes.findLT(prevDT); if (i >= 0) { dates << d->mRDateTimes[i]; } QDateTime kdt(startDateTime()); for (i = d->mRDates.count(); --i >= 0;) { kdt.setDate(d->mRDates[i]); if (kdt < prevDT) { dates << kdt; break; } } // Add the previous occurrences from all RRULEs. int end; for (i = 0, end = d->mRRules.count(); i < end; ++i) { QDateTime dt = d->mRRules[i]->getPreviousDate(prevDT); if (dt.isValid()) { dates << dt; } } // Take the last of these (all others can't be used later on) dates.sortUnique(); if (dates.isEmpty()) { return QDateTime(); } prevDT = dates.last(); // Check if that date/time is excluded explicitly or by an exrule: if (!d->mExDates.containsSorted(prevDT.date()) && !d->mExDateTimes.containsSorted(prevDT)) { bool allowed = true; for (i = 0, end = d->mExRules.count(); i < end; ++i) { allowed = allowed && !(d->mExRules[i]->recursAt(prevDT)); } if (allowed) { return prevDT; } } } // Couldn't find a valid occurrences in 1000 loops, something is wrong! return QDateTime(); } /***************************** PROTECTED FUNCTIONS ***************************/ RecurrenceRule::List Recurrence::rRules() const { return d->mRRules; } void Recurrence::addRRule(RecurrenceRule *rrule) { if (d->mRecurReadOnly || !rrule) { return; } rrule->setAllDay(d->mAllDay); d->mRRules.append(rrule); rrule->addObserver(this); updated(); } void Recurrence::removeRRule(RecurrenceRule *rrule) { if (d->mRecurReadOnly) { return; } d->mRRules.removeAll(rrule); rrule->removeObserver(this); updated(); } void Recurrence::deleteRRule(RecurrenceRule *rrule) { if (d->mRecurReadOnly) { return; } d->mRRules.removeAll(rrule); delete rrule; updated(); } RecurrenceRule::List Recurrence::exRules() const { return d->mExRules; } void Recurrence::addExRule(RecurrenceRule *exrule) { if (d->mRecurReadOnly || !exrule) { return; } exrule->setAllDay(d->mAllDay); d->mExRules.append(exrule); exrule->addObserver(this); updated(); } void Recurrence::removeExRule(RecurrenceRule *exrule) { if (d->mRecurReadOnly) { return; } d->mExRules.removeAll(exrule); exrule->removeObserver(this); updated(); } void Recurrence::deleteExRule(RecurrenceRule *exrule) { if (d->mRecurReadOnly) { return; } d->mExRules.removeAll(exrule); delete exrule; updated(); } SortableList Recurrence::rDateTimes() const { return d->mRDateTimes; } void Recurrence::setRDateTimes(const SortableList &rdates) { if (d->mRecurReadOnly) { return; } d->mRDateTimes = rdates; d->mRDateTimes.sortUnique(); updated(); } void Recurrence::addRDateTime(const QDateTime &rdate) { if (d->mRecurReadOnly) { return; } d->mRDateTimes.insertSorted(rdate); updated(); } DateList Recurrence::rDates() const { return d->mRDates; } void Recurrence::setRDates(const DateList &rdates) { if (d->mRecurReadOnly) { return; } d->mRDates = rdates; d->mRDates.sortUnique(); updated(); } void Recurrence::addRDate(const QDate &rdate) { if (d->mRecurReadOnly) { return; } d->mRDates.insertSorted(rdate); updated(); } SortableList Recurrence::exDateTimes() const { return d->mExDateTimes; } void Recurrence::setExDateTimes(const SortableList &exdates) { if (d->mRecurReadOnly) { return; } d->mExDateTimes = exdates; d->mExDateTimes.sortUnique(); } void Recurrence::addExDateTime(const QDateTime &exdate) { if (d->mRecurReadOnly) { return; } d->mExDateTimes.insertSorted(exdate); updated(); } DateList Recurrence::exDates() const { return d->mExDates; } void Recurrence::setExDates(const DateList &exdates) { if (d->mRecurReadOnly) { return; } DateList l = exdates; l.sortUnique(); if (d->mExDates != l) { d->mExDates = l; updated(); } } void Recurrence::addExDate(const QDate &exdate) { if (d->mRecurReadOnly) { return; } d->mExDates.insertSorted(exdate); updated(); } void Recurrence::recurrenceChanged(RecurrenceRule *) { updated(); } // %%%%%%%%%%%%%%%%%% end:Recurrencerule %%%%%%%%%%%%%%%%%% void Recurrence::dump() const { qCDebug(KCALCORE_LOG); int i; int count = d->mRRules.count(); qCDebug(KCALCORE_LOG) << " -)" << count << "RRULEs:"; for (i = 0; i < count; ++i) { qCDebug(KCALCORE_LOG) << " -) RecurrenceRule: "; d->mRRules[i]->dump(); } count = d->mExRules.count(); qCDebug(KCALCORE_LOG) << " -)" << count << "EXRULEs:"; for (i = 0; i < count; ++i) { qCDebug(KCALCORE_LOG) << " -) ExceptionRule :"; d->mExRules[i]->dump(); } count = d->mRDates.count(); qCDebug(KCALCORE_LOG) << " -)" << count << "Recurrence Dates:"; for (i = 0; i < count; ++i) { qCDebug(KCALCORE_LOG) << " " << d->mRDates[i]; } count = d->mRDateTimes.count(); qCDebug(KCALCORE_LOG) << " -)" << count << "Recurrence Date/Times:"; for (i = 0; i < count; ++i) { qCDebug(KCALCORE_LOG) << " " << d->mRDateTimes[i]; } count = d->mExDates.count(); qCDebug(KCALCORE_LOG) << " -)" << count << "Exceptions Dates:"; for (i = 0; i < count; ++i) { qCDebug(KCALCORE_LOG) << " " << d->mExDates[i]; } count = d->mExDateTimes.count(); qCDebug(KCALCORE_LOG) << " -)" << count << "Exception Date/Times:"; for (i = 0; i < count; ++i) { qCDebug(KCALCORE_LOG) << " " << d->mExDateTimes[i]; } } Recurrence::RecurrenceObserver::~RecurrenceObserver() { } KCALCORE_EXPORT QDataStream &KCalCore::operator<<(QDataStream &out, KCalCore::Recurrence *r) { if (!r) { return out; } serializeQDateTimeSortableList(out, r->d->mRDateTimes); serializeQDateTimeSortableList(out, r->d->mExDateTimes); out << r->d->mRDates; serializeQDateTimeAsKDateTime(out, r->d->mStartDateTime); out << r->d->mCachedType << r->d->mAllDay << r->d->mRecurReadOnly << r->d->mExDates << r->d->mExRules.count() << r->d->mRRules.count(); for (RecurrenceRule *rule : qAsConst(r->d->mExRules)) { out << rule; } for (RecurrenceRule *rule : qAsConst(r->d->mRRules)) { out << rule; } return out; } KCALCORE_EXPORT QDataStream &KCalCore::operator>>(QDataStream &in, KCalCore::Recurrence *r) { if (!r) { return in; } int rruleCount, exruleCount; deserializeQDateTimeSortableList(in, r->d->mRDateTimes); deserializeQDateTimeSortableList(in, r->d->mExDateTimes); in >> r->d->mRDates; deserializeKDateTimeAsQDateTime(in, r->d->mStartDateTime); in >> r->d->mCachedType >> r->d->mAllDay >> r->d->mRecurReadOnly >> r->d->mExDates >> exruleCount >> rruleCount; r->d->mExRules.clear(); r->d->mRRules.clear(); for (int i = 0; i < exruleCount; ++i) { RecurrenceRule *rule = new RecurrenceRule(); rule->addObserver(r); in >> rule; r->d->mExRules.append(rule); } for (int i = 0; i < rruleCount; ++i) { RecurrenceRule *rule = new RecurrenceRule(); rule->addObserver(r); in >> rule; r->d->mRRules.append(rule); } return in; } diff --git a/src/recurrencerule.cpp b/src/recurrencerule.cpp index de82bc77c..6e4b036a5 100644 --- a/src/recurrencerule.cpp +++ b/src/recurrencerule.cpp @@ -1,2327 +1,2327 @@ /* This file is part of the kcalcore library. Copyright (c) 2005 Reinhold Kainhofer Copyright (c) 2006-2008 David Jarvie This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "recurrencerule.h" #include "utils.h" #include "kcalcore_debug.h" #include "utils.h" #include #include #include #include #include using namespace KCalCore; // Maximum number of intervals to process const int LOOP_LIMIT = 10000; #ifndef NDEBUG static QString dumpTime(const QDateTime &dt, bool allDay); // for debugging #endif /*========================================================================= = = = IMPORTANT CODING NOTE: = = = = Recurrence handling code is time critical, especially for sub-daily = = recurrences. For example, if getNextDate() is called repeatedly to = = check all consecutive occurrences over a few years, on a slow machine = = this could take many seconds to complete in the worst case. Simple = = sub-daily recurrences are optimised by use of mTimedRepetition. = = = ==========================================================================*/ /************************************************************************** * DateHelper * **************************************************************************/ //@cond PRIVATE class DateHelper { public: #ifndef NDEBUG static QString dayName(short day); #endif static QDate getNthWeek(int year, int weeknumber, short weekstart = 1); static int weekNumbersInYear(int year, short weekstart = 1); static int getWeekNumber(const QDate &date, short weekstart, int *year = nullptr); static int getWeekNumberNeg(const QDate &date, short weekstart, int *year = nullptr); // Convert to QDate, allowing for day < 0. // month and day must be non-zero. static QDate getDate(int year, int month, int day) { if (day >= 0) { return QDate(year, month, day); } else { if (++month > 12) { month = 1; ++year; } return QDate(year, month, 1).addDays(day); } } }; #ifndef NDEBUG // TODO: Move to a general library / class, as we need the same in the iCal // generator and in the xcal format QString DateHelper::dayName(short day) { switch (day) { case 1: return QStringLiteral("MO"); case 2: return QStringLiteral("TU"); case 3: return QStringLiteral("WE"); case 4: return QStringLiteral("TH"); case 5: return QStringLiteral("FR"); case 6: return QStringLiteral("SA"); case 7: return QStringLiteral("SU"); default: return QStringLiteral("??"); } } #endif QDate DateHelper::getNthWeek(int year, int weeknumber, short weekstart) { if (weeknumber == 0) { return QDate(); } // Adjust this to the first day of week #1 of the year and add 7*weekno days. QDate dt(year, 1, 4); // Week #1 is the week that contains Jan 4 int adjust = -(7 + dt.dayOfWeek() - weekstart) % 7; if (weeknumber > 0) { dt = dt.addDays(7 * (weeknumber - 1) + adjust); } else if (weeknumber < 0) { dt = dt.addYears(1); dt = dt.addDays(7 * weeknumber + adjust); } return dt; } int DateHelper::getWeekNumber(const QDate &date, short weekstart, int *year) { int y = date.year(); QDate dt(y, 1, 4); // <= definitely in week #1 dt = dt.addDays(-(7 + dt.dayOfWeek() - weekstart) % 7); // begin of week #1 int daysto = dt.daysTo(date); if (daysto < 0) { // in first week of year --y; dt = QDate(y, 1, 4); dt = dt.addDays(-(7 + dt.dayOfWeek() - weekstart) % 7); // begin of week #1 daysto = dt.daysTo(date); } else if (daysto > 355) { // near the end of the year - check if it's next year QDate dtn(y + 1, 1, 4); // <= definitely first week of next year dtn = dtn.addDays(-(7 + dtn.dayOfWeek() - weekstart) % 7); int dayston = dtn.daysTo(date); if (dayston >= 0) { // in first week of next year; ++y; daysto = dayston; } } if (year) { *year = y; } return daysto / 7 + 1; } int DateHelper::weekNumbersInYear(int year, short weekstart) { QDate dt(year, 1, weekstart); QDate dt1(year + 1, 1, weekstart); return dt.daysTo(dt1) / 7; } // Week number from the end of the year int DateHelper::getWeekNumberNeg(const QDate &date, short weekstart, int *year) { int weekpos = getWeekNumber(date, weekstart, year); return weekNumbersInYear(*year, weekstart) - weekpos - 1; } //@endcond /************************************************************************** * WDayPos * **************************************************************************/ bool RecurrenceRule::WDayPos::operator==(const RecurrenceRule::WDayPos &pos2) const { return mDay == pos2.mDay && mPos == pos2.mPos; } bool RecurrenceRule::WDayPos::operator!=(const RecurrenceRule::WDayPos &pos2) const { return !operator==(pos2); } /************************************************************************** * Constraint * **************************************************************************/ //@cond PRIVATE class Constraint { public: typedef QVector List; Constraint() {} explicit Constraint(const QTimeZone &, int wkst = 1); Constraint(const QDateTime &dt, RecurrenceRule::PeriodType type, int wkst); void clear(); void setYear(int n) { year = n; useCachedDt = false; } void setMonth(int n) { month = n; useCachedDt = false; } void setDay(int n) { day = n; useCachedDt = false; } void setHour(int n) { hour = n; useCachedDt = false; } void setMinute(int n) { minute = n; useCachedDt = false; } void setSecond(int n) { second = n; useCachedDt = false; } void setWeekday(int n) { weekday = n; useCachedDt = false; } void setWeekdaynr(int n) { weekdaynr = n; useCachedDt = false; } void setWeeknumber(int n) { weeknumber = n; useCachedDt = false; } void setYearday(int n) { yearday = n; useCachedDt = false; } void setWeekstart(int n) { weekstart = n; useCachedDt = false; } int year; // 0 means unspecified int month; // 0 means unspecified int day; // 0 means unspecified int hour; // -1 means unspecified int minute; // -1 means unspecified int second; // -1 means unspecified int weekday; // 0 means unspecified int weekdaynr; // index of weekday in month/year (0=unspecified) int weeknumber; // 0 means unspecified int yearday; // 0 means unspecified int weekstart; // first day of week (1=monday, 7=sunday, 0=unspec.) QTimeZone timeZone; // time zone etc. to use bool readDateTime(const QDateTime &dt, RecurrenceRule::PeriodType type); bool matches(const QDate &dt, RecurrenceRule::PeriodType type) const; bool matches(const QDateTime &dt, RecurrenceRule::PeriodType type) const; bool merge(const Constraint &interval); bool isConsistent(RecurrenceRule::PeriodType period) const; bool increase(RecurrenceRule::PeriodType type, int freq); QDateTime intervalDateTime(RecurrenceRule::PeriodType type) const; QList dateTimes(RecurrenceRule::PeriodType type) const; void appendDateTime(const QDate &date, const QTime &time, QList &list) const; void dump() const; private: mutable bool useCachedDt; mutable QDateTime cachedDt; }; Constraint::Constraint(const QTimeZone &timeZone, int wkst) : weekstart(wkst), timeZone(timeZone) { clear(); } Constraint::Constraint(const QDateTime &dt, RecurrenceRule::PeriodType type, int wkst) : weekstart(wkst), timeZone(dt.timeZone()) { clear(); readDateTime(dt, type); } void Constraint::clear() { year = 0; month = 0; day = 0; hour = -1; minute = -1; second = -1; weekday = 0; weekdaynr = 0; weeknumber = 0; yearday = 0; useCachedDt = false; } bool Constraint::matches(const QDate &dt, RecurrenceRule::PeriodType type) const { // If the event recurs in week 53 or 1, the day might not belong to the same // year as the week it is in. E.g. Jan 1, 2005 is in week 53 of year 2004. // So we can't simply check the year in that case! if (weeknumber == 0) { if (year > 0 && year != dt.year()) { return false; } } else { int y; if (weeknumber > 0 && weeknumber != DateHelper::getWeekNumber(dt, weekstart, &y)) { return false; } if (weeknumber < 0 && weeknumber != DateHelper::getWeekNumberNeg(dt, weekstart, &y)) { return false; } if (year > 0 && year != y) { return false; } } if (month > 0 && month != dt.month()) { return false; } if (day > 0 && day != dt.day()) { return false; } if (day < 0 && dt.day() != (dt.daysInMonth() + day + 1)) { return false; } if (weekday > 0) { if (weekday != dt.dayOfWeek()) { return false; } if (weekdaynr != 0) { // If it's a yearly recurrence and a month is given, the position is // still in the month, not in the year. if ((type == RecurrenceRule::rMonthly) || (type == RecurrenceRule::rYearly && month > 0)) { // Monthly if (weekdaynr > 0 && weekdaynr != (dt.day() - 1) / 7 + 1) { return false; } if (weekdaynr < 0 && weekdaynr != -((dt.daysInMonth() - dt.day()) / 7 + 1)) { return false; } } else { // Yearly if (weekdaynr > 0 && weekdaynr != (dt.dayOfYear() - 1) / 7 + 1) { return false; } if (weekdaynr < 0 && weekdaynr != -((dt.daysInYear() - dt.dayOfYear()) / 7 + 1)) { return false; } } } } if (yearday > 0 && yearday != dt.dayOfYear()) { return false; } if (yearday < 0 && yearday != dt.daysInYear() - dt.dayOfYear() + 1) { return false; } return true; } /* Check for a match with the specified date/time. * The date/time's time specification must correspond with that of the start date/time. */ bool Constraint::matches(const QDateTime &dt, RecurrenceRule::PeriodType type) const { if ((hour >= 0 && hour != dt.time().hour()) || (minute >= 0 && minute != dt.time().minute()) || (second >= 0 && second != dt.time().second()) || !matches(dt.date(), type)) { return false; } return true; } bool Constraint::isConsistent(RecurrenceRule::PeriodType /*period*/) const { // TODO: Check for consistency, e.g. byyearday=3 and bymonth=10 return true; } // Return a date/time set to the constraint values, but with those parts less // significant than the given period type set to 1 (for dates) or 0 (for times). QDateTime Constraint::intervalDateTime(RecurrenceRule::PeriodType type) const { if (useCachedDt) { return cachedDt; } QDate d; QTime t(0, 0, 0); bool subdaily = true; switch (type) { case RecurrenceRule::rSecondly: t.setHMS(hour, minute, second); break; case RecurrenceRule::rMinutely: t.setHMS(hour, minute, 0); break; case RecurrenceRule::rHourly: t.setHMS(hour, 0, 0); break; case RecurrenceRule::rDaily: break; case RecurrenceRule::rWeekly: d = DateHelper::getNthWeek(year, weeknumber, weekstart); subdaily = false; break; case RecurrenceRule::rMonthly: d.setDate(year, month, 1); subdaily = false; break; case RecurrenceRule::rYearly: d.setDate(year, 1, 1); subdaily = false; break; default: break; } if (subdaily) { d = DateHelper::getDate(year, (month > 0) ? month : 1, day ? day : 1); } cachedDt = QDateTime(d, t, timeZone); useCachedDt = true; return cachedDt; } bool Constraint::merge(const Constraint &interval) { #define mergeConstraint( name, cmparison ) \ if ( interval.name cmparison ) { \ if ( !( name cmparison ) ) { \ name = interval.name; \ } else if ( name != interval.name ) { \ return false;\ } \ } useCachedDt = false; mergeConstraint(year, > 0); mergeConstraint(month, > 0); mergeConstraint(day, != 0); mergeConstraint(hour, >= 0); mergeConstraint(minute, >= 0); mergeConstraint(second, >= 0); mergeConstraint(weekday, != 0); mergeConstraint(weekdaynr, != 0); mergeConstraint(weeknumber, != 0); mergeConstraint(yearday, != 0); #undef mergeConstraint return true; } // Y M D | H Mn S | WD #WD | WN | YD // required: // x | x x x | | | // 0) Trivial: Exact date given, maybe other restrictions // x x x | x x x | | | // 1) Easy case: no weekly restrictions -> at most a loop through possible dates // x + + | x x x | - - | - | - // 2) Year day is given -> date known // x | x x x | | | + // 3) week number is given -> loop through all days of that week. Further // restrictions will be applied in the end, when we check all dates for // consistency with the constraints // x | x x x | | + | (-) // 4) week day is specified -> // x | x x x | x ? | (-)| (-) // 5) All possiblecases have already been treated, so this must be an error! QList Constraint::dateTimes(RecurrenceRule::PeriodType type) const { QList result; bool done = false; if (!isConsistent(type)) { return result; } // TODO_Recurrence: Handle all-day QTime tm(hour, minute, second); if (!done && day && month > 0) { appendDateTime(DateHelper::getDate(year, month, day), tm, result); done = true; } if (!done && weekday == 0 && weeknumber == 0 && yearday == 0) { // Easy case: date is given, not restrictions by week or yearday uint mstart = (month > 0) ? month : 1; uint mend = (month <= 0) ? 12 : month; for (uint m = mstart; m <= mend; ++m) { uint dstart, dend; if (day > 0) { dstart = dend = day; } else if (day < 0) { QDate date(year, month, 1); dstart = dend = date.daysInMonth() + day + 1; } else { QDate date(year, month, 1); dstart = 1; dend = date.daysInMonth(); } uint d = dstart; for (QDate dt(year, m, dstart);; dt = dt.addDays(1)) { appendDateTime(dt, tm, result); if (++d > dend) { break; } } } done = true; } // Else: At least one of the week / yearday restrictions was given... // If we have a yearday (and of course a year), we know the exact date if (!done && yearday != 0) { // yearday < 0 means from end of year, so we'll need Jan 1 of the next year QDate d(year + ((yearday > 0) ? 0 : 1), 1, 1); d = d.addDays(yearday - ((yearday > 0) ? 1 : 0)); appendDateTime(d, tm, result); done = true; } // Else: If we have a weeknumber, we have at most 7 possible dates, loop through them if (!done && weeknumber != 0) { QDate wst(DateHelper::getNthWeek(year, weeknumber, weekstart)); if (weekday != 0) { wst = wst.addDays((7 + weekday - weekstart) % 7); appendDateTime(wst, tm, result); } else { for (int i = 0; i < 7; ++i) { appendDateTime(wst, tm, result); wst = wst.addDays(1); } } done = true; } // weekday is given if (!done && weekday != 0) { QDate dt(year, 1, 1); // If type == yearly and month is given, pos is still in month not year! // TODO_Recurrence: Correct handling of n-th BYDAY... int maxloop = 53; bool inMonth = (type == RecurrenceRule::rMonthly) || (type == RecurrenceRule::rYearly && month > 0); if (inMonth && month > 0) { dt = QDate(year, month, 1); maxloop = 5; } if (weekdaynr < 0) { // From end of period (month, year) => relative to begin of next period if (inMonth) { dt = dt.addMonths(1); } else { dt = dt.addYears(1); } } int adj = (7 + weekday - dt.dayOfWeek()) % 7; dt = dt.addDays(adj); // correct first weekday of the period if (weekdaynr > 0) { dt = dt.addDays((weekdaynr - 1) * 7); appendDateTime(dt, tm, result); } else if (weekdaynr < 0) { dt = dt.addDays(weekdaynr * 7); appendDateTime(dt, tm, result); } else { // loop through all possible weeks, non-matching will be filtered later for (int i = 0; i < maxloop; ++i) { appendDateTime(dt, tm, result); dt = dt.addDays(7); } } } // weekday != 0 // Only use those times that really match all other constraints, too QList valid; for (int i = 0, iend = result.count(); i < iend; ++i) { if (matches(result[i], type)) { valid.append(result[i]); } } // Don't sort it here, would be unnecessary work. The results from all // constraints will be merged to one big list of the interval. Sort that one! return valid; } void Constraint::appendDateTime(const QDate &date, const QTime &time, QList &list) const { QDateTime dt(date, time, timeZone); if (dt.isValid()) { list.append(dt); } } bool Constraint::increase(RecurrenceRule::PeriodType type, int freq) { - // convert the first day of the interval to KDateTime + // convert the first day of the interval to QDateTime intervalDateTime(type); // Now add the intervals switch (type) { case RecurrenceRule::rSecondly: cachedDt = cachedDt.addSecs(freq); break; case RecurrenceRule::rMinutely: cachedDt = cachedDt.addSecs(60 * freq); break; case RecurrenceRule::rHourly: cachedDt = cachedDt.addSecs(3600 * freq); break; case RecurrenceRule::rDaily: cachedDt = cachedDt.addDays(freq); break; case RecurrenceRule::rWeekly: cachedDt = cachedDt.addDays(7 * freq); break; case RecurrenceRule::rMonthly: cachedDt = cachedDt.addMonths(freq); break; case RecurrenceRule::rYearly: cachedDt = cachedDt.addYears(freq); break; default: break; } - // Convert back from KDateTime to the Constraint class + // Convert back from QDateTime to the Constraint class readDateTime(cachedDt, type); useCachedDt = true; // readDateTime() resets this return true; } // Set the constraint's value appropriate to 'type', to the value contained in a date/time. bool Constraint::readDateTime(const QDateTime &dt, RecurrenceRule::PeriodType type) { switch (type) { // Really fall through! Only weekly needs to be treated differently! case RecurrenceRule::rSecondly: second = dt.time().second(); case RecurrenceRule::rMinutely: minute = dt.time().minute(); case RecurrenceRule::rHourly: hour = dt.time().hour(); case RecurrenceRule::rDaily: day = dt.date().day(); case RecurrenceRule::rMonthly: month = dt.date().month(); case RecurrenceRule::rYearly: year = dt.date().year(); break; case RecurrenceRule::rWeekly: // Determine start day of the current week, calculate the week number from that weeknumber = DateHelper::getWeekNumber(dt.date(), weekstart, &year); break; default: break; } useCachedDt = false; return true; } //@endcond /************************************************************************** * RecurrenceRule::Private * **************************************************************************/ //@cond PRIVATE class Q_DECL_HIDDEN KCalCore::RecurrenceRule::Private { public: Private(RecurrenceRule *parent) : mParent(parent), mPeriod(rNone), mFrequency(0), mDuration(-1), mWeekStart(1), mIsReadOnly(false), mAllDay(false) { setDirty(); } Private(RecurrenceRule *parent, const Private &p); Private &operator=(const Private &other); bool operator==(const Private &other) const; void clear(); void setDirty(); void buildConstraints(); bool buildCache() const; Constraint getNextValidDateInterval(const QDateTime &preDate, PeriodType type) const; Constraint getPreviousValidDateInterval(const QDateTime &afterDate, PeriodType type) const; SortableList datesForInterval(const Constraint &interval, PeriodType type) const; RecurrenceRule *mParent; QString mRRule; // RRULE string PeriodType mPeriod; QDateTime mDateStart; // start of recurrence (but mDateStart is not an occurrence // unless it matches the rule) uint mFrequency; /** how often it recurs: < 0 means no end date, 0 means an explicit end date, positive values give the number of occurrences */ int mDuration; QDateTime mDateEnd; QList mBySeconds; // values: second 0-59 QList mByMinutes; // values: minute 0-59 QList mByHours; // values: hour 0-23 QList mByDays; // n-th weekday of the month or year QList mByMonthDays; // values: day -31 to -1 and 1-31 QList mByYearDays; // values: day -366 to -1 and 1-366 QList mByWeekNumbers; // values: week -53 to -1 and 1-53 QList mByMonths; // values: month 1-12 QList mBySetPos; // values: position -366 to -1 and 1-366 short mWeekStart; // first day of the week (1=Monday, 7=Sunday) Constraint::List mConstraints; QList mObservers; // Cache for duration mutable SortableList mCachedDates; mutable QDateTime mCachedDateEnd; mutable QDateTime mCachedLastDate; // when mCachedDateEnd invalid, last date checked mutable bool mCached; bool mIsReadOnly; bool mAllDay; bool mNoByRules; // no BySeconds, ByMinutes, ... rules exist uint mTimedRepetition; // repeats at a regular number of seconds interval, or 0 }; RecurrenceRule::Private::Private(RecurrenceRule *parent, const Private &p) : mParent(parent), mRRule(p.mRRule), mPeriod(p.mPeriod), mDateStart(p.mDateStart), mFrequency(p.mFrequency), mDuration(p.mDuration), mDateEnd(p.mDateEnd), mBySeconds(p.mBySeconds), mByMinutes(p.mByMinutes), mByHours(p.mByHours), mByDays(p.mByDays), mByMonthDays(p.mByMonthDays), mByYearDays(p.mByYearDays), mByWeekNumbers(p.mByWeekNumbers), mByMonths(p.mByMonths), mBySetPos(p.mBySetPos), mWeekStart(p.mWeekStart), mIsReadOnly(p.mIsReadOnly), mAllDay(p.mAllDay), mNoByRules(p.mNoByRules) { setDirty(); } RecurrenceRule::Private &RecurrenceRule::Private::operator=(const Private &p) { // check for self assignment if (&p == this) { return *this; } mRRule = p.mRRule; mPeriod = p.mPeriod; mDateStart = p.mDateStart; mFrequency = p.mFrequency; mDuration = p.mDuration; mDateEnd = p.mDateEnd; mBySeconds = p.mBySeconds; mByMinutes = p.mByMinutes; mByHours = p.mByHours; mByDays = p.mByDays; mByMonthDays = p.mByMonthDays; mByYearDays = p.mByYearDays; mByWeekNumbers = p.mByWeekNumbers; mByMonths = p.mByMonths; mBySetPos = p.mBySetPos; mWeekStart = p.mWeekStart; mIsReadOnly = p.mIsReadOnly; mAllDay = p.mAllDay; mNoByRules = p.mNoByRules; setDirty(); return *this; } bool RecurrenceRule::Private::operator==(const Private &r) const { return mPeriod == r.mPeriod && ((mDateStart == r.mDateStart) || (!mDateStart.isValid() && !r.mDateStart.isValid())) && mDuration == r.mDuration && ((mDateEnd == r.mDateEnd) || (!mDateEnd.isValid() && !r.mDateEnd.isValid())) && mFrequency == r.mFrequency && mIsReadOnly == r.mIsReadOnly && mAllDay == r.mAllDay && mBySeconds == r.mBySeconds && mByMinutes == r.mByMinutes && mByHours == r.mByHours && mByDays == r.mByDays && mByMonthDays == r.mByMonthDays && mByYearDays == r.mByYearDays && mByWeekNumbers == r.mByWeekNumbers && mByMonths == r.mByMonths && mBySetPos == r.mBySetPos && mWeekStart == r.mWeekStart && mNoByRules == r.mNoByRules; } void RecurrenceRule::Private::clear() { if (mIsReadOnly) { return; } mPeriod = rNone; mBySeconds.clear(); mByMinutes.clear(); mByHours.clear(); mByDays.clear(); mByMonthDays.clear(); mByYearDays.clear(); mByWeekNumbers.clear(); mByMonths.clear(); mBySetPos.clear(); mWeekStart = 1; mNoByRules = false; setDirty(); } void RecurrenceRule::Private::setDirty() { buildConstraints(); mCached = false; mCachedDates.clear(); for (int i = 0, iend = mObservers.count(); i < iend; ++i) { if (mObservers[i]) { mObservers[i]->recurrenceChanged(mParent); } } } //@endcond /************************************************************************** * RecurrenceRule * **************************************************************************/ RecurrenceRule::RecurrenceRule() : d(new Private(this)) { } RecurrenceRule::RecurrenceRule(const RecurrenceRule &r) : d(new Private(this, *r.d)) { } RecurrenceRule::~RecurrenceRule() { delete d; } bool RecurrenceRule::operator==(const RecurrenceRule &r) const { return *d == *r.d; } RecurrenceRule &RecurrenceRule::operator=(const RecurrenceRule &r) { // check for self assignment if (&r == this) { return *this; } *d = *r.d; return *this; } void RecurrenceRule::addObserver(RuleObserver *observer) { if (!d->mObservers.contains(observer)) { d->mObservers.append(observer); } } void RecurrenceRule::removeObserver(RuleObserver *observer) { d->mObservers.removeAll(observer); } void RecurrenceRule::setRecurrenceType(PeriodType period) { if (isReadOnly()) { return; } d->mPeriod = period; d->setDirty(); } QDateTime RecurrenceRule::endDt(bool *result) const { if (result) { *result = false; } if (d->mPeriod == rNone) { return QDateTime(); } if (d->mDuration < 0) { return QDateTime(); } if (d->mDuration == 0) { if (result) { *result = true; } return d->mDateEnd; } // N occurrences. Check if we have a full cache. If so, return the cached end date. if (!d->mCached) { // If not enough occurrences can be found (i.e. inconsistent constraints) if (!d->buildCache()) { return QDateTime(); } } if (result) { *result = true; } return d->mCachedDateEnd; } void RecurrenceRule::setEndDt(const QDateTime &dateTime) { if (isReadOnly()) { return; } d->mDateEnd = dateTime; if (d->mDateEnd.isValid()) { d->mDuration = 0; // set to 0 because there is an end date/time } d->setDirty(); } void RecurrenceRule::setDuration(int duration) { if (isReadOnly()) { return; } d->mDuration = duration; d->setDirty(); } void RecurrenceRule::setAllDay(bool allDay) { if (isReadOnly()) { return; } d->mAllDay = allDay; d->setDirty(); } void RecurrenceRule::clear() { d->clear(); } void RecurrenceRule::setDirty() { d->setDirty(); } void RecurrenceRule::setStartDt(const QDateTime &start) { if (isReadOnly()) { return; } d->mDateStart = start; d->setDirty(); } void RecurrenceRule::setFrequency(int freq) { if (isReadOnly() || freq <= 0) { return; } d->mFrequency = freq; d->setDirty(); } void RecurrenceRule::setBySeconds(const QList &bySeconds) { if (isReadOnly()) { return; } d->mBySeconds = bySeconds; d->setDirty(); } void RecurrenceRule::setByMinutes(const QList &byMinutes) { if (isReadOnly()) { return; } d->mByMinutes = byMinutes; d->setDirty(); } void RecurrenceRule::setByHours(const QList &byHours) { if (isReadOnly()) { return; } d->mByHours = byHours; d->setDirty(); } void RecurrenceRule::setByDays(const QList &byDays) { if (isReadOnly()) { return; } d->mByDays = byDays; d->setDirty(); } void RecurrenceRule::setByMonthDays(const QList &byMonthDays) { if (isReadOnly()) { return; } d->mByMonthDays = byMonthDays; d->setDirty(); } void RecurrenceRule::setByYearDays(const QList &byYearDays) { if (isReadOnly()) { return; } d->mByYearDays = byYearDays; d->setDirty(); } void RecurrenceRule::setByWeekNumbers(const QList &byWeekNumbers) { if (isReadOnly()) { return; } d->mByWeekNumbers = byWeekNumbers; d->setDirty(); } void RecurrenceRule::setByMonths(const QList &byMonths) { if (isReadOnly()) { return; } d->mByMonths = byMonths; d->setDirty(); } void RecurrenceRule::setBySetPos(const QList &bySetPos) { if (isReadOnly()) { return; } d->mBySetPos = bySetPos; d->setDirty(); } void RecurrenceRule::setWeekStart(short weekStart) { if (isReadOnly()) { return; } d->mWeekStart = weekStart; d->setDirty(); } void RecurrenceRule::shiftTimes(const QTimeZone &oldTz, const QTimeZone &newTz) { d->mDateStart = d->mDateStart.toTimeZone(oldTz); d->mDateStart.setTimeZone(newTz); if (d->mDuration == 0) { d->mDateEnd = d->mDateEnd.toTimeZone(oldTz); d->mDateEnd.setTimeZone(newTz); } d->setDirty(); } // Taken from recurrence.cpp // int RecurrenceRule::maxIterations() const // { // /* Find the maximum number of iterations which may be needed to reach the // * next actual occurrence of a monthly or yearly recurrence. // * More than one iteration may be needed if, for example, it's the 29th February, // * the 31st day of the month or the 5th Monday, and the month being checked is // * February or a 30-day month. // * The following recurrences may never occur: // * - For rMonthlyDay: if the frequency is a whole number of years. // * - For rMonthlyPos: if the frequency is an even whole number of years. // * - For rYearlyDay, rYearlyMonth: if the frequeny is a multiple of 4 years. // * - For rYearlyPos: if the frequency is an even number of years. // * The maximum number of iterations needed, assuming that it does actually occur, // * was found empirically. // */ // switch (recurs) { // case rMonthlyDay: // return (rFreq % 12) ? 6 : 8; // // case rMonthlyPos: // if (rFreq % 12 == 0) { // // Some of these frequencies may never occur // return (rFreq % 84 == 0) ? 364 // frequency = multiple of 7 years // : (rFreq % 48 == 0) ? 7 // frequency = multiple of 4 years // : (rFreq % 24 == 0) ? 14 : 28; // frequency = multiple of 2 or 1 year // } // // All other frequencies will occur sometime // if (rFreq > 120) // return 364; // frequencies of > 10 years will hit the date limit first // switch (rFreq) { // case 23: return 50; // case 46: return 38; // case 56: return 138; // case 66: return 36; // case 89: return 54; // case 112: return 253; // default: return 25; // most frequencies will need < 25 iterations // } // // case rYearlyMonth: // case rYearlyDay: // return 8; // only 29th Feb or day 366 will need more than one iteration // // case rYearlyPos: // if (rFreq % 7 == 0) // return 364; // frequencies of a multiple of 7 years will hit the date limit first // if (rFreq % 2 == 0) { // // Some of these frequencies may never occur // return (rFreq % 4 == 0) ? 7 : 14; // frequency = even number of years // } // return 28; // } // return 1; // } //@cond PRIVATE void RecurrenceRule::Private::buildConstraints() { mTimedRepetition = 0; mNoByRules = mBySetPos.isEmpty(); mConstraints.clear(); Constraint con(mDateStart.timeZone()); if (mWeekStart > 0) { con.setWeekstart(mWeekStart); } mConstraints.append(con); int c, cend; int i, iend; Constraint::List tmp; #define intConstraint( list, setElement ) \ if ( !list.isEmpty() ) { \ mNoByRules = false; \ iend = list.count(); \ if ( iend == 1 ) { \ for ( c = 0, cend = mConstraints.count(); c < cend; ++c ) { \ mConstraints[c].setElement( list[0] ); \ } \ } else { \ tmp.reserve(mConstraints.count() * iend); \ for ( c = 0, cend = mConstraints.count(); c < cend; ++c ) { \ for ( i = 0; i < iend; ++i ) { \ con = mConstraints[c]; \ con.setElement( list[i] ); \ tmp.append( con ); \ } \ } \ mConstraints = tmp; \ tmp.clear(); \ } \ } intConstraint(mBySeconds, setSecond); intConstraint(mByMinutes, setMinute); intConstraint(mByHours, setHour); intConstraint(mByMonthDays, setDay); intConstraint(mByMonths, setMonth); intConstraint(mByYearDays, setYearday); intConstraint(mByWeekNumbers, setWeeknumber); #undef intConstraint if (!mByDays.isEmpty()) { mNoByRules = false; tmp.reserve(mConstraints.count() * mByDays.count()); for (c = 0, cend = mConstraints.count(); c < cend; ++c) { for (i = 0, iend = mByDays.count(); i < iend; ++i) { con = mConstraints[c]; con.setWeekday(mByDays[i].day()); con.setWeekdaynr(mByDays[i].pos()); tmp.append(con); } } mConstraints = tmp; tmp.clear(); } #define fixConstraint( setElement, value ) \ { \ for ( c = 0, cend = mConstraints.count(); c < cend; ++c ) { \ mConstraints[c].setElement( value ); \ } \ } // Now determine missing values from DTSTART. This can speed up things, // because we have more restrictions and save some loops. // TODO: Does RFC 2445 intend to restrict the weekday in all cases of weekly? if (mPeriod == rWeekly && mByDays.isEmpty()) { fixConstraint(setWeekday, mDateStart.date().dayOfWeek()); } // Really fall through in the cases, because all smaller time intervals are // constrained from dtstart switch (mPeriod) { case rYearly: if (mByDays.isEmpty() && mByWeekNumbers.isEmpty() && mByYearDays.isEmpty() && mByMonths.isEmpty()) { fixConstraint(setMonth, mDateStart.date().month()); } case rMonthly: if (mByDays.isEmpty() && mByWeekNumbers.isEmpty() && mByYearDays.isEmpty() && mByMonthDays.isEmpty()) { fixConstraint(setDay, mDateStart.date().day()); } case rWeekly: case rDaily: if (mByHours.isEmpty()) { fixConstraint(setHour, mDateStart.time().hour()); } case rHourly: if (mByMinutes.isEmpty()) { fixConstraint(setMinute, mDateStart.time().minute()); } case rMinutely: if (mBySeconds.isEmpty()) { fixConstraint(setSecond, mDateStart.time().second()); } case rSecondly: default: break; } #undef fixConstraint if (mNoByRules) { switch (mPeriod) { case rHourly: mTimedRepetition = mFrequency * 3600; break; case rMinutely: mTimedRepetition = mFrequency * 60; break; case rSecondly: mTimedRepetition = mFrequency; break; default: break; } } else { for (c = 0, cend = mConstraints.count(); c < cend;) { if (mConstraints[c].isConsistent(mPeriod)) { ++c; } else { mConstraints.removeAt(c); --cend; } } } } // Build and cache a list of all occurrences. // Only call buildCache() if mDuration > 0. bool RecurrenceRule::Private::buildCache() const { Q_ASSERT(mDuration > 0); // Build the list of all occurrences of this event (we need that to determine // the end date!) Constraint interval(getNextValidDateInterval(mDateStart, mPeriod)); auto dts = datesForInterval(interval, mPeriod); // Only use dates after the event has started (start date is only included // if it matches) int i = dts.findLT(mDateStart); if (i >= 0) { dts.erase(dts.begin(), dts.begin() + i + 1); } // some validity checks to avoid infinite loops (i.e. if we have // done this loop already 10000 times, bail out ) for (int loopnr = 0; loopnr < LOOP_LIMIT && dts.count() < mDuration; ++loopnr) { interval.increase(mPeriod, mFrequency); // The returned date list is already sorted! dts += datesForInterval(interval, mPeriod); } if (dts.count() > mDuration) { // we have picked up more occurrences than necessary, remove them dts.erase(dts.begin() + mDuration, dts.end()); } mCached = true; mCachedDates = dts; // it = dts.begin(); // while ( it != dts.end() ) { // qCDebug(KCALCORE_LOG) << " -=>" << dumpTime(*it); // ++it; // } if (int(dts.count()) == mDuration) { mCachedDateEnd = dts.last(); return true; } else { // The cached date list is incomplete mCachedDateEnd = QDateTime(); mCachedLastDate = interval.intervalDateTime(mPeriod); return false; } } //@endcond bool RecurrenceRule::dateMatchesRules(const QDateTime &kdt) const { QDateTime dt = kdt.toTimeZone(d->mDateStart.timeZone()); for (int i = 0, iend = d->mConstraints.count(); i < iend; ++i) { if (d->mConstraints[i].matches(dt, recurrenceType())) { return true; } } return false; } bool RecurrenceRule::recursOn(const QDate &qd, const QTimeZone &timeZone) const { int i, iend; if (!qd.isValid() || !d->mDateStart.isValid()) { // There can't be recurrences on invalid dates return false; } if (allDay()) { // It's a date-only rule, so it has no time specification. // Therefore ignore 'timeSpec'. if (qd < d->mDateStart.date()) { return false; } // Start date is only included if it really matches QDate endDate; if (d->mDuration >= 0) { endDate = endDt().date(); if (qd > endDate) { return false; } } // The date must be in an appropriate interval (getNextValidDateInterval), // Plus it must match at least one of the constraints bool match = false; for (i = 0, iend = d->mConstraints.count(); i < iend && !match; ++i) { match = d->mConstraints[i].matches(qd, recurrenceType()); } if (!match) { return false; } QDateTime start(qd, QTime(0, 0, 0), timeZone); //d->mDateStart.timeZone()); Constraint interval(d->getNextValidDateInterval(start, recurrenceType())); // Constraint::matches is quite efficient, so first check if it can occur at // all before we calculate all actual dates. if (!interval.matches(qd, recurrenceType())) { return false; } // We really need to obtain the list of dates in this interval, since // otherwise BYSETPOS will not work (i.e. the date will match the interval, // but BYSETPOS selects only one of these matching dates! QDateTime end = start.addDays(1); do { auto dts = d->datesForInterval(interval, recurrenceType()); for (i = 0, iend = dts.count(); i < iend; ++i) { if (dts[i].date() >= qd) { return dts[i].date() == qd; } } interval.increase(recurrenceType(), frequency()); } while (interval.intervalDateTime(recurrenceType()) < end); return false; } // It's a date-time rule, so we need to take the time specification into account. QDateTime start(qd, QTime(0, 0, 0), timeZone); QDateTime end = start.addDays(1).toTimeZone(d->mDateStart.timeZone()); start = start.toTimeZone(d->mDateStart.timeZone()); if (end < d->mDateStart) { return false; } if (start < d->mDateStart) { start = d->mDateStart; } // Start date is only included if it really matches if (d->mDuration >= 0) { QDateTime endRecur = endDt(); if (endRecur.isValid()) { if (start > endRecur) { return false; } if (end > endRecur) { end = endRecur; // limit end-of-day time to end of recurrence rule } } } if (d->mTimedRepetition) { // It's a simple sub-daily recurrence with no constraints int n = static_cast((d->mDateStart.secsTo(start) - 1) % d->mTimedRepetition); return start.addSecs(d->mTimedRepetition - n) < end; } // Find the start and end dates in the time spec for the rule QDate startDay = start.date(); QDate endDay = end.addSecs(-1).date(); int dayCount = startDay.daysTo(endDay) + 1; // The date must be in an appropriate interval (getNextValidDateInterval), // Plus it must match at least one of the constraints bool match = false; for (i = 0, iend = d->mConstraints.count(); i < iend && !match; ++i) { match = d->mConstraints[i].matches(startDay, recurrenceType()); for (int day = 1; day < dayCount && !match; ++day) { match = d->mConstraints[i].matches(startDay.addDays(day), recurrenceType()); } } if (!match) { return false; } Constraint interval(d->getNextValidDateInterval(start, recurrenceType())); // Constraint::matches is quite efficient, so first check if it can occur at // all before we calculate all actual dates. match = false; Constraint intervalm = interval; do { match = intervalm.matches(startDay, recurrenceType()); for (int day = 1; day < dayCount && !match; ++day) { match = intervalm.matches(startDay.addDays(day), recurrenceType()); } if (match) { break; } intervalm.increase(recurrenceType(), frequency()); } while (intervalm.intervalDateTime(recurrenceType()).isValid() && intervalm.intervalDateTime(recurrenceType()) < end); if (!match) { return false; } // We really need to obtain the list of dates in this interval, since // otherwise BYSETPOS will not work (i.e. the date will match the interval, // but BYSETPOS selects only one of these matching dates! do { auto dts = d->datesForInterval(interval, recurrenceType()); int i = dts.findGE(start); if (i >= 0) { return dts[i] <= end; } interval.increase(recurrenceType(), frequency()); } while (interval.intervalDateTime(recurrenceType()).isValid() && interval.intervalDateTime(recurrenceType()) < end); return false; } bool RecurrenceRule::recursAt(const QDateTime &kdt) const { // Convert to the time spec used by this recurrence rule QDateTime dt(kdt.toTimeZone(d->mDateStart.timeZone())); if (allDay()) { return recursOn(dt.date(), dt.timeZone()); } if (dt < d->mDateStart) { return false; } // Start date is only included if it really matches if (d->mDuration >= 0 && dt > endDt()) { return false; } if (d->mTimedRepetition) { // It's a simple sub-daily recurrence with no constraints return !(d->mDateStart.secsTo(dt) % d->mTimedRepetition); } // The date must be in an appropriate interval (getNextValidDateInterval), // Plus it must match at least one of the constraints if (!dateMatchesRules(dt)) { return false; } // if it recurs every interval, speed things up... // if ( d->mFrequency == 1 && d->mBySetPos.isEmpty() && d->mByDays.isEmpty() ) return true; Constraint interval(d->getNextValidDateInterval(dt, recurrenceType())); // TODO_Recurrence: Does this work with BySetPos??? if (interval.matches(dt, recurrenceType())) { return true; } return false; } TimeList RecurrenceRule::recurTimesOn(const QDate &date, const QTimeZone &timeZone) const { TimeList lst; if (allDay()) { return lst; } QDateTime start(date, QTime(0, 0, 0), timeZone); QDateTime end = start.addDays(1).addSecs(-1); auto dts = timesInInterval(start, end); // returns between start and end inclusive for (int i = 0, iend = dts.count(); i < iend; ++i) { lst += dts[i].toTimeZone(timeZone).time(); } return lst; } /** Returns the number of recurrences up to and including the date/time specified. */ int RecurrenceRule::durationTo(const QDateTime &dt) const { // Convert to the time spec used by this recurrence rule QDateTime toDate(dt.toTimeZone(d->mDateStart.timeZone())); // Easy cases: // either before start, or after all recurrences and we know their number if (toDate < d->mDateStart) { return 0; } // Start date is only included if it really matches if (d->mDuration > 0 && toDate >= endDt()) { return d->mDuration; } if (d->mTimedRepetition) { // It's a simple sub-daily recurrence with no constraints return static_cast(d->mDateStart.secsTo(toDate) / d->mTimedRepetition); } return timesInInterval(d->mDateStart, toDate).count(); } int RecurrenceRule::durationTo(const QDate &date) const { return durationTo(QDateTime(date, QTime(23, 59, 59), d->mDateStart.timeZone())); } QDateTime RecurrenceRule::getPreviousDate(const QDateTime &afterDate) const { // Convert to the time spec used by this recurrence rule QDateTime toDate(afterDate.toTimeZone(d->mDateStart.timeZone())); // Invalid starting point, or beyond end of recurrence if (!toDate.isValid() || toDate < d->mDateStart) { return QDateTime(); } if (d->mTimedRepetition) { // It's a simple sub-daily recurrence with no constraints QDateTime prev = toDate; if (d->mDuration >= 0 && endDt().isValid() && toDate > endDt()) { prev = endDt().addSecs(1).toTimeZone(d->mDateStart.timeZone()); } int n = static_cast((d->mDateStart.secsTo(prev) - 1) % d->mTimedRepetition); if (n < 0) { return QDateTime(); // before recurrence start } prev = prev.addSecs(-n - 1); return prev >= d->mDateStart ? prev : QDateTime(); } // If we have a cache (duration given), use that if (d->mDuration > 0) { if (!d->mCached) { d->buildCache(); } int i = d->mCachedDates.findLT(toDate); if (i >= 0) { return d->mCachedDates[i]; } return QDateTime(); } QDateTime prev = toDate; if (d->mDuration >= 0 && endDt().isValid() && toDate > endDt()) { prev = endDt().addSecs(1).toTimeZone(d->mDateStart.timeZone()); } Constraint interval(d->getPreviousValidDateInterval(prev, recurrenceType())); auto dts = d->datesForInterval(interval, recurrenceType()); int i = dts.findLT(prev); if (i >= 0) { return (dts[i] >= d->mDateStart) ? dts[i] : QDateTime(); } // Previous interval. As soon as we find an occurrence, we're done. while (interval.intervalDateTime(recurrenceType()) > d->mDateStart) { interval.increase(recurrenceType(), -int(frequency())); // The returned date list is sorted auto dts = d->datesForInterval(interval, recurrenceType()); // The list is sorted, so take the last one. if (!dts.isEmpty()) { prev = dts.last(); if (prev.isValid() && prev >= d->mDateStart) { return prev; } else { return QDateTime(); } } } return QDateTime(); } QDateTime RecurrenceRule::getNextDate(const QDateTime &preDate) const { // Convert to the time spec used by this recurrence rule QDateTime fromDate(preDate.toTimeZone(d->mDateStart.timeZone())); // Beyond end of recurrence if (d->mDuration >= 0 && endDt().isValid() && fromDate >= endDt()) { return QDateTime(); } // Start date is only included if it really matches if (fromDate < d->mDateStart) { fromDate = d->mDateStart.addSecs(-1); } if (d->mTimedRepetition) { // It's a simple sub-daily recurrence with no constraints int n = static_cast((d->mDateStart.secsTo(fromDate) + 1) % d->mTimedRepetition); QDateTime next = fromDate.addSecs(d->mTimedRepetition - n + 1); return d->mDuration < 0 || !endDt().isValid() || next <= endDt() ? next : QDateTime(); } if (d->mDuration > 0) { if (!d->mCached) { d->buildCache(); } int i = d->mCachedDates.findGT(fromDate); if (i >= 0) { return d->mCachedDates[i]; } } QDateTime end = endDt(); Constraint interval(d->getNextValidDateInterval(fromDate, recurrenceType())); auto dts = d->datesForInterval(interval, recurrenceType()); int i = dts.findGT(fromDate); if (i >= 0) { return (d->mDuration < 0 || dts[i] <= end) ? dts[i] : QDateTime(); } interval.increase(recurrenceType(), frequency()); if (d->mDuration >= 0 && interval.intervalDateTime(recurrenceType()) > end) { return QDateTime(); } // Increase the interval. The first occurrence that we find is the result (if // if's before the end date). // TODO: some validity checks to avoid infinite loops for contradictory constraints int loop = 0; do { auto dts = d->datesForInterval(interval, recurrenceType()); if (!dts.isEmpty()) { QDateTime ret(dts[0]); if (d->mDuration >= 0 && ret > end) { return QDateTime(); } else { return ret; } } interval.increase(recurrenceType(), frequency()); } while (++loop < LOOP_LIMIT && (d->mDuration < 0 || interval.intervalDateTime(recurrenceType()) < end)); return QDateTime(); } SortableList RecurrenceRule::timesInInterval(const QDateTime &dtStart, const QDateTime &dtEnd) const { const QDateTime start = dtStart.toTimeZone(d->mDateStart.timeZone()); const QDateTime end = dtEnd.toTimeZone(d->mDateStart.timeZone()); SortableList result; if (end < d->mDateStart) { return result; // before start of recurrence } QDateTime enddt = end; if (d->mDuration >= 0) { const QDateTime endRecur = endDt(); if (endRecur.isValid()) { if (start > endRecur) { return result; // beyond end of recurrence } if (end >= endRecur) { enddt = endRecur; // limit end time to end of recurrence rule } } } if (d->mTimedRepetition) { // It's a simple sub-daily recurrence with no constraints //Seconds to add to interval start, to get first occurrence which is within interval qint64 offsetFromNextOccurrence; if (d->mDateStart < start) { offsetFromNextOccurrence = d->mTimedRepetition - (d->mDateStart.secsTo(start) % d->mTimedRepetition); } else { offsetFromNextOccurrence = -(d->mDateStart.secsTo(start) % d->mTimedRepetition); } QDateTime dt = start.addSecs(offsetFromNextOccurrence); if (dt <= enddt) { int numberOfOccurrencesWithinInterval = static_cast(dt.secsTo(enddt) / d->mTimedRepetition) + 1; // limit n by a sane value else we can "explode". numberOfOccurrencesWithinInterval = qMin(numberOfOccurrencesWithinInterval, LOOP_LIMIT); for (int i = 0; i < numberOfOccurrencesWithinInterval; dt = dt.addSecs(d->mTimedRepetition), ++i) { result += dt; } } return result; } QDateTime st = start; bool done = false; if (d->mDuration > 0) { if (!d->mCached) { d->buildCache(); } if (d->mCachedDateEnd.isValid() && start > d->mCachedDateEnd) { return result; // beyond end of recurrence } int i = d->mCachedDates.findGE(start); if (i >= 0) { int iend = d->mCachedDates.findGT(enddt, i); if (iend < 0) { iend = d->mCachedDates.count(); } else { done = true; } while (i < iend) { result += d->mCachedDates[i++]; } } if (d->mCachedDateEnd.isValid()) { done = true; } else if (!result.isEmpty()) { result += QDateTime(); // indicate that the returned list is incomplete done = true; } if (done) { return result; } // We don't have any result yet, but we reached the end of the incomplete cache st = d->mCachedLastDate.addSecs(1); } Constraint interval(d->getNextValidDateInterval(st, recurrenceType())); int loop = 0; do { auto dts = d->datesForInterval(interval, recurrenceType()); int i = 0; int iend = dts.count(); if (loop == 0) { i = dts.findGE(st); if (i < 0) { i = iend; } } int j = dts.findGT(enddt, i); if (j >= 0) { iend = j; loop = LOOP_LIMIT; } while (i < iend) { result += dts[i++]; } // Increase the interval. interval.increase(recurrenceType(), frequency()); } while (++loop < LOOP_LIMIT && interval.intervalDateTime(recurrenceType()) < end); return result; } //@cond PRIVATE // Find the date/time of the occurrence at or before a date/time, // for a given period type. // Return a constraint whose value appropriate to 'type', is set to // the value contained in the date/time. Constraint RecurrenceRule::Private::getPreviousValidDateInterval(const QDateTime &dt, PeriodType type) const { long periods = 0; QDateTime start = mDateStart; QDateTime nextValid(start); int modifier = 1; QDateTime toDate(dt.toTimeZone(start.timeZone())); // for super-daily recurrences, don't care about the time part // Find the #intervals since the dtstart and round to the next multiple of // the frequency switch (type) { // Really fall through for sub-daily, since the calculations only differ // by the factor 60 and 60*60! Same for weekly and daily (factor 7) case rHourly: modifier *= 60; case rMinutely: modifier *= 60; case rSecondly: periods = static_cast(start.secsTo(toDate) / modifier); // round it down to the next lower multiple of frequency: if (mFrequency > 0) { periods = (periods / mFrequency) * mFrequency; } nextValid = start.addSecs(modifier * periods); break; case rWeekly: toDate = toDate.addDays(-(7 + toDate.date().dayOfWeek() - mWeekStart) % 7); start = start.addDays(-(7 + start.date().dayOfWeek() - mWeekStart) % 7); modifier *= 7; case rDaily: periods = start.daysTo(toDate) / modifier; // round it down to the next lower multiple of frequency: if (mFrequency > 0) { periods = (periods / mFrequency) * mFrequency; } nextValid = start.addDays(modifier * periods); break; case rMonthly: { periods = 12 * (toDate.date().year() - start.date().year()) + (toDate.date().month() - start.date().month()); // round it down to the next lower multiple of frequency: if (mFrequency > 0) { periods = (periods / mFrequency) * mFrequency; } // set the day to the first day of the month, so we don't have problems // with non-existent days like Feb 30 or April 31 start.setDate(QDate(start.date().year(), start.date().month(), 1)); nextValid.setDate(start.date().addMonths(periods)); break; } case rYearly: periods = (toDate.date().year() - start.date().year()); // round it down to the next lower multiple of frequency: if (mFrequency > 0) { periods = (periods / mFrequency) * mFrequency; } nextValid.setDate(start.date().addYears(periods)); break; default: break; } return Constraint(nextValid, type, mWeekStart); } // Find the date/time of the next occurrence at or after a date/time, // for a given period type. // Return a constraint whose value appropriate to 'type', is set to the // value contained in the date/time. Constraint RecurrenceRule::Private::getNextValidDateInterval(const QDateTime &dt, PeriodType type) const { // TODO: Simplify this! long periods = 0; QDateTime start = mDateStart; QDateTime nextValid(start); int modifier = 1; QDateTime toDate(dt.toTimeZone(start.timeZone())); // for super-daily recurrences, don't care about the time part // Find the #intervals since the dtstart and round to the next multiple of // the frequency switch (type) { // Really fall through for sub-daily, since the calculations only differ // by the factor 60 and 60*60! Same for weekly and daily (factor 7) case rHourly: modifier *= 60; case rMinutely: modifier *= 60; case rSecondly: periods = static_cast(start.secsTo(toDate) / modifier); periods = qMax(0L, periods); if (periods > 0 && mFrequency > 0) { periods += (mFrequency - 1 - ((periods - 1) % mFrequency)); } nextValid = start.addSecs(modifier * periods); break; case rWeekly: // correct both start date and current date to start of week toDate = toDate.addDays(-(7 + toDate.date().dayOfWeek() - mWeekStart) % 7); start = start.addDays(-(7 + start.date().dayOfWeek() - mWeekStart) % 7); modifier *= 7; case rDaily: periods = start.daysTo(toDate) / modifier; periods = qMax(0L, periods); if (periods > 0 && mFrequency > 0) { periods += (mFrequency - 1 - ((periods - 1) % mFrequency)); } nextValid = start.addDays(modifier * periods); break; case rMonthly: { periods = 12 * (toDate.date().year() - start.date().year()) + (toDate.date().month() - start.date().month()); periods = qMax(0L, periods); if (periods > 0 && mFrequency > 0) { periods += (mFrequency - 1 - ((periods - 1) % mFrequency)); } // set the day to the first day of the month, so we don't have problems // with non-existent days like Feb 30 or April 31 start.setDate(QDate(start.date().year(), start.date().month(), 1)); nextValid.setDate(start.date().addMonths(periods)); break; } case rYearly: periods = (toDate.date().year() - start.date().year()); periods = qMax(0L, periods); if (periods > 0 && mFrequency > 0) { periods += (mFrequency - 1 - ((periods - 1) % mFrequency)); } nextValid.setDate(start.date().addYears(periods)); break; default: break; } return Constraint(nextValid, type, mWeekStart); } SortableList RecurrenceRule::Private::datesForInterval(const Constraint &interval, PeriodType type) const { /* -) Loop through constraints, -) merge interval with each constraint -) if merged constraint is not consistent => ignore that constraint -) if complete => add that one date to the date list -) Loop through all missing fields => For each add the resulting */ SortableList lst; for (int i = 0, iend = mConstraints.count(); i < iend; ++i) { Constraint merged(interval); if (merged.merge(mConstraints[i])) { // If the information is incomplete, we can't use this constraint if (merged.year > 0 && merged.hour >= 0 && merged.minute >= 0 && merged.second >= 0) { // We have a valid constraint, so get all datetimes that match it andd // append it to all date/times of this interval QList lstnew = merged.dateTimes(type); lst += lstnew; } } } // Sort it so we can apply the BySetPos. Also some logic relies on this being sorted lst.sortUnique(); /*if ( lst.isEmpty() ) { qCDebug(KCALCORE_LOG) << " No Dates in Interval"; } else { qCDebug(KCALCORE_LOG) << " Dates:"; for ( int i = 0, iend = lst.count(); i < iend; ++i ) { qCDebug(KCALCORE_LOG)<< " -)" << dumpTime(lst[i]); } qCDebug(KCALCORE_LOG) << " ---------------------"; }*/ if (!mBySetPos.isEmpty()) { auto tmplst = lst; lst.clear(); for (int i = 0, iend = mBySetPos.count(); i < iend; ++i) { int pos = mBySetPos[i]; if (pos > 0) { --pos; } if (pos < 0) { pos += tmplst.count(); } if (pos >= 0 && pos < tmplst.count()) { lst.append(tmplst[pos]); } } lst.sortUnique(); } return lst; } //@endcond void RecurrenceRule::dump() const { #ifndef NDEBUG qCDebug(KCALCORE_LOG); if (!d->mRRule.isEmpty()) { qCDebug(KCALCORE_LOG) << " RRULE=" << d->mRRule; } qCDebug(KCALCORE_LOG) << " Read-Only:" << isReadOnly(); qCDebug(KCALCORE_LOG) << " Period type:" << int(recurrenceType()) << ", frequency:" << frequency(); qCDebug(KCALCORE_LOG) << " #occurrences:" << duration(); qCDebug(KCALCORE_LOG) << " start date:" << dumpTime(startDt(), allDay()) << ", end date:" << dumpTime(endDt(), allDay()); #define dumpByIntList(list,label) \ if ( !list.isEmpty() ) {\ QStringList lst;\ for ( int i = 0, iend = list.count(); i < iend; ++i ) {\ lst.append( QString::number( list[i] ) );\ }\ qCDebug(KCALCORE_LOG) << " " << label << lst.join( QStringLiteral(", ") );\ } dumpByIntList(d->mBySeconds, QStringLiteral("BySeconds: ")); dumpByIntList(d->mByMinutes, QStringLiteral("ByMinutes: ")); dumpByIntList(d->mByHours, QStringLiteral("ByHours: ")); if (!d->mByDays.isEmpty()) { QStringList lst; for (int i = 0, iend = d->mByDays.count(); i < iend; ++i) { \ lst.append((d->mByDays[i].pos() ? QString::number(d->mByDays[i].pos()) : QStringLiteral("")) + DateHelper::dayName(d->mByDays[i].day())); } qCDebug(KCALCORE_LOG) << " ByDays: " << lst.join(QStringLiteral(", ")); } dumpByIntList(d->mByMonthDays, QStringLiteral("ByMonthDays:")); dumpByIntList(d->mByYearDays, QStringLiteral("ByYearDays: ")); dumpByIntList(d->mByWeekNumbers, QStringLiteral("ByWeekNr: ")); dumpByIntList(d->mByMonths, QStringLiteral("ByMonths: ")); dumpByIntList(d->mBySetPos, QStringLiteral("BySetPos: ")); #undef dumpByIntList qCDebug(KCALCORE_LOG) << " Week start:" << DateHelper::dayName(d->mWeekStart); qCDebug(KCALCORE_LOG) << " Constraints:"; // dump constraints for (int i = 0, iend = d->mConstraints.count(); i < iend; ++i) { d->mConstraints[i].dump(); } #endif } //@cond PRIVATE void Constraint::dump() const { qCDebug(KCALCORE_LOG) << " ~> Y=" << year << ", M=" << month << ", D=" << day << ", H=" << hour << ", m=" << minute << ", S=" << second << ", wd=" << weekday << ",#wd=" << weekdaynr << ", #w=" << weeknumber << ", yd=" << yearday; } //@endcond QString dumpTime(const QDateTime &dt, bool isAllDay) { #ifndef NDEBUG if (!dt.isValid()) { return QString(); } QString result; if (isAllDay) { result = dt.toString(QStringLiteral("ddd yyyy-MM-dd t")); } else { result = dt.toString(QStringLiteral("ddd yyyy-MM-dd hh:mm:ss t")); } return result; #else Q_UNUSED(dt); return QString(); #endif } QDateTime RecurrenceRule::startDt() const { return d->mDateStart; } RecurrenceRule::PeriodType RecurrenceRule::recurrenceType() const { return d->mPeriod; } uint RecurrenceRule::frequency() const { return d->mFrequency; } int RecurrenceRule::duration() const { return d->mDuration; } QString RecurrenceRule::rrule() const { return d->mRRule; } void RecurrenceRule::setRRule(const QString &rrule) { d->mRRule = rrule; } bool RecurrenceRule::isReadOnly() const { return d->mIsReadOnly; } void RecurrenceRule::setReadOnly(bool readOnly) { d->mIsReadOnly = readOnly; } bool RecurrenceRule::recurs() const { return d->mPeriod != rNone; } bool RecurrenceRule::allDay() const { return d->mAllDay; } const QList &RecurrenceRule::bySeconds() const { return d->mBySeconds; } const QList &RecurrenceRule::byMinutes() const { return d->mByMinutes; } const QList &RecurrenceRule::byHours() const { return d->mByHours; } const QList &RecurrenceRule::byDays() const { return d->mByDays; } const QList &RecurrenceRule::byMonthDays() const { return d->mByMonthDays; } const QList &RecurrenceRule::byYearDays() const { return d->mByYearDays; } const QList &RecurrenceRule::byWeekNumbers() const { return d->mByWeekNumbers; } const QList &RecurrenceRule::byMonths() const { return d->mByMonths; } const QList &RecurrenceRule::bySetPos() const { return d->mBySetPos; } short RecurrenceRule::weekStart() const { return d->mWeekStart; } RecurrenceRule::RuleObserver::~RuleObserver() { } RecurrenceRule::WDayPos::WDayPos(int ps, short dy) : mDay(dy), mPos(ps) { } void RecurrenceRule::WDayPos::setDay(short dy) { mDay = dy; } short RecurrenceRule::WDayPos::day() const { return mDay; } void RecurrenceRule::WDayPos::setPos(int ps) { mPos = ps; } int RecurrenceRule::WDayPos::pos() const { return mPos; } QDataStream &operator<<(QDataStream &out, const Constraint &c) { out << c.year << c.month << c.day << c.hour << c.minute << c.second << c.weekday << c.weekdaynr << c.weeknumber << c.yearday << c.weekstart; serializeQTimeZoneAsSpec(out, c.timeZone); out << false; // for backwards compatibility return out; } QDataStream &operator>>(QDataStream &in, Constraint &c) { bool secondOccurrence; // no longer used in >> c.year >> c.month >> c.day >> c.hour >> c.minute >> c.second >> c.weekday >> c.weekdaynr >> c.weeknumber >> c.yearday >> c.weekstart; deserializeSpecAsQTimeZone(in, c.timeZone); in >> secondOccurrence; return in; } KCALCORE_EXPORT QDataStream &KCalCore::operator<<(QDataStream &out, const KCalCore::RecurrenceRule::WDayPos &w) { out << w.mDay << w.mPos; return out; } KCALCORE_EXPORT QDataStream &KCalCore::operator>>(QDataStream &in, KCalCore::RecurrenceRule::WDayPos &w) { in >> w.mDay >> w.mPos; return in; } KCALCORE_EXPORT QDataStream &KCalCore::operator<<(QDataStream &out, const KCalCore::RecurrenceRule *r) { if (!r) { return out; } RecurrenceRule::Private *d = r->d; out << d->mRRule << static_cast(d->mPeriod); serializeQDateTimeAsKDateTime(out, d->mDateStart); out << d->mFrequency << d->mDuration; serializeQDateTimeAsKDateTime(out, d->mDateEnd); out << d->mBySeconds << d->mByMinutes << d->mByHours << d->mByDays << d->mByMonthDays << d->mByYearDays << d->mByWeekNumbers << d->mByMonths << d->mBySetPos << d->mWeekStart << d->mConstraints << d->mAllDay << d->mNoByRules << d->mTimedRepetition << d->mIsReadOnly; return out; } KCALCORE_EXPORT QDataStream &KCalCore::operator>>(QDataStream &in, const KCalCore::RecurrenceRule *r) { if (!r) { return in; } RecurrenceRule::Private *d = r->d; quint32 period; in >> d->mRRule >> period; deserializeKDateTimeAsQDateTime(in, d->mDateStart); in >> d->mFrequency >> d->mDuration; deserializeKDateTimeAsQDateTime(in, d->mDateEnd); in >> d->mBySeconds >> d->mByMinutes >> d->mByHours >> d->mByDays >> d->mByMonthDays >> d->mByYearDays >> d->mByWeekNumbers >> d->mByMonths >> d->mBySetPos >> d->mWeekStart >> d->mConstraints >> d->mAllDay >> d->mNoByRules >> d->mTimedRepetition >> d->mIsReadOnly; d->mPeriod = static_cast(period); return in; } diff --git a/src/utils.cpp b/src/utils.cpp index acc55da5e..9358365bd 100644 --- a/src/utils.cpp +++ b/src/utils.cpp @@ -1,268 +1,257 @@ /* This file is part of the kcalcore library. Copyright (c) 2017 Daniel Vrátil This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "utils.h" #include #include #include #include #include KDateTime::Spec KCalCore::zoneToSpec(const QTimeZone& zone) { if (!zone.isValid()) return KDateTime::Invalid; if (zone == QTimeZone::utc()) return KDateTime::UTC; if (zone == QTimeZone::systemTimeZone()) return KDateTime::LocalZone; if (zone.id().startsWith("UTC")) { return KDateTime::Spec(KDateTime::OffsetFromUTC, zone.offsetFromUtc(QDateTime::currentDateTimeUtc())); } else { return KSystemTimeZones::zone(QString::fromLatin1(zone.id())); } } namespace { QTimeZone resolveCustomTZ(const KTimeZone &ktz) { // First, let's try Microsoft const auto msIana = QTimeZone::windowsIdToDefaultIanaId(ktz.name().toUtf8()); if (!msIana.isEmpty()) { return QTimeZone(msIana); } int standardUtcOffset = 0; bool matched = false; const auto phases = ktz.phases(); for (const auto &phase : phases) { if (!phase.isDst()) { standardUtcOffset = phase.utcOffset(); matched = true; break; } } if (!matched) { standardUtcOffset = ktz.currentOffset(Qt::UTC); } const auto candidates = QTimeZone::availableTimeZoneIds(standardUtcOffset); QMap matchedCandidates; for (const auto &tzid : candidates) { const QTimeZone candidate(tzid); // This would be a fallback if (candidate.hasTransitions() != ktz.hasTransitions()) { matchedCandidates.insert(0, candidate); continue; } // Without transitions, we can't do any more precise matching, so just // accept this candidate and be done with it if (!candidate.hasTransitions() && !ktz.hasTransitions()) { return candidate; } // Calculate how many transitions this candidate shares with the ktz. // The candidate with the most matching transitions will win. const auto transitions = ktz.transitions(QDateTime(), QDateTime::currentDateTimeUtc()); int matchedTransitions = 0; for (auto it = transitions.rbegin(), end = transitions.rend(); it != end; ++it) { const auto &transition = *it; const QTimeZone::OffsetDataList candidateTransitions = candidate.transitions(transition.time(), transition.time()); if (candidateTransitions.isEmpty()) { continue; } ++matchedTransitions; // 1 point for a matching transition const auto candidateTransition = candidateTransitions[0]; const auto abvs = transition.phase().abbreviations(); for (const auto &abv : abvs) { if (candidateTransition.abbreviation == QString::fromUtf8(abv)) { matchedTransitions += 1024; // lots of points for a transition with a matching abbreviation break; } } } matchedCandidates.insert(matchedTransitions, candidate); } if (!matchedCandidates.isEmpty()) { return matchedCandidates.value(matchedCandidates.lastKey()); } return {}; } } QTimeZone KCalCore::specToZone(const KDateTime::Spec &spec) { switch (spec.type()) { case KDateTime::Invalid: return QTimeZone(); case KDateTime::LocalZone: case KDateTime::ClockTime: return QTimeZone::systemTimeZone(); case KDateTime::UTC: return QTimeZone::utc(); default: { auto tz = QTimeZone(spec.timeZone().name().toUtf8()); if (!tz.isValid()) { tz = resolveCustomTZ(spec.timeZone()); qDebug() << "Resolved" << spec.timeZone().name() << "to" << tz.id(); } return tz; } } return QTimeZone::systemTimeZone(); } QDateTime KCalCore::k2q(const KDateTime &kdt) { if (kdt.isValid()) { return QDateTime(kdt.date(), kdt.time(), specToZone(kdt.timeSpec())); } else { return QDateTime(); } } -KDateTime KCalCore::q2k(const QDateTime &qdt, bool allDay) -{ - if (qdt.isValid()) { - KDateTime kdt(qdt.date(), qdt.time(), zoneToSpec(qdt.timeZone())); - kdt.setDateOnly(allDay && qdt.time() == QTime(0, 0, 0)); - return kdt; - } else { - return KDateTime(); - } -} - // To remain backwards compatible we need to (de)serialize QDateTime the way KDateTime // was (de)serialized void KCalCore::serializeQDateTimeAsKDateTime(QDataStream &out, const QDateTime &dt) { out << dt.date() << dt.time(); switch (dt.timeSpec()) { case Qt::UTC: out << static_cast('u'); break; case Qt::OffsetFromUTC: out << static_cast('o') << dt.offsetFromUtc(); break; case Qt::TimeZone: serializeQTimeZoneAsSpec(out, dt.timeZone()); break; case Qt::LocalTime: out << static_cast('c'); break; } const bool isDateOnly = dt.date().isValid() && !dt.time().isValid(); out << quint8(isDateOnly ? 0x01 : 0x00); } void KCalCore::deserializeKDateTimeAsQDateTime(QDataStream &in, QDateTime &dt) { QDate date; QTime time; quint8 ts, flags; in >> date >> time >> ts; switch (static_cast(ts)) { case 'u': dt = QDateTime(date, time, Qt::UTC); break; case 'o': { int offset; in >> offset; dt = QDateTime(date, time, Qt::OffsetFromUTC, offset); break; } case 'z': { QString tzid; in >> tzid; dt = QDateTime(date, time, QTimeZone(tzid.toUtf8())); break; } case 'c': dt = QDateTime(date, time, Qt::LocalTime); break; } // unused, we don't have a special handling for date-only QDateTime in >> flags; } void KCalCore::serializeQTimeZoneAsSpec(QDataStream &out, const QTimeZone& tz) { out << static_cast('z') << (tz.isValid() ? QString::fromUtf8(tz.id()) : QString()); } void KCalCore::deserializeSpecAsQTimeZone(QDataStream &in, QTimeZone &tz) { quint8 ts; in >> ts; switch (static_cast(ts)) { case 'u': tz = QTimeZone::utc(); return; case 'o': { int offset; in >> offset; tz = QTimeZone(offset); return; } case 'z': { QString tzid; in >> tzid; tz = QTimeZone(tzid.toUtf8()); return; } case 'c': tz = QTimeZone::systemTimeZone(); break; } } void KCalCore::serializeQDateTimeSortableList(QDataStream &out, const SortableList &list) { out << list.size(); for (const auto &i : list) { serializeQDateTimeAsKDateTime(out, i); } } void KCalCore::deserializeQDateTimeSortableList(QDataStream& in, SortableList& list) { int size; in >> size; list.clear(); list.reserve(size); for (int i = 0; i < size; ++i) { QDateTime dt; deserializeKDateTimeAsQDateTime(in, dt); list << dt; } } diff --git a/src/utils.h b/src/utils.h index 1168439ea..44adb3eef 100644 --- a/src/utils.h +++ b/src/utils.h @@ -1,61 +1,60 @@ /* This file is part of the kcalcore library. Copyright (c) 2017 Daniel Vrátil This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef KCALCORE_UTILS_H_ #define KCALCORE_UTILS_H_ #include "kcalcore_export.h" #include "sortablelist.h" #include #include class QDataStream; namespace KCalCore { // TODO: PORTING-helper only, remove once KDateTime is gone /** * Helpers to retain backwards compatibility of binary serialization. */ KCALCORE_EXPORT void serializeQDateTimeAsKDateTime(QDataStream &out, const QDateTime &dt); KCALCORE_EXPORT void deserializeKDateTimeAsQDateTime(QDataStream &in, QDateTime &dt); void serializeQDateTimeSortableList(QDataStream &out, const SortableList &list); void deserializeQDateTimeSortableList(QDataStream &in, SortableList &list); void serializeQTimeZoneAsSpec(QDataStream &out, const QTimeZone &tz); void deserializeSpecAsQTimeZone(QDataStream &in, QTimeZone &tz); /** Convert a QTimeZone to a KDateTime::Spec */ KDateTime::Spec zoneToSpec(const QTimeZone &zone); /** Convert a QTimeZone to a KDateTime::Spec */ QTimeZone specToZone(const KDateTime::Spec &spec); /** Convert KDateTime to QDateTime, correctly preserves timespec */ QDateTime k2q(const KDateTime &kdt); -KDateTime q2k(const QDateTime &qdt, bool isAllDay = false); } #endif