author | Michael Krelin <hacker@klever.net> | 2007-07-04 11:23:42 (UTC) |
---|---|---|
committer | Michael Krelin <hacker@klever.net> | 2007-07-04 11:23:42 (UTC) |
commit | a08aff328d4393031d5ba7d622c2b05705a89d73 (patch) (side-by-side diff) | |
tree | 8ee90d686081c52e7c69b5ce946e9b1a7d690001 /libkcal | |
parent | 11edc920afe4f274c0964436633aa632c8288a40 (diff) | |
download | kdepimpi-a08aff328d4393031d5ba7d622c2b05705a89d73.zip kdepimpi-a08aff328d4393031d5ba7d622c2b05705a89d73.tar.gz kdepimpi-a08aff328d4393031d5ba7d622c2b05705a89d73.tar.bz2 |
initial public commit of qt4 portp1
50 files changed, 521 insertions, 449 deletions
diff --git a/libkcal/alarm.cpp b/libkcal/alarm.cpp index 3157214..3c4a81c 100644 --- a/libkcal/alarm.cpp +++ b/libkcal/alarm.cpp @@ -1,444 +1,446 @@ /* This file is part of libkcal. Copyright (c) 1998 Preston Brown Copyright (c) 2001 Cornelius Schumacher <schumacher@kde.org> 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #include <kdebug.h> #include <klocale.h> #include "incidence.h" #include "todo.h" #include "alarm.h" +//Added by qt3to4: +#include <Q3ValueList> using namespace KCal; #include <qwidget.h> Alarm::Alarm(Incidence *parent) : mParent(parent), mType(Audio), mDescription(""), // to make operator==() not fail mFile(""), // to make operator==() not fail mMailSubject(""), // to make operator==() not fail mAlarmSnoozeTime(5), mAlarmRepeatCount(0), mEndOffset(false), mHasTime(false), mAlarmEnabled(false) { } Alarm::~Alarm() { } bool Alarm::operator==( const Alarm& rhs ) const { if ( mType != rhs.mType || mAlarmSnoozeTime != rhs.mAlarmSnoozeTime || mAlarmRepeatCount != rhs.mAlarmRepeatCount || mAlarmEnabled != rhs.mAlarmEnabled || mHasTime != rhs.mHasTime) return false; #if 0 if ( mType != rhs.mType ) { qDebug("aaa1 "); return false; } if ( mAlarmSnoozeTime != rhs.mAlarmSnoozeTime ) { qDebug("aaa2 "); return false; } if ( mAlarmRepeatCount != rhs.mAlarmRepeatCount ) { qDebug("aaa3 "); return false; } if ( mAlarmEnabled != rhs.mAlarmEnabled ) { qDebug("aaa4 "); return false; } if ( mHasTime != rhs.mHasTime ) { qDebug("aaa5 "); return false; } #endif if (mHasTime) { if (mAlarmTime != rhs.mAlarmTime) return false; } else { if (mOffset != rhs.mOffset || mEndOffset != rhs.mEndOffset) return false; } switch (mType) { case Display: return mDescription == rhs.mDescription; case Email: return mDescription == rhs.mDescription && mMailAttachFiles == rhs.mMailAttachFiles && mMailAddresses == rhs.mMailAddresses && mMailSubject == rhs.mMailSubject; case Procedure: return mFile == rhs.mFile && mDescription == rhs.mDescription; case Audio: return mFile == rhs.mFile; case Invalid: break; } return false; } void Alarm::setType(Alarm::Type type) { if (type == mType) return; switch (type) { case Display: mDescription = ""; break; case Procedure: mFile = mDescription = ""; break; case Audio: mFile = ""; break; case Email: mMailSubject = mDescription = ""; mMailAddresses.clear(); mMailAttachFiles.clear(); break; case Invalid: break; default: return; } mType = type; mParent->updated(); } Alarm::Type Alarm::type() const { return mType; } void Alarm::setAudioAlarm(const QString &audioFile) { mType = Audio; mFile = audioFile; mParent->updated(); } void Alarm::setAudioFile(const QString &audioFile) { if (mType == Audio) { mFile = audioFile; mParent->updated(); } } QString Alarm::audioFile() const { return (mType == Audio) ? mFile : QString::null; } void Alarm::setProcedureAlarm(const QString &programFile, const QString &arguments) { mType = Procedure; mFile = programFile; mDescription = arguments; mParent->updated(); } void Alarm::setProgramFile(const QString &programFile) { if (mType == Procedure) { mFile = programFile; mParent->updated(); } } QString Alarm::programFile() const { return (mType == Procedure) ? mFile : QString::null; } void Alarm::setProgramArguments(const QString &arguments) { if (mType == Procedure) { mDescription = arguments; mParent->updated(); } } QString Alarm::programArguments() const { return (mType == Procedure) ? mDescription : QString::null; } void Alarm::setEmailAlarm(const QString &subject, const QString &text, - const QValueList<Person> &addressees, const QStringList &attachments) + const Q3ValueList<Person> &addressees, const QStringList &attachments) { mType = Email; mMailSubject = subject; mDescription = text; mMailAddresses = addressees; mMailAttachFiles = attachments; mParent->updated(); } void Alarm::setMailAddress(const Person &mailAddress) { if (mType == Email) { mMailAddresses.clear(); mMailAddresses += mailAddress; mParent->updated(); } } -void Alarm::setMailAddresses(const QValueList<Person> &mailAddresses) +void Alarm::setMailAddresses(const Q3ValueList<Person> &mailAddresses) { if (mType == Email) { mMailAddresses = mailAddresses; mParent->updated(); } } void Alarm::addMailAddress(const Person &mailAddress) { if (mType == Email) { mMailAddresses += mailAddress; mParent->updated(); } } -QValueList<Person> Alarm::mailAddresses() const +Q3ValueList<Person> Alarm::mailAddresses() const { - return (mType == Email) ? mMailAddresses : QValueList<Person>(); + return (mType == Email) ? mMailAddresses : Q3ValueList<Person>(); } void Alarm::setMailSubject(const QString &mailAlarmSubject) { if (mType == Email) { mMailSubject = mailAlarmSubject; mParent->updated(); } } QString Alarm::mailSubject() const { return (mType == Email) ? mMailSubject : QString::null; } void Alarm::setMailAttachment(const QString &mailAttachFile) { if (mType == Email) { mMailAttachFiles.clear(); mMailAttachFiles += mailAttachFile; mParent->updated(); } } void Alarm::setMailAttachments(const QStringList &mailAttachFiles) { if (mType == Email) { mMailAttachFiles = mailAttachFiles; mParent->updated(); } } void Alarm::addMailAttachment(const QString &mailAttachFile) { if (mType == Email) { mMailAttachFiles += mailAttachFile; mParent->updated(); } } QStringList Alarm::mailAttachments() const { return (mType == Email) ? mMailAttachFiles : QStringList(); } void Alarm::setMailText(const QString &text) { if (mType == Email) { mDescription = text; mParent->updated(); } } QString Alarm::mailText() const { return (mType == Email) ? mDescription : QString::null; } void Alarm::setDisplayAlarm(const QString &text) { mType = Display; mDescription = text; mParent->updated(); } void Alarm::setText(const QString &text) { if (mType == Display) { mDescription = text; mParent->updated(); } } QString Alarm::text() const { return (mType == Display) ? mDescription : QString::null; } void Alarm::setTime(const QDateTime &alarmTime) { mAlarmTime = alarmTime; mHasTime = true; mParent->updated(); } int Alarm::offset() { if ( hasTime() ) { if (mParent->typeID() == todoID ) { Todo *t = static_cast<Todo*>(mParent); return t->dtDue().secsTo( mAlarmTime ) ; } else return mParent->dtStart().secsTo( mAlarmTime ) ; } else { return mOffset.asSeconds(); } } QString Alarm::offsetText() { int min = -offset()/60; int hours = min /60; min = min % 60; int days = hours /24; hours = hours % 24; QString message; //qDebug("%d %d %d ", days, hours, min ); if ( days > 0 ) message += i18n("%1d").arg( days ); if ( hours > 0 ) { if ( !message.isEmpty() ) message += "/"; message += i18n("%1h").arg( hours ); } if ( min > 0 ) { if ( !message.isEmpty() ) message += "/"; message += i18n("%1min").arg( min ); } if ( message.isEmpty() ) message = i18n("%1min").arg( 0 ); if ( !mParent->alarmEnabled() ) return "!"+message + i18n("(disabled)"); return message; } QDateTime Alarm::time() const { if ( hasTime() ) return mAlarmTime; else { if (mParent->typeID() == todoID ) { Todo *t = static_cast<Todo*>(mParent); return mOffset.end( t->dtDue() ); } else if (mEndOffset) { return mOffset.end( mParent->dtEnd() ); } else { return mOffset.end( mParent->dtStart() ); } } } bool Alarm::hasTime() const { return mHasTime; } void Alarm::setSnoozeTime(int alarmSnoozeTime) { mAlarmSnoozeTime = alarmSnoozeTime; mParent->updated(); } int Alarm::snoozeTime() const { return mAlarmSnoozeTime; } void Alarm::setRepeatCount(int alarmRepeatCount) { kdDebug(5800) << "Alarm::setRepeatCount(): " << alarmRepeatCount << endl; mAlarmRepeatCount = alarmRepeatCount; mParent->updated(); } int Alarm::repeatCount() const { kdDebug(5800) << "Alarm::repeatCount(): " << mAlarmRepeatCount << endl; return mAlarmRepeatCount; } void Alarm::toggleAlarm() { mAlarmEnabled = !mAlarmEnabled; mParent->updated(); } void Alarm::setEnabled(bool enable) { mAlarmEnabled = enable; mParent->updated(); } bool Alarm::enabled() const { return mAlarmEnabled; } void Alarm::setStartOffset( const Duration &offset ) diff --git a/libkcal/alarm.h b/libkcal/alarm.h index ac6ea0d..b24f0f7 100644 --- a/libkcal/alarm.h +++ b/libkcal/alarm.h @@ -1,246 +1,246 @@ /* This file is part of libkcal. Copyright (c) 2001 Cornelius Schumacher <schumacher@kde.org> 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #ifndef KCAL_ALARM_H #define KCAL_ALARM_H #include <qstring.h> -#include <qvaluelist.h> +#include <q3valuelist.h> #include "customproperties.h" #include "duration.h" #include "person.h" namespace KCal { class Incidence; /** This class represents an alarm notification. */ class Alarm : public CustomProperties { public: enum Type { Invalid, Display, Procedure, Email, Audio }; - typedef QValueList<Alarm *> List; + typedef Q3ValueList<Alarm *> List; /** Construct a new alarm with variables initialized to "sane" values. */ explicit Alarm(Incidence *parent); /** Destruct Alarm object. */ ~Alarm(); /** Compare this alarm with another one. */ bool operator==(const Alarm &) const; bool operator!=(const Alarm &a) const { return !operator==(a); } /** Set the type of the alarm. If the specified type is different from the current type of the alarm, the alarm's type-specific properties are initialised to null. @param type type of alarm. */ void setType(Type type); /** Return the type of the alarm */ Type type() const; int offset(); QString offsetText(); /** Set the alarm to be a display alarm. @param text text to display when the alarm is triggered. */ void setDisplayAlarm(const QString &text); /** Set the text to be displayed when the alarm is triggered. Ignored if the alarm is not a display alarm. */ void setText(const QString &text); /** Return the text string that displays when the alarm is triggered. */ QString text() const; /** Set the alarm to be an audio alarm. @param audioFile optional file to play when the alarm is triggered. */ void setAudioAlarm(const QString &audioFile = QString::null); /** Set the file to play when the audio alarm is triggered. Ignored if the alarm is not an audio alarm. */ void setAudioFile(const QString &audioFile); /** Return the name of the audio file for the alarm. @return The audio file for the alarm, or QString::null if not an audio alarm. */ QString audioFile() const; /** Set the alarm to be a procedure alarm. @param programFile program to execute when the alarm is triggered. @param arguments arguments to supply to programFile. */ void setProcedureAlarm(const QString &programFile, const QString &arguments = QString::null); /** Set the program file to execute when the alarm is triggered. Ignored if the alarm is not a procedure alarm. */ void setProgramFile(const QString &programFile); /** Return the name of the program file to execute when the alarm is triggered. @return the program file name, or QString::null if not a procedure alarm. */ QString programFile() const; /** Set the arguments to the program to execute when the alarm is triggered. Ignored if the alarm is not a procedure alarm. */ void setProgramArguments(const QString &arguments); /** Return the arguments to the program to run when the alarm is triggered. @return the program arguments, or QString::null if not a procedure alarm. */ QString programArguments() const; /** Set the alarm to be an email alarm. @param subject subject line of email. @param text body of email. @param addressees email addresses of recipient(s). @param attachments optional names of files to attach to the email. */ - void setEmailAlarm(const QString &subject, const QString &text, const QValueList<Person> &addressees, + void setEmailAlarm(const QString &subject, const QString &text, const Q3ValueList<Person> &addressees, const QStringList &attachments = QStringList()); /** Send mail to this address when the alarm is triggered. Ignored if the alarm is not an email alarm. */ void setMailAddress(const Person &mailAlarmAddress); /** Send mail to these addresses when the alarm is triggered. Ignored if the alarm is not an email alarm. */ - void setMailAddresses(const QValueList<Person> &mailAlarmAddresses); + void setMailAddresses(const Q3ValueList<Person> &mailAlarmAddresses); /** Add this address to the list of addresses to send mail to when the alarm is triggered. Ignored if the alarm is not an email alarm. */ void addMailAddress(const Person &mailAlarmAddress); /** return the addresses to send mail to when an alarm goes off */ - QValueList<Person> mailAddresses() const; + Q3ValueList<Person> mailAddresses() const; /** Set the subject line of the mail. Ignored if the alarm is not an email alarm. */ void setMailSubject(const QString &mailAlarmSubject); /** return the subject line of the mail */ QString mailSubject() const; /** Attach this filename to the email. Ignored if the alarm is not an email alarm. */ void setMailAttachment(const QString &mailAttachFile); /** Attach these filenames to the email. Ignored if the alarm is not an email alarm. */ void setMailAttachments(const QStringList &mailAttachFiles); /** Add this filename to the list of files to attach to the email. Ignored if the alarm is not an email alarm. */ void addMailAttachment(const QString &mailAttachFile); /** return the filenames to attach to the email */ QStringList mailAttachments() const; /** Set the email body text. Ignored if the alarm is not an email alarm. */ void setMailText(const QString &text); /** Return the email body text. @return the body text, or QString::null if not an email alarm. */ QString mailText() const; /** set the time to trigger an alarm */ void setTime(const QDateTime &alarmTime); /** return the date/time when an alarm goes off */ QDateTime time() const; /** Return true, if the alarm has an explicit date/time. */ bool hasTime() const; /** Set offset of alarm in time relative to the start of the event. */ void setStartOffset(const Duration &); /** Return offset of alarm in time relative to the start of the event. * If the alarm's time is not defined in terms of an offset relative * to the start of the event, returns zero. */ Duration startOffset() const; /** Return whether the alarm is defined in terms of an offset relative * to the start of the event. */ bool hasStartOffset() const; /** Set offset of alarm in time relative to the end of the event. */ void setEndOffset(const Duration &); /** Return offset of alarm in time relative to the end of the event. * If the alarm's time is not defined in terms of an offset relative * to the end of the event, returns zero. */ Duration endOffset() const; /** Return whether the alarm is defined in terms of an offset relative * to the end of the event. */ bool hasEndOffset() const; /** Set the interval between snoozes for the alarm. @param snoozeTime the time in minutes between snoozes. */ void setSnoozeTime(int alarmSnoozeTime); /** Get how long the alarm snooze interval is. @return the number of minutes between snoozes. */ int snoozeTime() const; /** set how many times an alarm is to repeat itself (w/snoozes) */ void setRepeatCount(int alarmRepeatCount); /** get how many times an alarm repeats */ int repeatCount() const; /** toggles the value of alarm to be either on or off. set's the alarm time to be x minutes before dtStart time. */ void toggleAlarm(); /** set the alarm enabled status */ void setEnabled(bool enable); /** get the alarm enabled status */ bool enabled() const; /** Set the alarm's parent incidence */ void setParent( Incidence * ); /** get the alarm's parent incidence */ Incidence *parent() const { return mParent; } private: Incidence *mParent; // the incidence which this alarm belongs to Type mType; // type of alarm QString mDescription; // text to display/email body/procedure arguments QString mFile; // procedure program to run/optional audio file to play QStringList mMailAttachFiles; // filenames to attach to email - QValueList<Person> mMailAddresses; // who to mail for reminder + Q3ValueList<Person> mMailAddresses; // who to mail for reminder QString mMailSubject; // subject of email int mAlarmSnoozeTime; // number of minutes after alarm to // snooze before ringing again int mAlarmRepeatCount; // number of times for alarm to repeat // after the initial time QDateTime mAlarmTime; // time at which to trigger the alarm Duration mOffset; // time relative to incidence DTSTART to trigger the alarm bool mEndOffset; // if true, mOffset relates to DTEND, not DTSTART bool mHasTime; // use mAlarmTime, not mOffset bool mAlarmEnabled; }; } #endif diff --git a/libkcal/calendar.cpp b/libkcal/calendar.cpp index 9b38d3f..bf095cf 100644 --- a/libkcal/calendar.cpp +++ b/libkcal/calendar.cpp @@ -1,526 +1,528 @@ /* This file is part of libkcal. Copyright (c) 1998 Preston Brown Copyright (c) 2000,2001 Cornelius Schumacher <schumacher@kde.org> 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #include <stdlib.h> #include <time.h> #include <kdebug.h> #include <kglobal.h> #include <klocale.h> #include "exceptions.h" #include "calfilter.h" #include "calendar.h" #include "syncdefines.h" +//Added by qt3to4: +#include <Q3PtrList> using namespace KCal; Calendar::Calendar() { init(); setTimeZoneId( " 00:00 Europe/London(UTC)" ); } Calendar::Calendar( const QString &timeZoneId ) { init(); setTimeZoneId(timeZoneId); } void Calendar::init() { mObserver = 0; mNewObserver = false; mUndoIncidence = 0; mDeleteIncidencesOnClose = true; mModified = false; mDefaultCalendar = 1; // Setup default filter, which does nothing mDefaultFilter = new CalFilter; mFilter = mDefaultFilter; mFilter->setEnabled(false); // initialize random numbers. This is a hack, and not // even that good of one at that. // srandom(time(0)); // user information... setOwner(i18n("Unknown Name")); setEmail(i18n("unknown@nowhere")); #if 0 tmpStr = KOPrefs::instance()->mTimeZone; // kdDebug(5800) << "Calendar::Calendar(): TimeZone: " << tmpStr << endl; int dstSetting = KOPrefs::instance()->mDaylightSavings; extern long int timezone; struct tm *now; time_t curtime; curtime = time(0); now = localtime(&curtime); int hourOff = - ((timezone / 60) / 60); if (now->tm_isdst) hourOff += 1; QString tzStr; tzStr.sprintf("%.2d%.2d", hourOff, abs((timezone / 60) % 60)); // if no time zone was in the config file, write what we just discovered. if (tmpStr.isEmpty()) { // KOPrefs::instance()->mTimeZone = tzStr; } else { tzStr = tmpStr; } // if daylight savings has changed since last load time, we need // to rewrite these settings to the config file. if ((now->tm_isdst && !dstSetting) || (!now->tm_isdst && dstSetting)) { KOPrefs::instance()->mTimeZone = tzStr; KOPrefs::instance()->mDaylightSavings = now->tm_isdst; } setTimeZone(tzStr); #endif // KOPrefs::instance()->writeConfig(); } Calendar::~Calendar() { delete mDefaultFilter; clearUndo( 0 ); } void Calendar::clearUndo( Incidence * newUndo ) { if ( mUndoIncidence ) { if ( mUndoIncidence->typeID() == eventID ) delete ((Event*) mUndoIncidence) ; else if ( mUndoIncidence->typeID() == todoID ) delete ( (Todo*) mUndoIncidence ); else if ( mUndoIncidence->typeID() == journalID ) delete ( (Journal*) mUndoIncidence ); else delete mUndoIncidence; } mUndoIncidence = newUndo; if ( mUndoIncidence ) { mUndoIncidence->clearRelations(); } } void Calendar::setDontDeleteIncidencesOnClose () { mDeleteIncidencesOnClose = false; } void Calendar::setDefaultCalendar( int d ) { mDefaultCalendar = d; } int Calendar::defaultCalendar() { return mDefaultCalendar; } const QString &Calendar::getOwner() const { return mOwner; } bool Calendar::undoDeleteIncidence() { if (!mUndoIncidence) return false; addIncidence(mUndoIncidence); mUndoIncidence = 0; return true; } void Calendar::setOwner(const QString &os) { int i; mOwner = os; i = mOwner.find(','); if (i != -1) mOwner = mOwner.left(i); setModified( true ); } void Calendar::setTimeZone(const QString & tz) { bool neg = FALSE; int hours, minutes; QString tmpStr(tz); if (tmpStr.left(1) == "-") neg = TRUE; if (tmpStr.left(1) == "-" || tmpStr.left(1) == "+") tmpStr.remove(0, 1); hours = tmpStr.left(2).toInt(); if (tmpStr.length() > 2) minutes = tmpStr.right(2).toInt(); else minutes = 0; mTimeZone = (60*hours+minutes); if (neg) mTimeZone = -mTimeZone; mLocalTime = false; setModified( true ); } QString Calendar::getTimeZoneStr() const { if (mLocalTime) return ""; QString tmpStr; int hours = abs(mTimeZone / 60); int minutes = abs(mTimeZone % 60); bool neg = mTimeZone < 0; tmpStr.sprintf("%c%.2d%.2d", (neg ? '-' : '+'), hours, minutes); return tmpStr; } void Calendar::setTimeZone(int tz) { mTimeZone = tz; mLocalTime = false; setModified( true ); } int Calendar::getTimeZone() const { return mTimeZone; } void Calendar::setTimeZoneId(const QString &id) { mTimeZoneId = id; mLocalTime = false; mTimeZone = KGlobal::locale()->timezoneOffset(mTimeZoneId); if ( mTimeZone > 1000) setLocalTime(); //qDebug("Calendar::setTimeZoneOffset %s %d ",mTimeZoneId.latin1(), mTimeZone); setModified( true ); } QString Calendar::timeZoneId() const { return mTimeZoneId; } void Calendar::setLocalTime() { //qDebug("Calendar::setLocalTime() "); mLocalTime = true; mTimeZone = 0; mTimeZoneId = ""; setModified( true ); } bool Calendar::isLocalTime() const { return mLocalTime; } const QString &Calendar::getEmail() { return mOwnerEmail; } void Calendar::setEmail(const QString &e) { mOwnerEmail = e; setModified( true ); } void Calendar::setFilter(CalFilter *filter) { mFilter = filter; } CalFilter *Calendar::filter() { return mFilter; } -QPtrList<Incidence> Calendar::incidences() +Q3PtrList<Incidence> Calendar::incidences() { - QPtrList<Incidence> incidences; + Q3PtrList<Incidence> incidences; Incidence *i; - QPtrList<Event> e = events(); + Q3PtrList<Event> e = events(); for( i = e.first(); i; i = e.next() ) incidences.append( i ); - QPtrList<Todo> t = todos(); + Q3PtrList<Todo> t = todos(); for( i = t.first(); i; i = t.next() ) incidences.append( i ); - QPtrList<Journal> j = journals(); + Q3PtrList<Journal> j = journals(); for( i = j.first(); i; i = j.next() ) incidences.append( i ); return incidences; } void Calendar::resetPilotStat(int id ) { - QPtrList<Incidence> incidences; + Q3PtrList<Incidence> incidences; Incidence *i; - QPtrList<Event> e = rawEvents(); + Q3PtrList<Event> e = rawEvents(); for( i = e.first(); i; i = e.next() ) i->setPilotId( id ); - QPtrList<Todo> t = rawTodos(); + Q3PtrList<Todo> t = rawTodos(); for( i = t.first(); i; i = t.next() ) i->setPilotId( id ); - QPtrList<Journal> j = journals(); + Q3PtrList<Journal> j = journals(); for( i = j.first(); i; i = j.next() ) i->setPilotId( id ); } void Calendar::resetTempSyncStat() { - QPtrList<Incidence> incidences; + Q3PtrList<Incidence> incidences; Incidence *i; - QPtrList<Event> e = rawEvents(); + Q3PtrList<Event> e = rawEvents(); for( i = e.first(); i; i = e.next() ) i->setTempSyncStat( SYNC_TEMPSTATE_INITIAL ); - QPtrList<Todo> t = rawTodos(); + Q3PtrList<Todo> t = rawTodos(); for( i = t.first(); i; i = t.next() ) i->setTempSyncStat( SYNC_TEMPSTATE_INITIAL ); - QPtrList<Journal> j = journals(); + Q3PtrList<Journal> j = journals(); for( i = j.first(); i; i = j.next() ) i->setTempSyncStat( SYNC_TEMPSTATE_INITIAL ); } -QPtrList<Incidence> Calendar::rawIncidences() +Q3PtrList<Incidence> Calendar::rawIncidences() { - QPtrList<Incidence> incidences; + Q3PtrList<Incidence> incidences; Incidence *i; - QPtrList<Event> e = rawEvents(); + Q3PtrList<Event> e = rawEvents(); for( i = e.first(); i; i = e.next() ) incidences.append( i ); - QPtrList<Todo> t = rawTodos(); + Q3PtrList<Todo> t = rawTodos(); for( i = t.first(); i; i = t.next() ) incidences.append( i ); - QPtrList<Journal> j = journals(); + Q3PtrList<Journal> j = journals(); for( i = j.first(); i; i = j.next() ) incidences.append( i ); return incidences; } -QPtrList<Event> Calendar::events( const QDate &date, bool sorted ) +Q3PtrList<Event> Calendar::events( const QDate &date, bool sorted ) { - QPtrList<Event> el = rawEventsForDate(date,sorted); + Q3PtrList<Event> el = rawEventsForDate(date,sorted); mFilter->apply(&el); return el; } -QPtrList<Event> Calendar::events( const QDateTime &qdt ) +Q3PtrList<Event> Calendar::events( const QDateTime &qdt ) { - QPtrList<Event> el = rawEventsForDate(qdt); + Q3PtrList<Event> el = rawEventsForDate(qdt); mFilter->apply(&el); return el; } -QPtrList<Event> Calendar::events( const QDate &start, const QDate &end, +Q3PtrList<Event> Calendar::events( const QDate &start, const QDate &end, bool inclusive) { - QPtrList<Event> el = rawEvents(start,end,inclusive); + Q3PtrList<Event> el = rawEvents(start,end,inclusive); mFilter->apply(&el); return el; } -QPtrList<Event> Calendar::events() +Q3PtrList<Event> Calendar::events() { - QPtrList<Event> el = rawEvents(); + Q3PtrList<Event> el = rawEvents(); mFilter->apply(&el); return el; } void Calendar::addIncidenceBranch(Incidence *i) { addIncidence( i ); Incidence * inc; - QPtrList<Incidence> Relations = i->relations(); + Q3PtrList<Incidence> Relations = i->relations(); for (inc=Relations.first();inc;inc=Relations.next()) { addIncidenceBranch( inc ); } } bool Calendar::addIncidence(Incidence *i) { Incidence::AddVisitor<Calendar> v(this); if ( i->calID() == 0 ) i->setCalID_block( mDefaultCalendar ); i->setCalEnabled( true ); return i->accept(v); } void Calendar::deleteIncidence(Incidence *in) { if ( in->typeID() == eventID ) deleteEvent( (Event*) in ); else if ( in->typeID() == todoID ) deleteTodo( (Todo*) in); else if ( in->typeID() == journalID ) deleteJournal( (Journal*) in ); } Incidence* Calendar::incidence( const QString& uid ) { Incidence* i; if( (i = todo( uid )) != 0 ) return i; if( (i = event( uid )) != 0 ) return i; if( (i = journal( uid )) != 0 ) return i; return 0; } -QPtrList<Todo> Calendar::todos() +Q3PtrList<Todo> Calendar::todos() { - QPtrList<Todo> tl = rawTodos(); + Q3PtrList<Todo> tl = rawTodos(); mFilter->apply( &tl ); return tl; } // When this is called, the todo have already been added to the calendar. // This method is only about linking related todos void Calendar::setupRelations( Incidence *incidence ) { QString uid = incidence->uid(); qDebug("Calendar::setupRelations %s", incidence->summary().latin1()); // First, go over the list of orphans and see if this is their parent while( Incidence* i = mOrphans[ uid ] ) { mOrphans.remove( uid ); i->setRelatedTo( incidence ); qDebug("Add child %s ti inc %s", i->summary().latin1(),incidence->summary().latin1()); incidence->addRelation( i ); mOrphanUids.remove( i->uid() ); } // Now see about this incidences parent if( !incidence->relatedTo() && !incidence->relatedToUid().isEmpty() ) { // This incidence has a uid it is related to, but is not registered to it yet // Try to find it qDebug("Test parent for %s", incidence->summary().latin1()); Incidence* parent = this->incidenceForUid( incidence->relatedToUid(), true ); if( parent ) { // Found it qDebug("parent found for for %s", incidence->summary().latin1()); incidence->setRelatedTo( parent ); parent->addRelation( incidence ); } else { qDebug("NO parent found for for %s", incidence->summary().latin1()); // Not found, put this in the mOrphans list mOrphans.insert( incidence->relatedToUid(), incidence ); mOrphanUids.insert( incidence->uid(), incidence ); } } } // If a task with subtasks is deleted, move it's subtasks to the orphans list void Calendar::removeRelations( Incidence *incidence ) { // qDebug("Calendar::removeRelations "); QString uid = incidence->uid(); - QPtrList<Incidence> relations = incidence->relations(); + Q3PtrList<Incidence> relations = incidence->relations(); for( Incidence* i = relations.first(); i; i = relations.next() ) if( !mOrphanUids.find( i->uid() ) ) { mOrphans.insert( uid, i ); mOrphanUids.insert( i->uid(), i ); i->setRelatedTo( 0 ); i->setRelatedToUid( uid ); } // If this incidence is related to something else, tell that about it if( incidence->relatedTo() ) incidence->relatedTo()->removeRelation( incidence ); // Remove this one from the orphans list if( mOrphanUids.remove( uid ) ) { QString r2uid = incidence->relatedToUid(); - QPtrList<Incidence> tempList; + Q3PtrList<Incidence> tempList; while( Incidence* i = mOrphans[ r2uid ] ) { mOrphans.remove( r2uid ); if ( i != incidence ) tempList.append( i ); } Incidence* inc = tempList.first(); while ( inc ) { mOrphans.insert( r2uid, inc ); inc = tempList.next(); } } // LR: and another big bad bug found #if 0 // This incidence is located in the orphans list - it should be removed if( !( incidence->relatedTo() != 0 && mOrphans.remove( incidence->relatedTo()->uid() ) ) ) { // Removing wasn't that easy - for( QDictIterator<Incidence> it( mOrphans ); it.current(); ++it ) { + for( Q3DictIterator<Incidence> it( mOrphans ); it.current(); ++it ) { if( it.current()->uid() == uid ) { mOrphans.remove( it.currentKey() ); break; } } } #endif } void Calendar::registerObserver( Observer *observer ) { mObserver = observer; mNewObserver = true; } void Calendar::setModified( bool modified ) { if ( mObserver ) mObserver->calendarModified( modified, this ); if ( modified != mModified || mNewObserver ) { mNewObserver = false; // if ( mObserver ) mObserver->calendarModified( modified, this ); mModified = modified; } } void Calendar::setLoadedProductId( const QString &id ) { mLoadedProductId = id; } QString Calendar::loadedProductId() { return mLoadedProductId; } //#include "calendar.moc" diff --git a/libkcal/calendar.h b/libkcal/calendar.h index fbc40ad..5845f44 100644 --- a/libkcal/calendar.h +++ b/libkcal/calendar.h @@ -1,385 +1,385 @@ /* This file is part of libkcal. Copyright (c) 1998 Preston Brown Copyright (c) 2001 Cornelius Schumacher <schumacher@kde.org> 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #ifndef CALENDAR_H #define CALENDAR_H #include <qobject.h> #include <qstring.h> #include <qdatetime.h> -#include <qptrlist.h> -#include <qdict.h> +#include <q3ptrlist.h> +#include <q3dict.h> #include "customproperties.h" #include "event.h" #include "todo.h" #include "journal.h" #include "calfilter.h" //#define _TIME_ZONE "-0500" /* hardcoded, overridden in config file. */ class KConfig; namespace KCal { /** This is the main "calendar" object class for KOrganizer. It holds information like all appointments/events, user information, etc. etc. one calendar is associated with each CalendarView (@see calendarview.h). This is an abstract base class defining the interface to a calendar. It is implemented by subclasses like @see CalendarLocal, which use different methods to store and access the data. Ownership of events etc. is handled by the following policy: As soon as an event (or any other subclass of IncidenceBase) object is added to the Calendar by addEvent() it is owned by the Calendar object. The Calendar takes care of deleting it. All Events returned by the query functions are returned as pointers, that means all changes to the returned events are immediately visible in the Calendar. You shouldn't delete any Event object you get from Calendar. */ class Calendar : public QObject, public CustomProperties, public IncidenceBase::Observer { Q_OBJECT public: Calendar(); Calendar(const QString &timeZoneId); virtual ~Calendar(); Incidence * undoIncidence() { return mUndoIncidence; }; bool undoDeleteIncidence(); void deleteIncidence(Incidence *in); void resetTempSyncStat(); void resetPilotStat(int id); /** Clears out the current calendar, freeing all used memory etc. */ virtual void close() = 0; virtual void addCalendar( Calendar* ) = 0; virtual bool addCalendarFile( QString name, int id ) = 0; virtual bool mergeCalendarFile( QString name ) = 0; virtual Incidence* incidenceForUid( const QString& uid, bool doNotCheckDuplicates , bool enabledOnly = false ,int * isDup = 0 ) = 0; virtual Todo* todoForUid( const QString& uid, bool doNotCheckDuplicates = true, bool enabledOnly = false ,int * isDup = 0) = 0; virtual void setSyncEventsReadOnly() = 0; virtual void setSyncEventsEnabled() = 0; virtual void stopAllTodos() = 0; virtual void clearUndo( Incidence * newUndo ); /** Sync changes in memory to persistant storage. */ virtual void save() = 0; - virtual QPtrList<Event> getExternLastSyncEvents() = 0; + virtual Q3PtrList<Event> getExternLastSyncEvents() = 0; virtual void removeSyncInfo( QString syncProfile) = 0; virtual bool isSaving() { return false; } /** Return the owner of the calendar's full name. */ const QString &getOwner() const; /** Set the owner of the calendar. Should be owner's full name. */ void setOwner( const QString &os ); /** Return the email address of the calendar owner. */ const QString &getEmail(); /** Set the email address of the calendar owner. */ void setEmail( const QString & ); /** Set time zone from a timezone string (e.g. -2:00) */ void setTimeZone( const QString &tz ); /** Set time zone from a minutes value (e.g. -60) */ void setTimeZone( int tz ); /** Return time zone as offest in minutes. */ int getTimeZone() const; /** Compute an ISO 8601 format string from the time zone. */ QString getTimeZoneStr() const; /** Set time zone id (see /usr/share/zoneinfo/zone.tab for list of legal values). */ void setTimeZoneId( const QString & ); /** Return time zone id. */ QString timeZoneId() const; /** Use local time, not UTC or a time zone. */ void setLocalTime(); /** Return whether local time is being used. */ bool isLocalTime() const; /** Add an incidence to calendar. @return true on success, false on error. */ virtual bool addIncidence( Incidence * ); // Adds an incidence and all relatedto incidences to the cal void addIncidenceBranch( Incidence * ); /** Return filtered list of all incidences of this calendar. */ - virtual QPtrList<Incidence> incidences(); + virtual Q3PtrList<Incidence> incidences(); /** Return unfiltered list of all incidences of this calendar. */ - virtual QPtrList<Incidence> rawIncidences(); + virtual Q3PtrList<Incidence> rawIncidences(); /** Adds a Event to this calendar object. @param anEvent a pointer to the event to add @return true on success, false on error. */ virtual bool addEventNoDup( Event *event ) = 0; virtual bool addAnniversaryNoDup( Event *event ) = 0; virtual bool addEvent( Event *anEvent ) = 0; /** Delete event from calendar. */ virtual void deleteEvent( Event * ) = 0; /** Retrieves an event on the basis of the unique string ID. */ virtual Event *event( const QString &UniqueStr ) = 0; virtual Event *event( QString, QString ) = 0; /** Builds and then returns a list of all events that match for the date specified. useful for dayView, etc. etc. The calendar filter is applied. */ - QPtrList<Event> events( const QDate &date, bool sorted = false); + Q3PtrList<Event> events( const QDate &date, bool sorted = false); /** Get events, which occur on the given date. The calendar filter is applied. */ - QPtrList<Event> events( const QDateTime &qdt ); + Q3PtrList<Event> events( const QDateTime &qdt ); /** Get events in a range of dates. If inclusive is set to true, only events are returned, which are completely included in the range. The calendar filter is applied. */ - QPtrList<Event> events( const QDate &start, const QDate &end, + Q3PtrList<Event> events( const QDate &start, const QDate &end, bool inclusive = false); /** Return filtered list of all events in calendar. */ - virtual QPtrList<Event> events(); + virtual Q3PtrList<Event> events(); /** Return unfiltered list of all events in calendar. */ - virtual QPtrList<Event> rawEvents() = 0; + virtual Q3PtrList<Event> rawEvents() = 0; /** Add a todo to the todolist. @return true on success, false on error. */ virtual bool addTodo( Todo *todo ) = 0; virtual bool addTodoNoDup( Todo *todo ) = 0; /** Remove a todo from the todolist. */ virtual void deleteTodo( Todo * ) = 0; virtual void deleteJournal( Journal * ) = 0; /** Return filterd list of todos. */ - virtual QPtrList<Todo> todos(); + virtual Q3PtrList<Todo> todos(); /** Searches todolist for an event with this unique string identifier, returns a pointer or null. */ virtual Todo *todo( const QString &uid ) = 0; virtual Todo *todo( QString, QString ) = 0; /** Returns list of todos due on the specified date. */ - virtual QPtrList<Todo> todos( const QDate &date ) = 0; + virtual Q3PtrList<Todo> todos( const QDate &date ) = 0; /** Return unfiltered list of todos. */ - virtual QPtrList<Todo> rawTodos() = 0; + virtual Q3PtrList<Todo> rawTodos() = 0; /** Add a Journal entry to calendar. @return true on success, false on error. */ virtual bool addJournal( Journal * ) = 0; /** Return Journal for given date. */ virtual Journal *journal( const QDate & ) = 0; - virtual QPtrList<Journal> journals4Date( const QDate & ) = 0; + virtual Q3PtrList<Journal> journals4Date( const QDate & ) = 0; /** Return Journal with given UID. */ virtual Journal *journal( const QString &UID ) = 0; /** Return list of all Journal entries. */ - virtual QPtrList<Journal> journals() = 0; + virtual Q3PtrList<Journal> journals() = 0; /** Searches all incidence types for an incidence with this unique string identifier, returns a pointer or null. */ Incidence* incidence( const QString&UID ); /** Setup relations for an incidence. */ virtual void setupRelations( Incidence * ); /** Remove all relations to an incidence */ virtual void removeRelations( Incidence * ); /** Set calendar filter, which filters events for the events() functions. The Filter object is owned by the caller. */ void setFilter( CalFilter * ); /** Return calendar filter. */ CalFilter *filter(); virtual QDateTime nextAlarm( int daysTo ) = 0; virtual QString nextSummary( ) const = 0; virtual void reInitAlarmSettings() = 0; virtual QDateTime nextAlarmEventDateTime() const = 0; virtual void checkAlarmForIncidence( Incidence *, bool ) = 0; /** Return all alarms, which ocur in the given time interval. */ virtual Alarm::List alarms( const QDateTime &from, const QDateTime &to ) = 0; class Observer { public: virtual void calendarModified( bool, Calendar * ) = 0; }; void registerObserver( Observer * ); void setModified( bool ); /** Set product id returned by loadedProductId(). This function is only useful for the calendar loading code. */ void setLoadedProductId( const QString & ); /** Return product id taken from file that has been loaded. Returns QString::null, if no calendar has been loaded. */ QString loadedProductId(); int defaultCalendar(); void setDontDeleteIncidencesOnClose (); public slots: void setDefaultCalendar( int ); virtual void setCalendarEnabled( int id, bool enable ) = 0; virtual void setAllCalendarEnabled( bool enable ) = 0; virtual void setAlarmEnabled( int id, bool enable ) = 0; virtual void setReadOnly( int id, bool enable ) = 0; virtual void setDefaultCalendarEnabledOnly() = 0; virtual void setCalendarRemove( int id ) = 0; virtual void getIncidenceCount( int calId, int& events, int & todos, int & journals) = 0; signals: void calendarChanged(); void calendarSaved(); void calendarLoaded(); void addAlarm(const QDateTime &qdt, const QString ¬i ); void removeAlarm(const QDateTime &qdt, const QString ¬i ); protected: /** Get unfiltered events, which occur on the given date. */ - virtual QPtrList<Event> rawEventsForDate( const QDateTime &qdt ) = 0; + virtual Q3PtrList<Event> rawEventsForDate( const QDateTime &qdt ) = 0; /** Get unfiltered events, which occur on the given date. */ - virtual QPtrList<Event> rawEventsForDate( const QDate &date, + virtual Q3PtrList<Event> rawEventsForDate( const QDate &date, bool sorted = false ) = 0; /** Get events in a range of dates. If inclusive is set to true, only events are returned, which are completely included in the range. */ - virtual QPtrList<Event> rawEvents( const QDate &start, const QDate &end, + virtual Q3PtrList<Event> rawEvents( const QDate &start, const QDate &end, bool inclusive = false ) = 0; Incidence *mNextAlarmIncidence; Incidence *mUndoIncidence; int mDefaultCalendar; bool mDeleteIncidencesOnClose; private: void init(); QString mOwner; // who the calendar belongs to QString mOwnerEmail; // email address of the owner int mTimeZone; // timezone OFFSET from GMT (MINUTES) bool mLocalTime; // use local time, not UTC or a time zone CalFilter *mFilter; CalFilter *mDefaultFilter; QString mTimeZoneId; Observer *mObserver; bool mNewObserver; bool mModified; QString mLoadedProductId; // This list is used to put together related todos - QDict<Incidence> mOrphans; - QDict<Incidence> mOrphanUids; + Q3Dict<Incidence> mOrphans; + Q3Dict<Incidence> mOrphanUids; }; } #endif diff --git a/libkcal/calendarlocal.cpp b/libkcal/calendarlocal.cpp index ce3cd09..cb52b7c 100644 --- a/libkcal/calendarlocal.cpp +++ b/libkcal/calendarlocal.cpp @@ -1,1149 +1,1149 @@ /* This file is part of libkcal. Copyright (c) 1998 Preston Brown Copyright (c) 2001,2003 Cornelius Schumacher <schumacher@kde.org> 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #include <qdatetime.h> #include <qstring.h> -#include <qptrlist.h> +#include <q3ptrlist.h> #include <kdebug.h> #include <kconfig.h> #include <kglobal.h> #include <klocale.h> #include "vcaldrag.h" #include "vcalformat.h" #include "icalformat.h" #include "exceptions.h" #include "incidence.h" #include "journal.h" #include "filestorage.h" #include "calfilter.h" #include "calendarlocal.h" // #ifndef DESKTOP_VERSION // #include <qtopia/alarmserver.h> // #endif using namespace KCal; CalendarLocal::CalendarLocal() : Calendar() { init(); } CalendarLocal::CalendarLocal(const QString &timeZoneId) : Calendar(timeZoneId) { init(); } void CalendarLocal::init() { mNextAlarmIncidence = 0; } CalendarLocal::~CalendarLocal() { registerObserver( 0 ); if ( mDeleteIncidencesOnClose ) close(); } bool CalendarLocal::mergeCalendarFile( QString name ) { CalendarLocal calendar( timeZoneId() ); calendar.setDefaultCalendar( 1 ); if ( calendar.load( name ) ) { mergeCalendar( &calendar ); return true; } return false; } Todo* CalendarLocal::todoForUid( const QString& uid, bool doNotCheckDuplicates, bool enabledOnly,int * isDup ) { int calID = 0; if ( isDup && *isDup > 0 ) calID = *isDup; Todo *todo;; Todo *retVal = 0; for ( todo = mTodoList.first(); todo; todo = mTodoList.next() ) { if ( todo->uid() == uid ) { if( calID ) { if ( todo->calID() != calID ) continue; } else { if ( enabledOnly ) { if ( !todo->calEnabled() ) { if ( isDup ) *isDup = todo->calID(); continue; } } } if ( doNotCheckDuplicates ) return todo; if ( retVal ) { if ( retVal->calID() > todo->calID() ) { if ( isDup ) *isDup = retVal->calID(); retVal = todo; } } else { retVal = todo; } } } return retVal; } //if ( isDup) and * isDup == 0: store duplicate found cal id in isDup //if ( isDup) and * isDup > 0: search only in calendar with ID *isDup, ignore enabledOnly Incidence* CalendarLocal::incidenceForUid( const QString& uid , bool doNotCheckDuplicates, bool enabledOnly, int * isDup ) { int calID = 0; if ( isDup && *isDup > 0 ) calID = *isDup; Incidence *retVal = todoForUid( uid , doNotCheckDuplicates,enabledOnly, isDup ); if ( retVal ) return retVal; Event *event; for ( event = mEventList.first(); event; event = mEventList.next() ) { if ( event->uid() == uid ) { if( calID ) { if ( event->calID() != calID ) continue; } else { if ( enabledOnly ) { if ( !event->calEnabled() ) { if ( isDup ) *isDup =event->calID() ; continue; } } } if ( doNotCheckDuplicates ) return event; if ( retVal ) { if ( retVal->calID() > event->calID() ) { if ( isDup ) *isDup = retVal->calID(); retVal = event; } } else { retVal = event; } } } if ( retVal ) return retVal; for ( Journal *it = mJournalList.first(); it; it = mJournalList.next() ) if ( it->uid() == uid ) { if( calID ) { if ( event->calID() != calID ) continue; } else { if ( enabledOnly ) { if ( !it->calEnabled() ) { if ( isDup ) *isDup = it->calID(); continue; } } } if ( doNotCheckDuplicates ) return it; if ( retVal ) { if ( retVal->calID() > it->calID() ) { if ( isDup ) *isDup = retVal->calID(); retVal = it; } } else { retVal = it; } } return retVal; } bool CalendarLocal::mergeCalendar( Calendar* remote ) { // 1 look for raw inc in local // if inc not in remote, delete in local // 2 look for raw inc in remote // if inc in local, replace it // if not in local, add it to default calendar - QPtrList<Incidence> localInc = rawIncidences(); + Q3PtrList<Incidence> localInc = rawIncidences(); Incidence* inL = localInc.first(); while ( inL ) { if ( ! inL->isReadOnly () ) if ( !remote->incidenceForUid( inL->uid(), true )) deleteIncidence( inL ); inL = localInc.next(); } - QPtrList<Incidence> er = remote->rawIncidences(); + Q3PtrList<Incidence> er = remote->rawIncidences(); Incidence* inR = er.first(); while ( inR ) { inL = incidenceForUid( inR->uid(),false ); if ( inL ) { if ( ! inL->isReadOnly () || inL->uid().left(15) == QString("last-syncEvent-") ) { int calID = inL->calID(); deleteIncidence( inL ); inL = inR->clone(); inL->setCalID_block( calID ); addIncidence( inL ); } } else { inL = inR->clone(); inL->setCalID_block( 0 );// add to default cal addIncidence( inL ); } inR = er.next(); } return true; } bool CalendarLocal::addCalendarFile( QString name, int id ) { CalendarLocal calendar( timeZoneId() ); calendar.setDefaultCalendar( id ); if ( calendar.load( name ) ) { addCalendar( &calendar ); return true; } return false; } void CalendarLocal::setSyncEventsEnabled() { Event * ev; ev = mEventList.first(); while ( ev ) { if ( ev->uid().left(15) == QString("last-syncEvent-") ) ev->setCalEnabled( true ); ev = mEventList.next(); } } void CalendarLocal::setSyncEventsReadOnly() { Event * ev; ev = mEventList.first(); while ( ev ) { if ( ev->uid().left(15) == QString("last-syncEvent-") ) { ev->setReadOnly( true ); } ev = mEventList.next(); } } void CalendarLocal::addCalendar( Calendar* cal ) { cal->setDontDeleteIncidencesOnClose(); setSyncEventsEnabled(); - QPtrList<Incidence> incList; + Q3PtrList<Incidence> incList; { - QPtrList<Event> EventList = cal->rawEvents(); + Q3PtrList<Event> EventList = cal->rawEvents(); Event * ev = EventList.first(); while ( ev ) { if ( ev->uid().left( 15 ) == QString("last-syncEvent-") ) { ev->setCalID_block( 1 ); } Event * se = event( ev->uid() ); if ( se ) incList.append( se ); ev->unRegisterObserver( cal ); ev->registerObserver( this ); mEventList.append( ev ); ev = EventList.next(); } } { - QPtrList<Todo> TodoList = cal->rawTodos(); + Q3PtrList<Todo> TodoList = cal->rawTodos(); Todo * ev = TodoList.first(); while ( ev ) { ev->resetRelatedTo(); Todo * se = todo( ev->uid() ); if ( se ) deleteTodo( se ); ev = TodoList.next(); } //TodoList = cal->rawTodos(); ev = TodoList.first(); while ( ev ) { ev->unRegisterObserver( cal ); ev->registerObserver( this ); mTodoList.append( ev ); setupRelations( ev ); ev = TodoList.next(); } } { - QPtrList<Journal> JournalList = cal->journals(); + Q3PtrList<Journal> JournalList = cal->journals(); Journal * ev = JournalList.first(); while ( ev ) { Journal * se = journal( ev->uid() ); if ( se ) incList.append( se ); ev->unRegisterObserver( cal ); ev->registerObserver( this ); mJournalList.append( ev ); ev = JournalList.next(); } } { for (Incidence * inc = incList.first(); inc; inc = incList.next() ) { deleteIncidence ( inc ); } } setModified( true ); } bool CalendarLocal::load( const QString &fileName ) { FileStorage storage( this, fileName ); return storage.load(); } bool CalendarLocal::save( const QString &fileName, CalFormat *format ) { FileStorage storage( this, fileName, format ); return storage.save(); } void CalendarLocal::stopAllTodos() { for ( Todo *it = mTodoList.first(); it; it = mTodoList.next() ) it->setRunning( false ); } void CalendarLocal::close() { Todo * i; for( i = mTodoList.first(); i; i = mTodoList.next() ) i->setRunning(false); mEventList.setAutoDelete( true ); mTodoList.setAutoDelete( true ); mJournalList.setAutoDelete( true ); mEventList.clear(); mTodoList.clear(); mJournalList.clear(); mEventList.setAutoDelete( false ); mTodoList.setAutoDelete( false ); mJournalList.setAutoDelete( false ); setModified( false ); } bool CalendarLocal::addAnniversaryNoDup( Event *event ) { QString cat; bool isBirthday = true; if( event->categoriesStr() == i18n( "Anniversary" ) ) { isBirthday = false; cat = i18n( "Anniversary" ); } else if( event->categoriesStr() == i18n( "Birthday" ) ) { isBirthday = true; cat = i18n( "Birthday" ); } else { qDebug("addAnniversaryNoDup called without fitting category! "); return false; } Event * eve; for ( eve = mEventList.first(); eve ; eve = mEventList.next() ) { if ( !(eve->categories().contains( cat ) )) continue; // now we have an event with fitting category if ( eve->dtStart().date() != event->dtStart().date() ) continue; // now we have an event with fitting category+date if ( eve->summary() != event->summary() ) continue; // now we have an event with fitting category+date+summary return false; } return addEvent( event ); } bool CalendarLocal::addEventNoDup( Event *event ) { Event * eve; for ( eve = mEventList.first(); eve ; eve = mEventList.next() ) { if ( *eve == *event ) { //qDebug("CalendarLocal::Duplicate event found! Not inserted! "); return false; } } return addEvent( event ); } bool CalendarLocal::addEvent( Event *event ) { insertEvent( event ); event->registerObserver( this ); setModified( true ); if ( event->calID() == 0 ) event->setCalID_block( mDefaultCalendar ); event->setCalEnabled( true ); return true; } void CalendarLocal::deleteEvent( Event *event ) { clearUndo(event); if ( mEventList.removeRef( event ) ) { setModified( true ); } } Event *CalendarLocal::event( const QString &uid ) { Event *event; Event *retVal = 0; for ( event = mEventList.first(); event; event = mEventList.next() ) { if ( event->calEnabled() && event->uid() == uid ) { if ( retVal ) { if ( retVal->calID() > event->calID() ) { retVal = event; } } else { retVal = event; } } } return retVal; } bool CalendarLocal::addTodoNoDup( Todo *todo ) { Todo * eve; for ( eve = mTodoList.first(); eve ; eve = mTodoList.next() ) { if ( *eve == *todo ) { //qDebug("duplicate todo found! not inserted! "); return false; } } return addTodo( todo ); } bool CalendarLocal::addTodo( Todo *todo ) { mTodoList.append( todo ); todo->registerObserver( this ); // Set up subtask relations setupRelations( todo ); setModified( true ); if ( todo->calID() == 0 ) todo->setCalID_block( mDefaultCalendar ); todo->setCalEnabled( true ); return true; } void CalendarLocal::deleteTodo( Todo *todo ) { QString uid = todo->uid(); // Handle orphaned children removeRelations( todo ); clearUndo(todo); if ( mTodoList.removeRef( todo ) ) { setModified( true ); } Todo* dup = todoForUid( uid ); if ( dup ) setupRelations( dup ); } -QPtrList<Todo> CalendarLocal::rawTodos() +Q3PtrList<Todo> CalendarLocal::rawTodos() { - QPtrList<Todo> el; + Q3PtrList<Todo> el; for ( Todo *it = mTodoList.first(); it; it = mTodoList.next() ) if ( it->calEnabled() ) el.append( it ); return el; } Todo *CalendarLocal::todo( QString syncProf, QString id ) { Todo *todo; for ( todo = mTodoList.first(); todo; todo = mTodoList.next() ) { if ( todo->calEnabled() && todo->getID( syncProf ) == id ) return todo; } return 0; } void CalendarLocal::removeSyncInfo( QString syncProfile) { - QPtrList<Incidence> all = rawIncidences() ; + Q3PtrList<Incidence> all = rawIncidences() ; Incidence *inc; for ( inc = all.first(); inc; inc = all.next() ) { inc->removeID( syncProfile ); } if ( syncProfile.isEmpty() ) { - QPtrList<Event> el; + Q3PtrList<Event> el; Event *todo; for ( todo = mEventList.first(); todo; todo = mEventList.next() ) { if ( todo->uid().left( 15 ) == QString("last-syncEvent-") ) el.append( todo ); } for ( todo = el.first(); todo; todo = el.next() ) { deleteIncidence ( todo ); } } else { Event *lse = event( "last-syncEvent-"+ syncProfile); if ( lse ) deleteIncidence ( lse ); } } -QPtrList<Event> CalendarLocal::getExternLastSyncEvents() +Q3PtrList<Event> CalendarLocal::getExternLastSyncEvents() { - QPtrList<Event> el; + Q3PtrList<Event> el; Event *todo; for ( todo = mEventList.first(); todo; todo = mEventList.next() ) { if ( todo->uid().left( 15 ) == QString("last-syncEvent-") ) if ( todo->summary().left(3) == "E: " ) el.append( todo ); } return el; } Event *CalendarLocal::event( QString syncProf, QString id ) { Event *todo; for ( todo = mEventList.first(); todo; todo = mEventList.next() ) { if ( todo->calEnabled() && todo->getID( syncProf ) == id ) return todo; } return 0; } Todo *CalendarLocal::todo( const QString &uid ) { Todo *todo; Todo *retVal = 0; for ( todo = mTodoList.first(); todo; todo = mTodoList.next() ) { if ( todo->calEnabled() && todo->uid() == uid ) { if ( retVal ) { if ( retVal->calID() > todo->calID() ) { retVal = todo; } } else { retVal = todo; } } } return retVal; } void CalendarLocal::getIncidenceCount( int calId, int& events, int & todos, int & journals) { events = 0; todos = 0; journals = 0; { Todo *todo; for ( todo = mTodoList.first(); todo; todo = mTodoList.next() ) { if ( todo->calID() == calId ) ++todos; } } { Event *todo; for ( todo = mEventList.first(); todo; todo = mEventList.next() ) { if ( todo->calID() == calId ) ++events; } } for ( Journal *it = mJournalList.first(); it; it = mJournalList.next() ) if ( it->calID() == calId ) ++journals; } QString CalendarLocal::nextSummary() const { return mNextSummary; } QDateTime CalendarLocal::nextAlarmEventDateTime() const { return mNextAlarmEventDateTime; } void CalendarLocal::checkAlarmForIncidence( Incidence * incidence, bool deleted) { //mNextAlarmIncidence //mNextAlarmDateTime //return mNextSummary; //return mNextAlarmEventDateTime; bool newNextAlarm = false; bool computeNextAlarm = false; bool ok; int offset; QDateTime nextA; // QString nextSum; //QDateTime nextEvent; if ( mNextAlarmIncidence == 0 || incidence == 0 ) { computeNextAlarm = true; } else { if ( ! deleted ) { nextA = incidence->getNextAlarmDateTime(& ok, &offset, QDateTime::currentDateTime() ) ; if ( ok ) { if ( nextA < mNextAlarmDateTime ) { deRegisterAlarm(); mNextAlarmDateTime = nextA; mNextSummary = incidence->summary(); mNextAlarmEventDateTime = nextA.addSecs(offset ) ; mNextAlarmEventDateTimeString = KGlobal::locale()->formatDateTime(mNextAlarmEventDateTime); newNextAlarm = true; mNextAlarmIncidence = incidence; } else { if ( incidence == mNextAlarmIncidence ) { computeNextAlarm = true; } } } else { if ( mNextAlarmIncidence == incidence ) { computeNextAlarm = true; } } } else { // deleted if ( incidence == mNextAlarmIncidence ) { computeNextAlarm = true; } } } if ( computeNextAlarm ) { deRegisterAlarm(); nextA = nextAlarm( 1000 ); if (! mNextAlarmIncidence ) { return; } newNextAlarm = true; } if ( newNextAlarm ) registerAlarm(); } QString CalendarLocal:: getAlarmNotification() { QString ret; // this should not happen if (! mNextAlarmIncidence ) return "cal_alarm"+ mNextSummary.left( 25 )+"\n"+mNextAlarmEventDateTimeString; Alarm* alarm = mNextAlarmIncidence->alarms().first(); if ( alarm->type() == Alarm::Procedure ) { ret = "proc_alarm" + alarm->programFile()+"+++"; } else { ret = "audio_alarm" +alarm->audioFile() +"+++"; } ret += "cal_alarm"+ mNextSummary.left( 25 ); if ( mNextSummary.length() > 25 ) ret += "\n" + mNextSummary.mid(25, 25 ); ret+= "\n"+mNextAlarmEventDateTimeString; return ret; } void CalendarLocal::registerAlarm() { mLastAlarmNotificationString = getAlarmNotification(); // qDebug("++ register Alarm %s %s",mNextAlarmDateTime.toString().latin1(), mLastAlarmNotificationString.latin1() ); emit addAlarm ( mNextAlarmDateTime, mLastAlarmNotificationString ); // #ifndef DESKTOP_VERSION // AlarmServer::addAlarm ( mNextAlarmDateTime,"koalarm", mLastAlarmNotificationString.latin1() ); // #endif } void CalendarLocal::deRegisterAlarm() { if ( mLastAlarmNotificationString.isNull() ) return; //qDebug("-- deregister Alarm %s ", mLastAlarmNotificationString.latin1() ); emit removeAlarm ( mNextAlarmDateTime, mLastAlarmNotificationString ); mNextAlarmEventDateTime = QDateTime(); // #ifndef DESKTOP_VERSION // AlarmServer::deleteAlarm (mNextAlarmDateTime ,"koalarm" ,mLastAlarmNotificationString.latin1() ); // #endif } -QPtrList<Todo> CalendarLocal::todos( const QDate &date ) +Q3PtrList<Todo> CalendarLocal::todos( const QDate &date ) { - QPtrList<Todo> todos; + Q3PtrList<Todo> todos; Todo *todo; for ( todo = mTodoList.first(); todo; todo = mTodoList.next() ) { if ( !todo->calEnabled() ) continue; if ( todo->hasDueDate() && todo->dtDue().date() == date ) { todos.append( todo ); } } filter()->apply( &todos ); return todos; } void CalendarLocal::reInitAlarmSettings() { if ( !mNextAlarmIncidence ) { nextAlarm( 1000 ); } deRegisterAlarm(); mNextAlarmIncidence = 0; checkAlarmForIncidence( 0, false ); } QDateTime CalendarLocal::nextAlarm( int daysTo ) { QDateTime nextA = QDateTime::currentDateTime().addDays( daysTo ); QDateTime start = QDateTime::currentDateTime().addSecs( 30 ); QDateTime next; Event *e; bool ok; bool found = false; int offset; mNextAlarmIncidence = 0; for( e = mEventList.first(); e; e = mEventList.next() ) { if ( !e->calEnabled() ) continue; next = e->getNextAlarmDateTime(& ok, &offset, QDateTime::currentDateTime() ) ; if ( ok ) { if ( next < nextA ) { nextA = next; found = true; mNextSummary = e->summary(); mNextAlarmEventDateTime = next.addSecs(offset ) ; mNextAlarmIncidence = (Incidence *) e; } } } Todo *t; for( t = mTodoList.first(); t; t = mTodoList.next() ) { if ( !t->calEnabled() ) continue; next = t->getNextAlarmDateTime(& ok, &offset, QDateTime::currentDateTime() ) ; if ( ok ) { if ( next < nextA ) { nextA = next; found = true; mNextSummary = t->summary(); mNextAlarmEventDateTime = next.addSecs(offset ); mNextAlarmIncidence = (Incidence *) t; } } } if ( mNextAlarmIncidence ) { mNextAlarmEventDateTimeString = KGlobal::locale()->formatDateTime(mNextAlarmEventDateTime); mNextAlarmDateTime = nextA; } return nextA; } Alarm::List CalendarLocal::alarmsTo( const QDateTime &to ) { return alarms( QDateTime( QDate( 1900, 1, 1 ) ), to ); } Alarm::List CalendarLocal::alarms( const QDateTime &from, const QDateTime &to ) { Alarm::List alarms; Event *e; for( e = mEventList.first(); e; e = mEventList.next() ) { if ( !e->calEnabled() ) continue; if ( e->doesRecur() ) appendRecurringAlarms( alarms, e, from, to ); else appendAlarms( alarms, e, from, to ); } Todo *t; for( t = mTodoList.first(); t; t = mTodoList.next() ) { if ( !t->calEnabled() ) continue; appendAlarms( alarms, t, from, to ); } return alarms; } void CalendarLocal::appendAlarms( Alarm::List &alarms, Incidence *incidence, const QDateTime &from, const QDateTime &to ) { - QPtrList<Alarm> alarmList = incidence->alarms(); + Q3PtrList<Alarm> alarmList = incidence->alarms(); Alarm *alarm; for( alarm = alarmList.first(); alarm; alarm = alarmList.next() ) { // kdDebug(5800) << "CalendarLocal::appendAlarms() '" << alarm->text() // << "': " << alarm->time().toString() << " - " << alarm->enabled() << endl; if ( alarm->enabled() ) { if ( alarm->time() >= from && alarm->time() <= to ) { alarms.append( alarm ); } } } } void CalendarLocal::appendRecurringAlarms( Alarm::List &alarms, Incidence *incidence, const QDateTime &from, const QDateTime &to ) { - QPtrList<Alarm> alarmList = incidence->alarms(); + Q3PtrList<Alarm> alarmList = incidence->alarms(); Alarm *alarm; QDateTime qdt; for( alarm = alarmList.first(); alarm; alarm = alarmList.next() ) { if (incidence->recursOn(from.date())) { qdt.setTime(alarm->time().time()); qdt.setDate(from.date()); } else qdt = alarm->time(); // qDebug("1 %s %s %s", qdt.toString().latin1(), from.toString().latin1(), to.toString().latin1()); if ( alarm->enabled() ) { if ( qdt >= from && qdt <= to ) { alarms.append( alarm ); } } } } /****************************** PROTECTED METHODS ****************************/ // after changes are made to an event, this should be called. void CalendarLocal::update( IncidenceBase *incidence ) { incidence->setSyncStatus( Event::SYNCMOD ); incidence->setLastModified( QDateTime::currentDateTime() ); // we should probably update the revision number here, // or internally in the Event itself when certain things change. // need to verify with ical documentation. setModified( true ); } void CalendarLocal::insertEvent( Event *event ) { if ( mEventList.findRef( event ) < 0 ) mEventList.append( event ); } -QPtrList<Event> CalendarLocal::rawEventsForDate( const QDate &qd, bool sorted ) +Q3PtrList<Event> CalendarLocal::rawEventsForDate( const QDate &qd, bool sorted ) { - QPtrList<Event> eventList; + Q3PtrList<Event> eventList; Event *event; for( event = mEventList.first(); event; event = mEventList.next() ) { if ( !event->calEnabled() ) continue; if ( event->doesRecur() ) { if ( event->isMultiDay() ) { int extraDays = event->dtStart().date().daysTo( event->dtEnd().date() ); int i; for ( i = 0; i <= extraDays; i++ ) { if ( event->recursOn( qd.addDays( -i ) ) ) { eventList.append( event ); break; } } } else { if ( event->recursOn( qd ) ) eventList.append( event ); } } else { if ( event->dtStart().date() <= qd && event->dtEnd().date() >= qd ) { eventList.append( event ); } } } if ( !sorted ) { return eventList; } // kdDebug(5800) << "Sorting events for date\n" << endl; // now, we have to sort it based on dtStart.time() - QPtrList<Event> eventListSorted; + Q3PtrList<Event> eventListSorted; Event *sortEvent; for ( event = eventList.first(); event; event = eventList.next() ) { sortEvent = eventListSorted.first(); int i = 0; while ( sortEvent && event->dtStart().time()>=sortEvent->dtStart().time() ) { i++; sortEvent = eventListSorted.next(); } eventListSorted.insert( i, event ); } return eventListSorted; } -QPtrList<Event> CalendarLocal::rawEvents( const QDate &start, const QDate &end, +Q3PtrList<Event> CalendarLocal::rawEvents( const QDate &start, const QDate &end, bool inclusive ) { Event *event = 0; - QPtrList<Event> eventList; + Q3PtrList<Event> eventList; // Get non-recurring events for( event = mEventList.first(); event; event = mEventList.next() ) { if ( !event->calEnabled() ) continue; if ( event->doesRecur() ) { QDate rStart = event->dtStart().date(); bool found = false; if ( inclusive ) { if ( rStart >= start && rStart <= end ) { // Start date of event is in range. Now check for end date. // if duration is negative, event recurs forever, so do not include it. if ( event->recurrence()->duration() == 0 ) { // End date set QDate rEnd = event->recurrence()->endDate(); if ( rEnd >= start && rEnd <= end ) { // End date within range found = true; } } else if ( event->recurrence()->duration() > 0 ) { // Duration set // TODO: Calculate end date from duration. Should be done in Event // For now exclude all events with a duration. } } } else { bool founOne; - QDate next = event->getNextOccurence( start, &founOne ).date(); + QDate next = event->getNextOccurence( (QDateTime)start, &founOne ).date(); if ( founOne ) { if ( next <= end ) { found = true; } } /* // crap !!! if ( rStart <= end ) { // Start date not after range if ( rStart >= start ) { // Start date within range found = true; } else if ( event->recurrence()->duration() == -1 ) { // Recurs forever found = true; } else if ( event->recurrence()->duration() == 0 ) { // End date set QDate rEnd = event->recurrence()->endDate(); if ( rEnd >= start && rEnd <= end ) { // End date within range found = true; } } else { // Duration set // TODO: Calculate end date from duration. Should be done in Event // For now include all events with a duration. found = true; } } */ } if ( found ) eventList.append( event ); } else { QDate s = event->dtStart().date(); QDate e = event->dtEnd().date(); if ( inclusive ) { if ( s >= start && e <= end ) { eventList.append( event ); } } else { if ( ( e >= start && s <= end ) ) { eventList.append( event ); } } } } return eventList; } -QPtrList<Event> CalendarLocal::rawEventsForDate( const QDateTime &qdt ) +Q3PtrList<Event> CalendarLocal::rawEventsForDate( const QDateTime &qdt ) { return rawEventsForDate( qdt.date() ); } -QPtrList<Event> CalendarLocal::rawEvents() +Q3PtrList<Event> CalendarLocal::rawEvents() { - QPtrList<Event> el; + Q3PtrList<Event> el; for ( Event *it = mEventList.first(); it; it = mEventList.next() ) if ( it->calEnabled() ) el.append( it ); return el; } bool CalendarLocal::addJournal(Journal *journal) { mJournalList.append(journal); journal->registerObserver( this ); setModified( true ); if ( journal->calID() == 0 ) journal->setCalID_block( mDefaultCalendar ); journal->setCalEnabled( true ); return true; } void CalendarLocal::deleteJournal( Journal *journal ) { clearUndo(journal); if ( mJournalList.removeRef(journal) ) { setModified( true ); } } -QPtrList<Journal> CalendarLocal::journals4Date( const QDate & date ) +Q3PtrList<Journal> CalendarLocal::journals4Date( const QDate & date ) { - QPtrList<Journal> el; + Q3PtrList<Journal> el; for ( Journal *it = mJournalList.first(); it; it = mJournalList.next() ) if ( it->calEnabled() && it->dtStart().date() == date) el.append( it ); return el; } Journal *CalendarLocal::journal( const QDate &date ) { // kdDebug(5800) << "CalendarLocal::journal() " << date.toString() << endl; for ( Journal *it = mJournalList.first(); it; it = mJournalList.next() ) if ( it->calEnabled() && it->dtStart().date() == date ) return it; return 0; } Journal *CalendarLocal::journal( const QString &uid ) { Journal * retVal = 0; for ( Journal *it = mJournalList.first(); it; it = mJournalList.next() ) if ( it->calEnabled() && it->uid() == uid ) { if ( retVal ) { if ( retVal->calID() > it->calID() ) { retVal = it; } } else { retVal = it; } } return retVal; } -QPtrList<Journal> CalendarLocal::journals() +Q3PtrList<Journal> CalendarLocal::journals() { - QPtrList<Journal> el; + Q3PtrList<Journal> el; for ( Journal *it = mJournalList.first(); it; it = mJournalList.next() ) if ( it->calEnabled() ) el.append( it ); return el; } void CalendarLocal::setCalendarRemove( int id ) { { - QPtrList<Event> EventList = mEventList; + Q3PtrList<Event> EventList = mEventList; Event * ev = EventList.first(); while ( ev ) { if ( ev->calID() == id && ev->uid().left( 15 ) != QString("last-syncEvent-") ) deleteEvent( ev ); ev = EventList.next(); } } { - QPtrList<Todo> TodoList = mTodoList; + Q3PtrList<Todo> TodoList = mTodoList; Todo * ev = TodoList.first(); while ( ev ) { if ( ev->calID() == id ) deleteTodo( ev ); ev = TodoList.next(); } } { - QPtrList<Journal> JournalList = mJournalList; + Q3PtrList<Journal> JournalList = mJournalList; Journal * ev = JournalList.first(); while ( ev ) { if ( ev->calID() == id ) deleteJournal( ev ); ev = JournalList.next(); } } clearUndo(0); } void CalendarLocal::setAllCalendarEnabled( bool enable ) { for ( Journal *it = mJournalList.first(); it; it = mJournalList.next() ) it->setCalEnabled( enable ); for ( Event *it = mEventList.first(); it; it = mEventList.next() ) it->setCalEnabled( enable ); for ( Todo *it = mTodoList.first(); it; it = mTodoList.next() ) it->setCalEnabled( enable ); } void CalendarLocal::setCalendarEnabled( int id, bool enable ) { for ( Journal *it = mJournalList.first(); it; it = mJournalList.next() ) if ( it->calID() == id ) it->setCalEnabled( enable ); for ( Event *it = mEventList.first(); it; it = mEventList.next() ) if ( it->calID() == id ) it->setCalEnabled( enable ); for ( Todo *it = mTodoList.first(); it; it = mTodoList.next() ) if ( it->calID() == id ) it->setCalEnabled( enable ); } void CalendarLocal::setReadOnly( int id, bool enable ) { for ( Journal *it = mJournalList.first(); it; it = mJournalList.next() ) if ( it->calID() == id ) it->setReadOnly( enable ); for ( Event *it = mEventList.first(); it; it = mEventList.next() ) if ( it->calID() == id ) it->setReadOnly( enable ); for ( Todo *it = mTodoList.first(); it; it = mTodoList.next() ) if ( it->calID() == id ) it->setReadOnly( enable ); } void CalendarLocal::setAlarmEnabled( int id, bool enable ) { for ( Journal *it = mJournalList.first(); it; it = mJournalList.next() ) if ( it->calID() == id ) it->setAlarmEnabled( enable ); for ( Event *it = mEventList.first(); it; it = mEventList.next() ) if ( it->calID() == id ) it->setAlarmEnabled( enable ); for ( Todo *it = mTodoList.first(); it; it = mTodoList.next() ) if ( it->calID() == id ) it->setAlarmEnabled( enable ); reInitAlarmSettings(); } void CalendarLocal::setDefaultCalendarEnabledOnly() { for ( Journal *it = mJournalList.first(); it; it = mJournalList.next() ) it->setCalEnabled( it->calID() == mDefaultCalendar ); for ( Event *it = mEventList.first(); it; it = mEventList.next() ) it->setCalEnabled( it->calID() == mDefaultCalendar); for ( Todo *it = mTodoList.first(); it; it = mTodoList.next() ) it->setCalEnabled( it->calID() == mDefaultCalendar); } diff --git a/libkcal/calendarlocal.h b/libkcal/calendarlocal.h index 1ceabce..1df65c7 100644 --- a/libkcal/calendarlocal.h +++ b/libkcal/calendarlocal.h @@ -1,234 +1,236 @@ /* This file is part of libkcal. Copyright (c) 1998 Preston Brown Copyright (c) 2001,2003 Cornelius Schumacher <schumacher@kde.org> 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #ifndef KCAL_CALENDARLOCAL_H #define KCAL_CALENDARLOCAL_H #include "calendar.h" +//Added by qt3to4: +#include <Q3PtrList> namespace KCal { class CalFormat; /** This class provides a calendar stored as a local file. */ class CalendarLocal : public Calendar { public: /** Constructs a new calendar, with variables initialized to sane values. */ CalendarLocal(); /** Constructs a new calendar, with variables initialized to sane values. */ CalendarLocal( const QString &timeZoneId ); ~CalendarLocal(); void addCalendar( Calendar* ); bool addCalendarFile( QString name, int id ); bool mergeCalendarFile( QString name ); bool mergeCalendar( Calendar* cal ); Incidence* incidenceForUid( const QString& uid, bool doNotCheckDuplicates, bool enabledOnly = false,int * isDup = 0 ); Todo* todoForUid( const QString& uid, bool doNotCheckDuplicates = true, bool enabledOnly = false ,int * isDup = 0 ); void setSyncEventsReadOnly(); void setSyncEventsEnabled(); void stopAllTodos(); /** Loads a calendar on disk in vCalendar or iCalendar format into the current calendar. Any information already present is lost. @return true, if successfull, false on error. @param fileName the name of the calendar on disk. */ bool load( const QString &fileName ); /** Writes out the calendar to disk in the specified \a format. CalendarLocal takes ownership of the CalFormat object. @return true, if successfull, false on error. @param fileName the name of the file */ bool save( const QString &fileName, CalFormat *format = 0 ); /** Clears out the current calendar, freeing all used memory etc. etc. */ void close(); void save() {} /** Add Event to calendar. */ void removeSyncInfo( QString syncProfile); bool addAnniversaryNoDup( Event *event ); bool addEventNoDup( Event *event ); bool addEvent( Event *event ); /** Deletes an event from this calendar. */ void deleteEvent( Event *event ); /** Retrieves an event on the basis of the unique string ID. */ Event *event( const QString &uid ); /** Return unfiltered list of all events in calendar. */ - QPtrList<Event> rawEvents(); - QPtrList<Event> getExternLastSyncEvents(); + Q3PtrList<Event> rawEvents(); + Q3PtrList<Event> getExternLastSyncEvents(); /** Add a todo to the todolist. */ bool addTodo( Todo *todo ); bool addTodoNoDup( Todo *todo ); /** Remove a todo from the todolist. */ void deleteTodo( Todo * ); /** Searches todolist for an event with this unique string identifier, returns a pointer or null. */ Todo *todo( const QString &uid ); /** Return list of all todos. */ - QPtrList<Todo> rawTodos(); + Q3PtrList<Todo> rawTodos(); /** Returns list of todos due on the specified date. */ - QPtrList<Todo> todos( const QDate &date ); + Q3PtrList<Todo> todos( const QDate &date ); /** Return list of all todos. Workaround because compiler does not recognize function of base class. */ - QPtrList<Todo> todos() { return Calendar::todos(); } + Q3PtrList<Todo> todos() { return Calendar::todos(); } /** Add a Journal entry to calendar. */ bool addJournal( Journal * ); /** Remove a Journal from the calendar. */ void deleteJournal( Journal * ); /** Return Journal for given date. */ Journal *journal( const QDate & ); - QPtrList<Journal> journals4Date( const QDate & ); + Q3PtrList<Journal> journals4Date( const QDate & ); /** Return Journal with given UID. */ Journal *journal( const QString &uid ); /** Return list of all Journals stored in calendar. */ - QPtrList<Journal> journals(); + Q3PtrList<Journal> journals(); /** Return all alarms, which ocur in the given time interval. */ Alarm::List alarms( const QDateTime &from, const QDateTime &to ); /** Return all alarms, which ocur before given date. */ Alarm::List alarmsTo( const QDateTime &to ); QDateTime nextAlarm( int daysTo ) ; QDateTime nextAlarmEventDateTime() const; void checkAlarmForIncidence( Incidence *, bool deleted ) ; void registerAlarm(); void deRegisterAlarm(); QString getAlarmNotification(); QString nextSummary() const ; /** This method should be called whenever a Event is modified directly via it's pointer. It makes sure that the calendar is internally consistent. */ void update( IncidenceBase *incidence ); /** Builds and then returns a list of all events that match for the date specified. useful for dayView, etc. etc. */ - QPtrList<Event> rawEventsForDate( const QDate &date, bool sorted = false ); + Q3PtrList<Event> rawEventsForDate( const QDate &date, bool sorted = false ); /** Get unfiltered events for date \a qdt. */ - QPtrList<Event> rawEventsForDate( const QDateTime &qdt ); + Q3PtrList<Event> rawEventsForDate( const QDateTime &qdt ); /** Get unfiltered events in a range of dates. If inclusive is set to true, only events are returned, which are completely included in the range. */ - QPtrList<Event> rawEvents( const QDate &start, const QDate &end, + Q3PtrList<Event> rawEvents( const QDate &start, const QDate &end, bool inclusive = false ); Todo *todo( QString, QString ); Event *event( QString, QString ); void getIncidenceCount( int calId, int& events, int & todos, int & journals); public slots: void setCalendarEnabled( int id, bool enable ); void setAlarmEnabled( int id, bool enable ); void setReadOnly( int id, bool enable ); void setDefaultCalendarEnabledOnly(); void setCalendarRemove( int id ); void setAllCalendarEnabled( bool enable ); protected: // Event* mNextAlarmEvent; QString mNextSummary; QString mNextAlarmEventDateTimeString; QString mLastAlarmNotificationString; QDateTime mNextAlarmEventDateTime; QDateTime mNextAlarmDateTime; void reInitAlarmSettings(); /** Notification function of IncidenceBase::Observer. */ void incidenceUpdated( IncidenceBase *i ) { update( i ); } /** inserts an event into its "proper place" in the calendar. */ void insertEvent( Event *event ); /** Append alarms of incidence in interval to list of alarms. */ void appendAlarms( Alarm::List &alarms, Incidence *incidence, const QDateTime &from, const QDateTime &to ); /** Append alarms of recurring events in interval to list of alarms. */ void appendRecurringAlarms( Alarm::List &alarms, Incidence *incidence, const QDateTime &from, const QDateTime &to ); private: void init(); - QPtrList<Event> mEventList; - QPtrList<Todo> mTodoList; - QPtrList<Journal> mJournalList; + Q3PtrList<Event> mEventList; + Q3PtrList<Todo> mTodoList; + Q3PtrList<Journal> mJournalList; }; } #endif diff --git a/libkcal/calfilter.cpp b/libkcal/calfilter.cpp index 72f70c2..fa1dbd5 100644 --- a/libkcal/calfilter.cpp +++ b/libkcal/calfilter.cpp @@ -1,221 +1,223 @@ /* This file is part of libkcal. Copyright (c) 2001 Cornelius Schumacher <schumacher@kde.org> 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #include <kdebug.h> #include "calfilter.h" +//Added by qt3to4: +#include <Q3PtrList> using namespace KCal; CalFilter::CalFilter() { mEnabled = true; mCriteria = ShowPublic | ShowPrivate| ShowConfidential ; } CalFilter::CalFilter(const QString &name) { mName = name; mEnabled = true; mCriteria = ShowPublic | ShowPrivate| ShowConfidential ; } CalFilter::~CalFilter() { } -void CalFilter::apply(QPtrList<Event> *eventlist) +void CalFilter::apply(Q3PtrList<Event> *eventlist) { if (!mEnabled) return; // kdDebug(5800) << "CalFilter::apply()" << endl; Event *event = eventlist->first(); while(event) { if (!filterEvent(event)) { eventlist->remove(); event = eventlist->current(); } else { event = eventlist->next(); } } // kdDebug(5800) << "CalFilter::apply() done" << endl; } // TODO: avoid duplicating apply() code -void CalFilter::apply(QPtrList<Todo> *eventlist) +void CalFilter::apply(Q3PtrList<Todo> *eventlist) { if (!mEnabled) return; Todo *event = eventlist->first(); while(event) { if (!filterTodo(event)) { eventlist->remove(); event = eventlist->current(); } else { event = eventlist->next(); } } // kdDebug(5800) << "CalFilter::apply() done" << endl; } bool CalFilter::filterCalendarItem(Incidence *in) { if ( !in->calEnabled() ) return false; if ( in->typeID() == eventID ) return filterEvent( (Event*) in ); else if ( in->typeID() == todoID ) return filterTodo( (Todo*) in); else if ( in->typeID () == journalID ) return filterJournal( (Journal*) in ); return false; } bool CalFilter::filterEvent(Event *event) { if ( !event->calEnabled() ) return false; if (mCriteria & HideEvents) return false; if (mCriteria & HideRecurring) { if (event->recurrence()->doesRecur()) return false; } return filterIncidence(event); } bool CalFilter::filterJournal(Journal *j) { if ( !j->calEnabled() ) return false; if (mCriteria & HideJournals) return false; return true; } bool CalFilter::filterTodo(Todo *todo) { if ( !todo->calEnabled() ) return false; if (mCriteria & HideTodos) return false; if (mCriteria & HideCompleted) { if (todo->isCompleted()) return false; } return filterIncidence(todo); } bool CalFilter::showCategories() { return mCriteria & ShowCategories; } int CalFilter::getSecrecy() { if ( (mCriteria & ShowPublic )) return Incidence::SecrecyPublic; if ( (mCriteria & ShowPrivate )) return Incidence::SecrecyPrivate; if ( (mCriteria & ShowConfidential )) return Incidence::SecrecyConfidential; return Incidence::SecrecyPublic; } bool CalFilter::filterIncidence(Incidence *incidence) { if ( mCriteria > 7 ) { switch (incidence->secrecy()) { case Incidence::SecrecyPublic: if (! (mCriteria & ShowPublic )) return false; break; case Incidence::SecrecyPrivate: if (! (mCriteria & ShowPrivate )) return false; break; case Incidence::SecrecyConfidential: if (! (mCriteria & ShowConfidential )) return false; break; default: return false; break; } } // kdDebug(5800) << "CalFilter::filterEvent(): " << event->getSummary() << endl; if (mCriteria & ShowCategories) { for (QStringList::Iterator it = mCategoryList.begin(); it != mCategoryList.end(); ++it ) { //QStringList incidenceCategories = incidence->categories(); for (QStringList::Iterator it2 = incidence->categoriesP()->begin(); it2 != incidence->categoriesP()->end(); ++it2 ) { if ((*it) == (*it2)) { return true; } } } return false; } else { for (QStringList::Iterator it = mCategoryList.begin(); it != mCategoryList.end(); ++it ) { //QStringList incidenceCategories = incidence->categories(); for (QStringList::Iterator it2 = incidence->categoriesP()->begin(); it2 != incidence->categoriesP()->end(); ++it2 ) { if ((*it) == (*it2)) { return false; } } } return true; } // kdDebug(5800) << "CalFilter::filterEvent(): passed" << endl; return true; } void CalFilter::setEnabled(bool enabled) { mEnabled = enabled; } bool CalFilter::isEnabled() { return mEnabled; } void CalFilter::setCriteria(int criteria) { mCriteria = criteria; } int CalFilter::criteria() { return mCriteria; } void CalFilter::setCategoryList(const QStringList &categoryList) { mCategoryList = categoryList; } QStringList CalFilter::categoryList() { return mCategoryList; } diff --git a/libkcal/calfilter.h b/libkcal/calfilter.h index e349770..821149f 100644 --- a/libkcal/calfilter.h +++ b/libkcal/calfilter.h @@ -1,130 +1,130 @@ /* This file is part of libkcal. Copyright (c) 2001 Cornelius Schumacher <schumacher@kde.org> 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #ifndef _CALFILTER_H #define _CALFILTER_H #include <qstring.h> -#include <qptrlist.h> +#include <q3ptrlist.h> #include "event.h" #include "todo.h" #include "journal.h" namespace KCal { /** Filter for calendar objects. */ class CalFilter { public: /** Construct filter. */ CalFilter(); /** Construct filter with name */ CalFilter(const QString &name); /** Destruct filter. */ ~CalFilter(); /** Set name of filter. */ void setName(const QString &name) { mName = name; } /** Return name of filter. */ QString name() const { return mName; } /** Apply filter to eventlist, all events not matching filter criterias are removed from the list. */ - void apply(QPtrList<Event> *eventlist); + void apply(Q3PtrList<Event> *eventlist); /** Apply filter to todolist, all todos not matching filter criterias are removed from the list. */ - void apply(QPtrList<Todo> *todolist); - bool CalFilter::filterCalendarItem(Incidence *in); - bool CalFilter::filterJournal(Journal *in); + void apply(Q3PtrList<Todo> *todolist); + bool filterCalendarItem(Incidence *in); + bool filterJournal(Journal *in); /** Apply filter criteria on the specified event. Return true, if event passes criteria, otherwise return false. */ bool filterEvent(Event *); /** Apply filter criteria on the specified todo. Return true, if event passes criteria, otherwise return false. */ bool filterTodo(Todo *); /** Apply filter criteria on the specified incidence. Return true, if event passes criteria, otherwise return false. */ bool filterIncidence(Incidence *); /** Enable or disable filter. */ void setEnabled(bool); /** Return wheter the filter is enabled or not. */ bool isEnabled(); bool showCategories(); int getSecrecy(); /** Set list of categories, which is used for showing/hiding categories of events. See related functions. */ void setCategoryList(const QStringList &); /** Return category list, used for showing/hiding categories of events. See related functions. */ QStringList categoryList(); enum { HideRecurring = 1, HideCompleted = 2, ShowCategories = 4 ,ShowPublic = 8, ShowPrivate = 16, ShowConfidential = 32, HideEvents = 64, HideTodos = 128, HideJournals = 256 }; /** Set criteria, which have to be fulfilled by events passing the filter. */ void setCriteria(int); /** Get inclusive filter criteria. */ int criteria(); private: QString mName; int mCriteria; bool mEnabled; QStringList mCategoryList; }; } #endif /* _CALFILTER_H */ diff --git a/libkcal/customproperties.cpp b/libkcal/customproperties.cpp index adc1710..16f4a28 100644 --- a/libkcal/customproperties.cpp +++ b/libkcal/customproperties.cpp @@ -1,114 +1,116 @@ /* This file is part of libkcal. Copyright (c) 2002 David Jarvie <software@astrojar.org.uk> 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #include "customproperties.h" +//Added by qt3to4: +#include <Q3CString> using namespace KCal; CustomProperties::CustomProperties() { } CustomProperties::CustomProperties(const CustomProperties &cp) : mProperties(cp.mProperties) { } CustomProperties::~CustomProperties() { } -void CustomProperties::setCustomProperty(const QCString &app, const QCString &key, +void CustomProperties::setCustomProperty(const Q3CString &app, const Q3CString &key, const QString &value) { if (value.isNull() || key.isEmpty() || app.isEmpty()) return; - QCString property = "X-KDE-" + app + "-" + key; + Q3CString property = "X-KDE-" + app + "-" + key; if (!checkName(property)) return; mProperties[property] = value; } -void CustomProperties::removeCustomProperty(const QCString &app, const QCString &key) +void CustomProperties::removeCustomProperty(const Q3CString &app, const Q3CString &key) { - removeNonKDECustomProperty(QCString("X-KDE-" + app + "-" + key)); + removeNonKDECustomProperty(Q3CString("X-KDE-" + app + "-" + key)); } -QString CustomProperties::customProperty(const QCString &app, const QCString &key) const +QString CustomProperties::customProperty(const Q3CString &app, const Q3CString &key) const { - return nonKDECustomProperty(QCString("X-KDE-" + app + "-" + key)); + return nonKDECustomProperty(Q3CString("X-KDE-" + app + "-" + key)); } -void CustomProperties::setNonKDECustomProperty(const QCString &name, const QString &value) +void CustomProperties::setNonKDECustomProperty(const Q3CString &name, const QString &value) { if (value.isNull() || !checkName(name)) return; mProperties[name] = value; } -void CustomProperties::removeNonKDECustomProperty(const QCString &name) +void CustomProperties::removeNonKDECustomProperty(const Q3CString &name) { - QMap<QCString, QString>::Iterator it = mProperties.find(name); + QMap<Q3CString, QString>::Iterator it = mProperties.find(name); if (it != mProperties.end()) mProperties.remove(it); } -QString CustomProperties::nonKDECustomProperty(const QCString &name) const +QString CustomProperties::nonKDECustomProperty(const Q3CString &name) const { - QMap<QCString, QString>::ConstIterator it = mProperties.find(name); + QMap<Q3CString, QString>::ConstIterator it = mProperties.find(name); if (it == mProperties.end()) return QString::null; return it.data(); } -void CustomProperties::setCustomProperties(const QMap<QCString, QString> &properties) +void CustomProperties::setCustomProperties(const QMap<Q3CString, QString> &properties) { - for (QMap<QCString, QString>::ConstIterator it = properties.begin(); it != properties.end(); ++it) { + for (QMap<Q3CString, QString>::ConstIterator it = properties.begin(); it != properties.end(); ++it) { // Validate the property name and convert any null string to empty string if (checkName(it.key())) { mProperties[it.key()] = it.data().isNull() ? QString("") : it.data(); } } } -QMap<QCString, QString> CustomProperties::customProperties() const +QMap<Q3CString, QString> CustomProperties::customProperties() const { return mProperties; } -bool CustomProperties::checkName(const QCString &name) +bool CustomProperties::checkName(const Q3CString &name) { // Check that the property name starts with 'X-' and contains // only the permitted characters const char* n = name; int len = name.length(); if (len < 2 || n[0] != 'X' || n[1] != '-') return false; for (int i = 2; i < len; ++i) { char ch = n[i]; if (ch >= 'A' && ch <= 'Z' || ch >= 'a' && ch <= 'z' || ch >= '0' && ch <= '9' || ch == '-') continue; return false; // invalid character found } return true; } diff --git a/libkcal/customproperties.h b/libkcal/customproperties.h index 0cbfdcd..75eb3ad 100644 --- a/libkcal/customproperties.h +++ b/libkcal/customproperties.h @@ -1,97 +1,99 @@ /* This file is part of libkcal. Copyright (c) 2002 David Jarvie <software@astrojar.org.uk> 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #ifndef KCAL_CUSTOM_PROPERTIES_H #define KCAL_CUSTOM_PROPERTIES_H #include <qstring.h> #include <qmap.h> +//Added by qt3to4: +#include <Q3CString> namespace KCal { /** This class represents custom calendar properties. It is used as a base class for classes which represent calendar components. A custom property name written by libkcal has the form X-KDE-APP-KEY where APP represents the application name, and KEY distinguishes individual properties for the application. In keeping with RFC2445, property names must be composed only of the characters A-Z, a-z, 0-9 and '-'. */ class CustomProperties { public: /** Construct a new empty custom properties instance */ CustomProperties(); CustomProperties(const CustomProperties &); ~CustomProperties(); /** Create or modify a custom calendar property. @param app Application name as it appears in the custom property name. @param key Property identifier specific to the application. @param value The property's value. A call with a value of QString::null will be ignored. */ - void setCustomProperty(const QCString &app, const QCString &key, + void setCustomProperty(const Q3CString &app, const Q3CString &key, const QString &value); /** Delete a custom calendar property. @param app Application name as it appears in the custom property name. @param key Property identifier specific to the application. */ - void removeCustomProperty(const QCString &app, const QCString &key); + void removeCustomProperty(const Q3CString &app, const Q3CString &key); /** Return the value of a custom calendar property. @param app Application name as it appears in the custom property name. @param key Property identifier specific to the application. @return Property value, or QString::null if (and only if) the property does not exist. */ - QString customProperty(const QCString &app, const QCString &key) const; + QString customProperty(const Q3CString &app, const Q3CString &key) const; /** Create or modify a non-KDE or non-standard custom calendar property. @param name Full property name @param value The property's value. A call with a value of QString::null will be ignored. */ - void setNonKDECustomProperty(const QCString &name, const QString &value); + void setNonKDECustomProperty(const Q3CString &name, const QString &value); /** Delete a non-KDE or non-standard custom calendar property. @param name Full property name */ - void removeNonKDECustomProperty(const QCString &name); + void removeNonKDECustomProperty(const Q3CString &name); /** Return the value of a non-KDE or non-standard custom calendar property. @param name Full property name @return Property value, or QString::null if (and only if) the property does not exist. */ - QString nonKDECustomProperty(const QCString& name) const; + QString nonKDECustomProperty(const Q3CString& name) const; /** Initialise the alarm's custom calendar properties to the specified key/value pairs. */ - void setCustomProperties(const QMap<QCString, QString> &properties); + void setCustomProperties(const QMap<Q3CString, QString> &properties); /** Return all custom calendar property key/value pairs. */ - QMap<QCString, QString> customProperties() const; + QMap<Q3CString, QString> customProperties() const; private: - static bool checkName(const QCString& name); + static bool checkName(const Q3CString& name); - QMap<QCString, QString> mProperties; // custom calendar properties + QMap<Q3CString, QString> mProperties; // custom calendar properties }; } #endif diff --git a/libkcal/dndfactory.cpp b/libkcal/dndfactory.cpp index cdcfae4..ca7e212 100644 --- a/libkcal/dndfactory.cpp +++ b/libkcal/dndfactory.cpp @@ -1,186 +1,189 @@ /* This file is part of libkcal. Copyright (c) 1998 Preston Brwon Copyright (c) 2001,2002 Cornelius Schumacher <schumacher@kde.org> Copyright (C) 2003-2004 Reinhold Kainhofer <reinhold@kainhofer.com> 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #include <qapplication.h> #include <qclipboard.h> +//Added by qt3to4: +#include <QDropEvent> +#include <Q3PtrList> #include <kiconloader.h> #include <kdebug.h> #include <kmessagebox.h> #include <klocale.h> #include "vcaldrag.h" #include "icaldrag.h" #include "calendar.h" #include "vcalformat.h" #include "icalformat.h" #include "calendarlocal.h" #include "dndfactory.h" using namespace KCal; DndFactory::DndFactory( Calendar *cal ) : mCalendar( cal ) { } ICalDrag *DndFactory::createDrag( Incidence *incidence, QWidget *owner ) { CalendarLocal cal( mCalendar->timeZoneId() ); Incidence *i = incidence->clone(); cal.addIncidence( i ); ICalDrag *icd = new ICalDrag( &cal, owner ); if ( i->type() == "Event" ) icd->setPixmap( BarIcon( "appointment" ) ); else if ( i->type() == "Todo" ) icd->setPixmap( BarIcon( "todo" ) ); return icd; } Event *DndFactory::createDrop(QDropEvent *de) { kdDebug(5800) << "DndFactory::createDrop()" << endl; CalendarLocal cal( mCalendar->timeZoneId() ); if ( ICalDrag::decode( de, &cal ) || VCalDrag::decode( de, &cal ) ) { de->accept(); - QPtrList<Event> events = cal.events(); + Q3PtrList<Event> events = cal.events(); if ( !events.isEmpty() ) { Event *event = new Event( *events.first() ); return event; } } return 0; } Todo *DndFactory::createDropTodo(QDropEvent *de) { kdDebug(5800) << "VCalFormat::createDropTodo()" << endl; CalendarLocal cal( mCalendar->timeZoneId() ); if ( ICalDrag::decode( de, &cal ) || VCalDrag::decode( de, &cal ) ) { de->accept(); - QPtrList<Todo> todos = cal.todos(); + Q3PtrList<Todo> todos = cal.todos(); if ( !todos.isEmpty() ) { Todo *todo = new Todo( *todos.first() ); return todo; } } return 0; } void DndFactory::cutIncidence( Incidence *selectedInc ) { if ( copyIncidence( selectedInc ) ) { mCalendar->deleteIncidence( selectedInc ); } } bool DndFactory::copyIncidence( Incidence *selectedInc ) { if ( !selectedInc ) return false; QClipboard *cb = QApplication::clipboard(); CalendarLocal cal( mCalendar->timeZoneId() ); Incidence *inc = selectedInc->clone(); cal.addIncidence( inc ); cb->setData( new ICalDrag( &cal ) ); return true; } Incidence *DndFactory::pasteIncidence(const QDate &newDate, const QTime *newTime) { // kdDebug(5800) << "DnDFactory::pasteEvent()" << endl; CalendarLocal cal( mCalendar->timeZoneId() ); QClipboard *cb = QApplication::clipboard(); if ( !ICalDrag::decode( cb->data(), &cal ) && !VCalDrag::decode( cb->data(), &cal ) ) { kdDebug(5800) << "Can't parse clipboard" << endl; return 0; } - QPtrList<Incidence> incList = cal.incidences(); + Q3PtrList<Incidence> incList = cal.incidences(); Incidence *inc = incList.first(); if ( !incList.isEmpty() && inc ) { inc = inc->clone(); inc->recreate(); if ( inc->type() == "Event" ) { Event *anEvent = static_cast<Event*>( inc ); // Calculate length of event int daysOffset = anEvent->dtStart().date().daysTo( anEvent->dtEnd().date() ); // new end date if event starts at the same time on the new day QDateTime endDate( newDate.addDays(daysOffset), anEvent->dtEnd().time() ); if ( newTime ) { // additional offset for new time of day int addSecsOffset( anEvent->dtStart().time().secsTo( *newTime )); endDate=endDate.addSecs( addSecsOffset ); anEvent->setDtStart( QDateTime( newDate, *newTime ) ); } else { anEvent->setDtStart( QDateTime( newDate, anEvent->dtStart().time() ) ); } anEvent->setDtEnd( endDate ); } else if ( inc->type() == "Todo" ) { Todo *anTodo = static_cast<Todo*>( inc ); if ( newTime ) { anTodo->setDtDue( QDateTime( newDate, *newTime ) ); } else { anTodo->setDtDue( QDateTime( newDate, anTodo->dtDue().time() ) ); } } else if ( inc->type() == "Journal" ) { Journal *anJournal = static_cast<Journal*>( inc ); if ( newTime ) { anJournal->setDtStart( QDateTime( newDate, *newTime ) ); } else { anJournal->setDtStart( QDateTime( newDate ) ); } } else { kdDebug(5850) << "Trying to paste unknown incidence of type " << inc->type() << endl; } return inc; } return 0; } diff --git a/libkcal/dndfactory.h b/libkcal/dndfactory.h index 2df5259..a873c37 100644 --- a/libkcal/dndfactory.h +++ b/libkcal/dndfactory.h @@ -1,83 +1,85 @@ +//Added by qt3to4: +#include <QDropEvent> /* This file is part of libkcal. Copyright (c) 1998 Preston Brown Copyright (c) 2001,2002,2003 Cornelius Schumacher <schumacher@kde.org> Copyright (C) 2003-2004 Reinhold Kainhofer <reinhold@kainhofer.com> 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #ifdef DESKTOP_VERSION #ifndef KCAL_DNDFACTORY_H #define KCAL_DNDFACTORY_H //#include "libkcal_export.h" namespace KCal { class ICalDrag; class Event; class Todo; class Calendar; #define LIBKCAL_EXPORT /** This class implements functions to create Drag and Drop objects used for Drag-and-Drop and Copy-and-Paste. @short vCalendar/iCalendar Drag-and-Drop object factory. */ class LIBKCAL_EXPORT DndFactory { public: DndFactory( Calendar * ); /** Create a drag object. */ ICalDrag *createDrag( Incidence *incidence, QWidget *owner ); /** Create Todo object from drop event */ Todo *createDropTodo(QDropEvent *de); /** Create Event object from drop event */ Event *createDrop(QDropEvent *de); /** cut incidence to clipboard */ void cutIncidence( Incidence * ); /** copy the incidence to clipboard */ bool copyIncidence( Incidence * ); /** pastes the event or todo and returns a pointer to the new incidence pasted. */ Incidence *pasteIncidence( const QDate &, const QTime *newTime = 0 ); private: Calendar *mCalendar; class Private; Private *d; }; } #endif #else // dummy implementation for embedded #include "dndfactory_dummy.h" #define cutIncidence cutEvent #define pasteIncidence pasteEvent #define copyIncidence copyEvent #endif diff --git a/libkcal/dndfactory_dummy.h b/libkcal/dndfactory_dummy.h index 44cc114..3ab6adf 100644 --- a/libkcal/dndfactory_dummy.h +++ b/libkcal/dndfactory_dummy.h @@ -1,65 +1,67 @@ /* This file is part of libkcal. Copyright (c) 1998 Preston Brown Copyright (c) 2001,2002 Cornelius Schumacher <schumacher@kde.org> 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ // $Id$ #ifndef KCAL_DNDFACTORY_H #define KCAL_DNDFACTORY_H #include "vcalformat.h" +//Added by qt3to4: +#include <QDropEvent> class QDropEvent; namespace KCal { /** This class implements functions to create Drag and Drop objects used for Drag-and-Drop and Copy-and-Paste. @short vCalendar Drag-and-Drop object factory. */ class DndFactory { public: DndFactory( Calendar * ) {} /** create an object to be used with the Xdnd Drag And Drop protocol. */ ICalDrag *createDrag(Event *, QWidget *) { return 0; } /** create an object to be used with the Xdnd Drag And Drop protocol. */ ICalDrag *createDragTodo(Todo *, QWidget *) { return 0; } /** Create Todo object from drop event */ Todo *createDropTodo(QDropEvent *) { return 0; } /** Create Event object from drop event */ Event *createDrop(QDropEvent *) { return 0; } /** cut event to clipboard */ void cutEvent(Event *) {} /** cut, copy, and paste operations follow. */ bool copyEvent(Event *) { return false; } /** pastes the event and returns a pointer to the new event pasted. */ Event *pasteEvent(const QDate &, const QTime *newTime = 0) { Q_UNUSED( newTime ); return 0; } }; } #endif diff --git a/libkcal/dummyscheduler.cpp b/libkcal/dummyscheduler.cpp index ae40e6d..73eb3d0 100644 --- a/libkcal/dummyscheduler.cpp +++ b/libkcal/dummyscheduler.cpp @@ -1,119 +1,121 @@ /* This file is part of libkcal. Copyright (c) 2001 Cornelius Schumacher <schumacher@kde.org> 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ // // DummyScheduler - iMIP implementation of iTIP methods // #include <qfile.h> -#include <qtextstream.h> +#include <q3textstream.h> +//Added by qt3to4: +#include <Q3PtrList> #include <kdebug.h> #include "event.h" #include "icalformat.h" #include "dummyscheduler.h" using namespace KCal; DummyScheduler::DummyScheduler(Calendar *calendar) : Scheduler(calendar) { } DummyScheduler::~DummyScheduler() { } bool DummyScheduler::publish (IncidenceBase *incidence,const QString &recipients) { QString messageText = mFormat->createScheduleMessage(incidence, Scheduler::Publish); return saveMessage(messageText); } bool DummyScheduler::performTransaction(IncidenceBase *incidence,Method method,const QString &recipients) { QString messageText = mFormat->createScheduleMessage(incidence,method); return saveMessage(messageText); } bool DummyScheduler::performTransaction(IncidenceBase *incidence,Method method) { QString messageText = mFormat->createScheduleMessage(incidence,method); return saveMessage(messageText); } bool DummyScheduler::saveMessage(const QString &message) { QFile f("dummyscheduler.store"); - if (f.open(IO_WriteOnly | IO_Append)) { - QTextStream t(&f); + if (f.open(QIODevice::WriteOnly | QIODevice::Append)) { + Q3TextStream t(&f); t << message << endl; f.close(); return true; } else { return false; } } -QPtrList<ScheduleMessage> DummyScheduler::retrieveTransactions() +Q3PtrList<ScheduleMessage> DummyScheduler::retrieveTransactions() { - QPtrList<ScheduleMessage> messageList; + Q3PtrList<ScheduleMessage> messageList; QFile f("dummyscheduler.store"); - if (!f.open(IO_ReadOnly)) { + if (!f.open(QIODevice::ReadOnly)) { kdDebug(5800) << "DummyScheduler::retrieveTransactions(): Can't open file" << endl; } else { - QTextStream t(&f); + Q3TextStream t(&f); QString messageString; QString messageLine = t.readLine(); while (!messageLine.isNull()) { // kdDebug(5800) << "++++++++" << messageLine << endl; messageString += messageLine + "\n"; if (messageLine.find("END:VCALENDAR") >= 0) { kdDebug(5800) << "---------------" << messageString << endl; ScheduleMessage *message = mFormat->parseScheduleMessage(mCalendar, messageString); kdDebug(5800) << "--Parsed" << endl; if (message) { messageList.append(message); } else { QString errorMessage; if (mFormat->exception()) { errorMessage = mFormat->exception()->message(); } kdDebug(5800) << "DummyScheduler::retrieveTransactions() Error parsing " "message: " << errorMessage << endl; } messageString=""; } messageLine = t.readLine(); } f.close(); } return messageList; } diff --git a/libkcal/dummyscheduler.h b/libkcal/dummyscheduler.h index df42153..f86d583 100644 --- a/libkcal/dummyscheduler.h +++ b/libkcal/dummyscheduler.h @@ -1,51 +1,53 @@ /* This file is part of libkcal. Copyright (c) 2001 Cornelius Schumacher <schumacher@kde.org> 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #ifndef DUMMYSCHEDULER_H #define DUMMYSCHEDULER_H // // Dummy implementation of iTIP methods // #include "scheduler.h" +//Added by qt3to4: +#include <Q3PtrList> namespace KCal { /** This class implements the iTIP interface as a primitive local version for testing. It uses a file dummyscheduler.store as inbox/outbox. */ class DummyScheduler : public Scheduler { public: DummyScheduler(Calendar *); virtual ~DummyScheduler(); bool publish (IncidenceBase *incidence,const QString &recipients); bool performTransaction(IncidenceBase *incidence,Method method); bool performTransaction(IncidenceBase *incidence,Method method,const QString &recipients); - QPtrList<ScheduleMessage> retrieveTransactions(); + Q3PtrList<ScheduleMessage> retrieveTransactions(); protected: bool saveMessage(const QString &); }; } #endif // DUMMYSCHEDULER_H diff --git a/libkcal/event.cpp b/libkcal/event.cpp index fdf5657..060df81 100644 --- a/libkcal/event.cpp +++ b/libkcal/event.cpp @@ -195,230 +195,230 @@ bool Event::matchTime(QDateTime*startDT, QDateTime* endDT) bool Event::isOverlapping ( Event* testEvent, QDateTime* overlapDT, QDateTime* startDT ) { if ( testEvent == this ) return false; if ( ! doesRecur() && !testEvent->doesRecur() ) { QDateTime te; if ( testEvent->doesFloat() ) te = testEvent->mDtEnd.addDays( 1 ); else te = testEvent->mDtEnd; QDateTime e; if ( doesFloat() ) e = mDtEnd.addDays( 1 ); else e = mDtEnd; if ( mDtStart < te && testEvent->mDtStart < e ) { if ( mDtStart < testEvent->mDtStart ) *overlapDT = testEvent->mDtStart; else *overlapDT = mDtStart; if ( startDT ) return (*overlapDT >= *startDT ); return true; } return false; } if ( !doesFloat() && !testEvent->doesFloat() && !isMultiDay() && !testEvent->isMultiDay() ) { if ( mDtStart.time() >= testEvent->mDtEnd.time() || testEvent->mDtStart.time() >= mDtEnd.time() ) { // no need to test. times mismatch //fprintf(stderr,"timi "); return false; } } Event *nonRecur = 0; Event *recurEvent = 0; if ( ! doesRecur() ) { nonRecur = this; recurEvent = testEvent; } else if ( !testEvent->doesRecur() ) { nonRecur = testEvent; recurEvent = this; } if ( nonRecur ) { QDateTime enr; if ( nonRecur->doesFloat() ) enr = nonRecur->mDtEnd.addDays( 1 ); else enr = nonRecur->mDtEnd; if ( enr < recurEvent->mDtStart ) return false; if ( startDT && enr < *startDT ) return false; int recDuration = recurEvent->mDtStart.secsTo( recurEvent->mDtEnd ); if ( recurEvent->doesFloat() ) recDuration += 86400; bool ok = false; QDateTime recStart; if ( startDT ) { recStart = recurEvent->recurrence()->getPreviousDateTime( startDT->addSecs( 61 ), &ok ); } if ( recStart.isValid() ) { //qDebug("%s start at %s ", startDT-> toString().latin1(), recStart.toString().latin1()); recStart = recStart.addSecs( -300); } else recStart = recurEvent->mDtStart.addSecs( -300); ok = true; while ( ok ) { recStart = recurEvent->getNextOccurence( recStart.addSecs( 60 ), &ok ); if ( ok ) { if ( recStart > enr ) return false; QDateTime recEnd = recStart.addSecs( recDuration ); if ( nonRecur->mDtStart < recEnd && recStart < nonRecur->mDtEnd ) { if ( nonRecur->mDtStart < recStart ) *overlapDT = recStart; else *overlapDT = nonRecur->mDtStart; if ( startDT ) { if ( *overlapDT >= *startDT ) return true; } else return true; } } } return false; } if ( !doesFloat() && !testEvent->doesFloat() && !isMultiDay() && !testEvent->isMultiDay() ) { if ( recurrence()->doesRecur() == Recurrence::rWeekly && testEvent->recurrence()->doesRecur() == Recurrence::rWeekly ) { bool found = false; uint i; for ( i=0; i< recurrence()->days().size();++i ) { found = found || (recurrence()->days().testBit( i ) && testEvent->recurrence()->days().testBit( i ) ); } if ( ! found ) { //qDebug("recurring days mismatch %s -- %s", summary().latin1(),testEvent->summary().latin1()); return false; } } } bool ok = true; QDateTime incidenceStart;// = mDtStart; QDateTime testincidenceStart;// = testEvent->mDtStart; if ( startDT ) { incidenceStart = recurrence()->getPreviousDateTime( startDT->addSecs( 61 ), &ok ); testincidenceStart = testEvent->recurrence()->getPreviousDateTime( startDT->addSecs( 61 ), &ok ); } if ( !testincidenceStart.isValid() ) testincidenceStart = testEvent->mDtStart; if ( !incidenceStart.isValid() ) incidenceStart = mDtStart; int duration = mDtStart.secsTo( mDtEnd ); if ( doesFloat() ) duration += 86400; int testduration = testEvent->mDtStart.secsTo( testEvent->mDtEnd ); if ( testEvent->doesFloat() ) testduration += 86400; bool computeThis = false; if ( incidenceStart < testincidenceStart ) computeThis = true; if ( computeThis ) incidenceStart = incidenceStart.addSecs( -300 ); else testincidenceStart = testincidenceStart.addSecs( -300 ); int count = 0; ok = true; int countbreak = 2000; QDateTime stopSearch; bool testStop = false; if ( startDT ) { stopSearch = startDT->addDays( 365*3 ); testStop = true; } while ( ok ) { ++count; if ( count > countbreak ) break; if ( computeThis ) { if ( testStop ) if ( testincidenceStart > stopSearch ) break; incidenceStart = getNextOccurence( incidenceStart.addSecs( 60 ), &ok ); } else { if ( testStop ) if ( incidenceStart > stopSearch ) break; testincidenceStart = testEvent->getNextOccurence( testincidenceStart.addSecs( 60 ), &ok ); } if ( ok ) { if ( incidenceStart < testincidenceStart.addSecs( testduration ) && testincidenceStart < incidenceStart.addSecs( duration ) ) { if ( incidenceStart < testincidenceStart ) *overlapDT = testincidenceStart; else *overlapDT = incidenceStart; if ( startDT ) { if ( *overlapDT >= *startDT ) return true; } else return true; } computeThis = ( incidenceStart < testincidenceStart ); } } //qDebug("%d rec counter stopped at %d - %s %s", ok ,count, summary().latin1(),testEvent->summary().latin1() ); return false; } QDateTime Event::getNextAlarmDateTime( bool * ok, int * offset, QDateTime start_dt ) const { *ok = false; if ( !alarmEnabled() ) return QDateTime (); bool yes; QDateTime incidenceStart = getNextOccurence( start_dt, &yes ); if ( ! yes || cancelled() ) { *ok = false; return QDateTime (); } bool enabled = false; Alarm* alarm; int off = 0; QDateTime alarmStart = QDateTime::currentDateTime().addDays( 3650 );; // if ( QDateTime::currentDateTime() > incidenceStart ){ // *ok = false; // return incidenceStart; // } - for (QPtrListIterator<Alarm> it(mAlarms); (alarm = it.current()) != 0; ++it) { + for (Q3PtrListIterator<Alarm> it(mAlarms); (alarm = it.current()) != 0; ++it) { if (alarm->enabled()) { if ( alarm->hasTime () ) { if ( alarm->time() < alarmStart ) { alarmStart = alarm->time(); enabled = true; off = alarmStart.secsTo( incidenceStart ); } } else { int secs = alarm->startOffset().asSeconds(); if ( incidenceStart.addSecs( secs ) < alarmStart ) { alarmStart = incidenceStart.addSecs( secs ); enabled = true; off = -secs; } } } } if ( enabled ) { if ( alarmStart > start_dt ) { *ok = true; * offset = off; return alarmStart; } } *ok = false; return QDateTime (); } QString Event::durationText() { int sec = mDtStart.secsTo( mDtEnd ); if ( doesFloat() ) sec += 86400; return durationText4Time( sec ); } diff --git a/libkcal/event.h b/libkcal/event.h index 6a58618..da44f81 100644 --- a/libkcal/event.h +++ b/libkcal/event.h @@ -1,95 +1,97 @@ /* This file is part of libkcal. Copyright (c) 2001 Cornelius Schumacher <schumacher@kde.org> 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #ifndef EVENT_H #define EVENT_H // // Event component, representing a VEVENT object // #include "incidence.h" +//Added by qt3to4: +#include <Q3CString> namespace KCal { /** This class provides an Event in the sense of RFC2445. */ class Event : public Incidence { public: enum Transparency { Opaque, Transparent }; typedef ListBase<Event> List; Event(); Event(const Event &); ~Event(); bool matchTime(QDateTime*startDT, QDateTime* endDT); - QCString type() const { return "Event"; } + Q3CString type() const { return "Event"; } IncTypeID typeID() const { return eventID; } Incidence *clone(); QDateTime getNextAlarmDateTime( bool * ok, int * offset ,QDateTime start_dt ) const; /** for setting an event's ending date/time with a QDateTime. */ void setDtEnd(const QDateTime &dtEnd); /** Return the event's ending date/time as a QDateTime. */ virtual QDateTime dtEnd() const; /** returns an event's end time as a string formatted according to the users locale settings */ QString dtEndTimeStr() const; /** returns an event's end date as a string formatted according to the users locale settings */ QString dtEndDateStr(bool shortfmt=true) const; /** returns an event's end date and time as a string formatted according to the users locale settings */ QString dtEndStr(bool shortfmt=true) const; void setHasEndDate(bool); /** Return whether the event has an end date/time. */ bool hasEndDate() const; /** Return true if the event spans multiple days, otherwise return false. */ bool isMultiDay() const; /** set the event's time transparency level. */ void setTransparency(Transparency transparency); /** get the event's time transparency level. */ Transparency transparency() const; void setDuration(int seconds); bool contains ( Event*); bool isOverlapping ( Event*, QDateTime*, QDateTime* ); QString durationText(); private: bool accept(Visitor &v) { return v.visit(this); } QDateTime mDtEnd; bool mHasEndDate; Transparency mTransparency; }; bool operator==( const Event&, const Event& ); } #endif diff --git a/libkcal/filestorage.cpp b/libkcal/filestorage.cpp index a139124..3d1309f 100644 --- a/libkcal/filestorage.cpp +++ b/libkcal/filestorage.cpp @@ -1,140 +1,140 @@ /* This file is part of libkcal. Copyright (c) 2002 Cornelius Schumacher <schumacher@kde.org> 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #include <stdlib.h> #include <qdatetime.h> #include <qstring.h> -#include <qptrlist.h> +#include <q3ptrlist.h> #include <kdebug.h> #include "calendar.h" #include "vcaldrag.h" #include "vcalformat.h" #include "icalformat.h" #include "filestorage.h" using namespace KCal; FileStorage::FileStorage( Calendar *cal, const QString &fileName, CalFormat *format ) : CalStorage( cal ), mFileName( fileName ), mSaveFormat( format ) { } FileStorage::~FileStorage() { delete mSaveFormat; } void FileStorage::setFileName( const QString &fileName ) { mFileName = fileName; } QString FileStorage::fileName()const { return mFileName; } void FileStorage::setSaveFormat( CalFormat *format ) { delete mSaveFormat; mSaveFormat = format; } CalFormat *FileStorage::saveFormat()const { return mSaveFormat; } bool FileStorage::open() { return true; } bool FileStorage::load( ) { kdDebug(5800) << "FileStorage::load(): '" << mFileName << "'" << endl; // do we want to silently accept this, or make some noise? Dunno... // it is a semantical thing vs. a practical thing. if (mFileName.isEmpty()) return false; // Always try to load with iCalendar. It will detect, if it is actually a // vCalendar file. ICalFormat iCal; bool success = iCal.load( calendar(), mFileName); if ( !success ) { if ( iCal.exception() ) { // kdDebug(5800) << "---Error: " << mFormat->exception()->errorCode() << endl; if ( iCal.exception()->errorCode() == ErrorFormat::CalVersion1 ) { // Expected non vCalendar file, but detected vCalendar kdDebug(5800) << "FileStorage::load() Fallback to VCalFormat" << endl; VCalFormat vCal; success = vCal.load( calendar(), mFileName ); calendar()->setLoadedProductId( vCal.productId() ); } else { return false; } } else { kdDebug(5800) << "Warning! There should be set an exception." << endl; return false; } } else { // kdDebug(5800) << "---Success" << endl; calendar()->setLoadedProductId( iCal.loadedProductId() ); } calendar()->setModified( false ); return true; } bool FileStorage::save() { if ( mFileName.isEmpty() ) return false; bool success; if ( mSaveFormat ) { success = mSaveFormat->save( calendar(), mFileName); } else { ICalFormat iCal; success = iCal.save( calendar(), mFileName); } if ( success ) calendar()->setModified( false ); return success; } bool FileStorage::close() { return true; } diff --git a/libkcal/freebusy.cpp b/libkcal/freebusy.cpp index ba15d6d..e4e9ec9 100644 --- a/libkcal/freebusy.cpp +++ b/libkcal/freebusy.cpp @@ -1,184 +1,187 @@ /* This file is part of libkcal. Copyright (c) 2001 Cornelius Schumacher <schumacher@kde.org> 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #include <kdebug.h> #include "freebusy.h" +//Added by qt3to4: +#include <Q3ValueList> +#include <Q3PtrList> using namespace KCal; FreeBusy::FreeBusy() { } FreeBusy::FreeBusy(const QDateTime &start, const QDateTime &end) { setDtStart(start); setDtEnd(end); } FreeBusy::FreeBusy( Calendar *calendar, const QDateTime &start, const QDateTime &end ) { kdDebug() << "FreeBusy::FreeBusy" << endl; mCalendar = calendar; setDtStart(start); setDtEnd(end); //Gets all the events in the calendar - QPtrList<Event> eventList = mCalendar->events(); + Q3PtrList<Event> eventList = mCalendar->events(); Event *event; int extraDays, i, x, duration; duration = start.daysTo(end); QDate day; QDateTime tmpStart; QDateTime tmpEnd; //Loops through every event in the calendar for( event = eventList.first(); event; event = eventList.next() ) { //This whole for loop is for recurring events, it loops through //each of the days of the freebusy request //First check if this is transparent. If it is, it shouldn't be in the //freebusy list if ( event->transparency() == Event::Transparent ) // Transparent continue; for(i=0; i<=duration; i++) { day=(start.addDays(i).date()); tmpStart.setDate(day); tmpEnd.setDate(day); if( (*(event->recurrence())).doesRecur() ) { if ( event->isMultiDay() ) { extraDays = event->dtStart().date().daysTo(event->dtEnd().date()); for (x=0; x<=extraDays; x++) { if ( event->recursOn(day.addDays(-x))) { tmpStart.setDate(day.addDays(-x)); tmpStart.setTime(event->dtStart().time()); tmpEnd=tmpStart.addSecs( (event->duration()) ); addLocalPeriod( tmpStart, tmpEnd ); break; } } } else { if (event->recursOn(day)) { tmpStart.setTime(event->dtStart().time()); tmpEnd.setTime(event->dtEnd().time()); addLocalPeriod (tmpStart, tmpEnd); } } } } //Non-reocurring events addLocalPeriod(event->dtStart(), event->dtEnd()); } sortList(); } FreeBusy::~FreeBusy() { } bool FreeBusy::setDtEnd( const QDateTime &end ) { mDtEnd = end; return true; } QDateTime FreeBusy::dtEnd() const { return mDtEnd; } -QValueList<Period> FreeBusy::busyPeriods() const +Q3ValueList<Period> FreeBusy::busyPeriods() const { return mBusyPeriods; } bool FreeBusy::addLocalPeriod(const QDateTime &eventStart, const QDateTime &eventEnd ) { QDateTime tmpStart; QDateTime tmpEnd; //Check to see if the start *or* end of the event is //between the start and end of the freebusy dates. if (!((((this->dtStart()).secsTo(eventStart)>=0)&&(eventStart.secsTo(this->dtEnd())>=0)) ||(((this->dtStart()).secsTo(eventEnd) >= 0)&&(eventEnd.secsTo(this->dtEnd()) >= 0)))) return false; if ( eventStart.secsTo(this->dtStart())>=0) { tmpStart = this->dtStart(); } else { tmpStart = eventStart; } if ( eventEnd.secsTo(this->dtEnd())<=0 ) { tmpEnd = this->dtEnd(); } else { tmpEnd = eventEnd; } Period p(tmpStart, tmpEnd); mBusyPeriods.append( p ); return true; } -FreeBusy::FreeBusy(QValueList<Period> busyPeriods) +FreeBusy::FreeBusy(Q3ValueList<Period> busyPeriods) { mBusyPeriods = busyPeriods; } void FreeBusy::sortList() { - typedef QValueList<Period> PeriodList; + typedef Q3ValueList<Period> PeriodList; PeriodList::Iterator tmpPeriod, earlyPeriod; PeriodList sortedList; QDateTime earlyTime; while( mBusyPeriods.count() > 0 ) { earlyTime=(*mBusyPeriods.begin()).start(); for (tmpPeriod=mBusyPeriods.begin(); tmpPeriod!=mBusyPeriods.end(); tmpPeriod++) { if (earlyTime.secsTo((*tmpPeriod).start()) <= 0) { earlyTime=(*tmpPeriod).start(); earlyPeriod=tmpPeriod; } } //Move tmpPeriod to sortedList Period tmpPeriod( (*earlyPeriod).start(), (*earlyPeriod).end() ); sortedList.append( tmpPeriod ); mBusyPeriods.remove( earlyPeriod ); } mBusyPeriods=sortedList; } void FreeBusy::addPeriod(const QDateTime &start, const QDateTime &end) { Period p(start, end); mBusyPeriods.append( p ); sortList(); } diff --git a/libkcal/freebusy.h b/libkcal/freebusy.h index d741c72..bd14cb7 100644 --- a/libkcal/freebusy.h +++ b/libkcal/freebusy.h @@ -1,73 +1,75 @@ /* This file is part of libkcal. Copyright (c) 2001 Cornelius Schumacher <schumacher@kde.org> 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #ifndef KCAL_FREEBUSY_H #define KCAL_FREEBUSY_H // // FreeBusy - information about free/busy times // #include <qdatetime.h> -#include <qvaluelist.h> -#include <qptrlist.h> +#include <q3valuelist.h> +#include <q3ptrlist.h> +//Added by qt3to4: +#include <Q3CString> #include "period.h" #include "calendar.h" #include "incidencebase.h" namespace KCal { /** This class provides information about free/busy time of a calendar user. */ class FreeBusy : public IncidenceBase { public: FreeBusy(); FreeBusy(const QDateTime &start, const QDateTime &end); FreeBusy(Calendar *calendar, const QDateTime &start, const QDateTime &end); - FreeBusy(QValueList<Period> busyPeriods); + FreeBusy(Q3ValueList<Period> busyPeriods); ~FreeBusy(); - QCString type() const { return "FreeBusy"; } + Q3CString type() const { return "FreeBusy"; } IncTypeID typeID() const { return freebusyID; } virtual QDateTime dtEnd() const; bool setDtEnd( const QDateTime &end ); - QValueList<Period> busyPeriods() const; + Q3ValueList<Period> busyPeriods() const; void addPeriod(const QDateTime &start, const QDateTime &end); void sortList(); private: //This is used for creating a freebusy object for the current user bool addLocalPeriod(const QDateTime &start, const QDateTime &end); QDateTime mDtEnd; - QValueList<Period> mBusyPeriods; + Q3ValueList<Period> mBusyPeriods; Calendar *mCalendar; }; } #endif diff --git a/libkcal/icaldrag.cpp b/libkcal/icaldrag.cpp index 446a115..7f5a796 100644 --- a/libkcal/icaldrag.cpp +++ b/libkcal/icaldrag.cpp @@ -1,58 +1,58 @@ /* This file is part of libkcal. Copyright (c) 1998 Preston Brown Copyright (c) 2001 Cornelius Schumacher <schumacher@kde.org> 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #include "icaldrag.h" #include "icalformat.h" #include <kdebug.h> using namespace KCal; ICalDrag::ICalDrag( Calendar *cal, QWidget *parent, const char *name ) - : QStoredDrag( "text/calendar", parent, name ) + : Q3StoredDrag( "text/calendar", parent, name ) { ICalFormat icf; QString scal = icf.toString( cal ); setEncodedData( scal.utf8() ); } bool ICalDrag::canDecode( QMimeSource *me ) { return me->provides( "text/calendar" ); } bool ICalDrag::decode( QMimeSource *de, Calendar *cal ) { bool success = false; QByteArray payload = de->encodedData( "text/calendar" ); if ( payload.size() ) { QString txt = QString::fromUtf8( payload.data() ); ICalFormat icf; success = icf.fromString( cal, txt ); } return success; } diff --git a/libkcal/icaldrag.h b/libkcal/icaldrag.h index fdf32b7..c1f73f4 100644 --- a/libkcal/icaldrag.h +++ b/libkcal/icaldrag.h @@ -1,46 +1,46 @@ /* This file is part of libkcal. Copyright (c) 1998 Preston Brown Copyright (c) 2001 Cornelius Schumacher <schumacher@kde.org> 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #ifndef ICALDRAG_H #define ICALDRAG_H -#include <qdragobject.h> +#include <q3dragobject.h> #include "calendar.h" namespace KCal { /** iCalendar drag&drop class. */ -class ICalDrag : public QStoredDrag +class ICalDrag : public Q3StoredDrag { public: /** Create a drag&drop object for iCalendar component \a ical. */ ICalDrag( Calendar *cal, QWidget *parent = 0, const char *name = 0 ); ~ICalDrag() {}; /** Return, if drag&drop object can be decode to iCalendar. */ static bool canDecode( QMimeSource * ); /** Decode drag&drop object to iCalendar component \a cal. */ static bool decode( QMimeSource *e, Calendar *cal ); }; } #endif diff --git a/libkcal/icalformat.cpp b/libkcal/icalformat.cpp index 6f3a799..3829bc1 100644 --- a/libkcal/icalformat.cpp +++ b/libkcal/icalformat.cpp @@ -1,402 +1,402 @@ /* This file is part of libkcal. Copyright (c) 2001 Cornelius Schumacher <schumacher@kde.org> 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #include <qdatetime.h> #include <qstring.h> -#include <qptrlist.h> +#include <q3ptrlist.h> #include <qregexp.h> #include <qclipboard.h> #include <qfile.h> -#include <qtextstream.h> +#include <q3textstream.h> #include <qtextcodec.h> #include <stdlib.h> #include <kdebug.h> #include <kglobal.h> #include <klocale.h> extern "C" { #include <ical.h> #include <icalss.h> #include <icalparser.h> #include <icalrestriction.h> } #include "calendar.h" #include "calendarlocal.h" #include "journal.h" #include "icalformat.h" #include "icalformatimpl.h" #define _ICAL_VERSION "2.0" using namespace KCal; ICalFormat::ICalFormat( bool pe ) { mProcessEvents = pe; mImpl = new ICalFormatImpl( this ); tzOffsetMin = 0; //qDebug("new ICalFormat() "); } ICalFormat::~ICalFormat() { delete mImpl; //qDebug("delete ICalFormat "); } bool ICalFormat::load( Calendar *calendar, const QString &fileName) { clearException(); QFile file( fileName ); - if (!file.open( IO_ReadOnly ) ) { + if (!file.open( QIODevice::ReadOnly ) ) { setException(new ErrorFormat(ErrorFormat::LoadError)); return false; } - QTextStream ts( &file ); + Q3TextStream ts( &file ); QString text; - ts.setEncoding( QTextStream::Latin1 ); + ts.setEncoding( Q3TextStream::Latin1 ); text = ts.read(); file.close(); return fromString( calendar, text ); } //#include <qdatetime.h> bool ICalFormat::save( Calendar *calendar, const QString &fileName ) { //kdDebug(5800) << "ICalFormat::save(): " << fileName << endl; //qDebug("ICalFormat::save "); clearException(); QString text = toString( calendar ); //return false; // qDebug("to string takes ms: %d ",is.elapsed() ); if ( text.isNull() ) return false; // TODO: write backup file //is.restart(); QFile file( fileName ); - if (!file.open( IO_WriteOnly ) ) { + if (!file.open( QIODevice::WriteOnly ) ) { setException(new ErrorFormat(ErrorFormat::SaveError, i18n("Could not open file '%1'").arg(fileName))); return false; } - QTextStream ts( &file ); + Q3TextStream ts( &file ); - ts.setEncoding( QTextStream::Latin1 ); + ts.setEncoding( Q3TextStream::Latin1 ); ts << text; file.close(); //qDebug("saving file takes ms: %d ", is.elapsed() ); return true; } bool ICalFormat::fromString( Calendar *cal, const QString &text ) { setTimeZone( cal->timeZoneId(), !cal->isLocalTime() ); // qDebug("ICalFormat::fromString tz: %s ", cal->timeZoneId().latin1()); // Get first VCALENDAR component. // TODO: Handle more than one VCALENDAR or non-VCALENDAR top components icalcomponent *calendar; //calendar = icalcomponent_new_from_string( text.local8Bit().data()); // good calendar = icalcomponent_new_from_string( text.utf8().data()); calendar = icalcomponent_new_from_string( (char*)text.latin1()); if (!calendar) { setException(new ErrorFormat(ErrorFormat::ParseErrorIcal)); return false; } bool success = true; if (icalcomponent_isa(calendar) != ICAL_VCALENDAR_COMPONENT) { setException(new ErrorFormat(ErrorFormat::NoCalendar)); success = false; } else { // put all objects into their proper places if ( !mImpl->populate( cal, calendar ) ) { if ( !exception() ) { setException(new ErrorFormat(ErrorFormat::ParseErrorKcal)); } success = false; } else mLoadedProductId = mImpl->loadedProductId(); } icalcomponent_free( calendar ); icalmemory_free_ring(); return success; } Incidence *ICalFormat::fromString( const QString &text ) { CalendarLocal cal( mTimeZoneId ); fromString(&cal, text); Incidence *ical = 0; - QPtrList<Event> elist = cal.events(); + Q3PtrList<Event> elist = cal.events(); if ( elist.count() > 0 ) { ical = elist.first(); } else { - QPtrList<Todo> tlist = cal.todos(); + Q3PtrList<Todo> tlist = cal.todos(); if ( tlist.count() > 0 ) { ical = tlist.first(); } else { - QPtrList<Journal> jlist = cal.journals(); + Q3PtrList<Journal> jlist = cal.journals(); if ( jlist.count() > 0 ) { ical = jlist.first(); } } } return ical; } -#include <qapp.h> +#include <qapplication.h> QString ICalFormat::toString( Calendar *cal ) { setTimeZone( cal->timeZoneId(), !cal->isLocalTime() ); icalcomponent *calendar = mImpl->createCalendarComponent(cal); icalcomponent *component; // todos - QPtrList<Todo> todoList = cal->rawTodos(); - QPtrListIterator<Todo> qlt(todoList); + Q3PtrList<Todo> todoList = cal->rawTodos(); + Q3PtrListIterator<Todo> qlt(todoList); for (; qlt.current(); ++qlt) { component = mImpl->writeTodo(qlt.current()); icalcomponent_add_component(calendar,component); //qDebug(" todos "); if ( mProcessEvents ) { //qDebug("mProcessEvents "); qApp->processEvents(); } } // events - QPtrList<Event> events = cal->rawEvents(); + Q3PtrList<Event> events = cal->rawEvents(); Event *ev; for(ev=events.first();ev;ev=events.next()) { component = mImpl->writeEvent(ev); icalcomponent_add_component(calendar,component); //qDebug("events "); if ( mProcessEvents ) qApp->processEvents(); } // journals - QPtrList<Journal> journals = cal->journals(); + Q3PtrList<Journal> journals = cal->journals(); Journal *j; for(j=journals.first();j;j=journals.next()) { component = mImpl->writeJournal(j); icalcomponent_add_component(calendar,component); //qDebug("journals "); if ( mProcessEvents ) qApp->processEvents(); } const char *text; QString ret =""; text = icalcomponent_as_ical_string( calendar ); if ( mProcessEvents ) qApp->processEvents(); // text = "BEGIN:VCALENDAR\nPRODID\n :-//K Desktop Environment//NONSGML libkcal 3.1//EN\nVERSION\n :2.0\nBEGIN:VEVENT\nDTSTAMP\n :20031231T213514Z\nORGANIZER\n :MAILTO:lutz@putz.de\nCREATED\n :20031231T213513Z\nUID\n :libkcal-1295166342.120\nSEQUENCE\n :0\nLAST-MODIFIED\n :20031231T213513Z\nSUMMARY\n :test1\nCLASS\n :PUBLIC\nPRIORITY\n :3\nDTSTART\n :20040101T090000Z\nDTEND\n :20040101T110000Z\nTRANSP\n :OPAQUE\nEND:VEVENT\nEND:VCALENDAR\n"; if ( text ) { ret = QString ( text ); } icalcomponent_free( calendar ); if (!text) { setException(new ErrorFormat(ErrorFormat::SaveError, i18n("libical error"))); icalmemory_free_ring(); return QString::null; } icalmemory_free_ring(); return ret; } QString ICalFormat::toICalString( Incidence *incidence ) { CalendarLocal cal( mTimeZoneId ); cal.addIncidence( incidence->clone() ); return toString( &cal ); } QString ICalFormat::toString( Incidence *incidence ) { icalcomponent *component; component = mImpl->writeIncidence( incidence ); const char *text = icalcomponent_as_ical_string( component ); icalcomponent_free( component ); return QString::fromLocal8Bit( text ); } QString ICalFormat::toString( Recurrence *recurrence ) { icalproperty *property; property = mImpl->writeRecurrenceRule( recurrence ); const char *text = icalproperty_as_ical_string( property ); icalproperty_free( property ); return QString::fromLocal8Bit( text ); } /* bool ICalFormat::fromString( Recurrence * recurrence, const QString& rrule ) { bool success = true; icalerror_clear_errno(); struct icalrecurrencetype recur = icalrecurrencetype_from_string( rrule ); if ( icalerrno != ICAL_NO_ERROR ) { kdDebug() << "Recurrence parsing error: " << icalerror_strerror( icalerrno ) << endl; success = false; } if ( success ) { mImpl->readRecurrence( recur, recurrence ); } return success; } */ QString ICalFormat::createScheduleMessage(IncidenceBase *incidence, Scheduler::Method method) { icalcomponent *message = mImpl->createScheduleComponent(incidence,method); QString messageText = icalcomponent_as_ical_string(message); return messageText; } ScheduleMessage *ICalFormat::parseScheduleMessage( Calendar *cal, const QString &messageText ) { setTimeZone( cal->timeZoneId(), !cal->isLocalTime() ); clearException(); if (messageText.isEmpty()) return 0; icalcomponent *message; message = icalparser_parse_string(messageText.local8Bit()); if (!message) return 0; icalproperty *m = icalcomponent_get_first_property(message, ICAL_METHOD_PROPERTY); if (!m) return 0; icalcomponent *c; IncidenceBase *incidence = 0; c = icalcomponent_get_first_component(message,ICAL_VEVENT_COMPONENT); if (c) { incidence = mImpl->readEvent(c); } if (!incidence) { c = icalcomponent_get_first_component(message,ICAL_VTODO_COMPONENT); if (c) { incidence = mImpl->readTodo(c); } } if (!incidence) { c = icalcomponent_get_first_component(message,ICAL_VFREEBUSY_COMPONENT); if (c) { incidence = mImpl->readFreeBusy(c); } } if (!incidence) { kdDebug() << "ICalFormat:parseScheduleMessage: object is not a freebusy, event or todo" << endl; return 0; } kdDebug(5800) << "ICalFormat::parseScheduleMessage() getting method..." << endl; icalproperty_method icalmethod = icalproperty_get_method(m); Scheduler::Method method; switch (icalmethod) { case ICAL_METHOD_PUBLISH: method = Scheduler::Publish; break; case ICAL_METHOD_REQUEST: method = Scheduler::Request; break; case ICAL_METHOD_REFRESH: method = Scheduler::Refresh; break; case ICAL_METHOD_CANCEL: method = Scheduler::Cancel; break; case ICAL_METHOD_ADD: method = Scheduler::Add; break; case ICAL_METHOD_REPLY: method = Scheduler::Reply; break; case ICAL_METHOD_COUNTER: method = Scheduler::Counter; break; case ICAL_METHOD_DECLINECOUNTER: method = Scheduler::Declinecounter; break; default: method = Scheduler::NoMethod; kdDebug(5800) << "ICalFormat::parseScheduleMessage(): Unknow method" << endl; break; } if (!icalrestriction_check(message)) { setException(new ErrorFormat(ErrorFormat::Restriction, Scheduler::translatedMethodName(method) + ": " + mImpl->extractErrorProperty(c))); return 0; } icalcomponent *calendarComponent = mImpl->createCalendarComponent(cal); Incidence *existingIncidence = cal->event(incidence->uid()); if (existingIncidence) { // TODO: check, if cast is required, or if it can be done by virtual funcs. if (existingIncidence->typeID() == todoID ) { Todo *todo = static_cast<Todo *>(existingIncidence); icalcomponent_add_component(calendarComponent, mImpl->writeTodo(todo)); } if (existingIncidence->typeID() == eventID ) { Event *event = static_cast<Event *>(existingIncidence); diff --git a/libkcal/icalformat.h b/libkcal/icalformat.h index a770dbb..a454b35 100644 --- a/libkcal/icalformat.h +++ b/libkcal/icalformat.h @@ -1,116 +1,118 @@ /* This file is part of libkcal. Copyright (c) 2001 Cornelius Schumacher <schumacher@kde.org> 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #ifndef ICALFORMAT_H #define ICALFORMAT_H #include <qstring.h> +//Added by qt3to4: +#include <Q3CString> #include "scheduler.h" #include "calformat.h" namespace KCal { class ICalFormatImpl; /** This class implements the iCalendar format. It provides methods for loading/saving/converting iCalendar format data into the internal KOrganizer representation as Calendar and Events. @short iCalendar format implementation */ class ICalFormat : public CalFormat { public: /** Create new iCalendar format. */ ICalFormat( bool pe = true); virtual ~ICalFormat(); /** Loads a calendar on disk in iCalendar format into calendar. Returns true if successful, else returns false. Provides more error information by exception(). @param calendar Calendar object to be filled. @param fileName The name of the calendar file on disk. */ bool load( Calendar *, const QString &fileName ); /** Writes out the calendar to disk in iCalendar format. Returns true if successful and false on error. @param calendar The Calendar object to be written. @param fileName The name of the calendar file on disk. */ bool save( Calendar *, const QString &fileName ); /** Parse string and populate calendar with that information. */ bool fromString( Calendar *, const QString & ); /** Parse string and return first ical component. */ Incidence *fromString( const QString & ); /** Return calendar information as string. */ QString toString( Calendar * ); /** Return incidence as full iCalendar formatted text. */ QString toICalString( Incidence * ); /** Return incidence as iCalendar formatted text. */ QString toString( Incidence * ); /** Return recurrence as iCalendar formatted text. */ QString toString( Recurrence * ); /** Parse string and fill recurrence object with that information */ //bool fromString ( Recurrence *, const QString& ); /** Create a scheduling message for event \a e using method \m */ QString createScheduleMessage(IncidenceBase *e,Scheduler::Method m); /** Parse scheduling message provided as string \s */ ScheduleMessage *parseScheduleMessage( Calendar *, const QString &s); /** Set id of used time zone and whether this time zone is UTC or not. */ void setTimeZone( const QString &id, bool utc ); QString timeZoneId() const; int timeOffset(); const char * tzString(); bool utc() const; private: bool mProcessEvents; ICalFormatImpl *mImpl; QString mTimeZoneId; - QCString mTzString; + Q3CString mTzString; int tzOffsetMin; bool mUtc; }; } #endif diff --git a/libkcal/icalformatimpl.cpp b/libkcal/icalformatimpl.cpp index 65eabc8..ea144ee 100644 --- a/libkcal/icalformatimpl.cpp +++ b/libkcal/icalformatimpl.cpp @@ -1,959 +1,962 @@ /* This file is part of libkcal. Copyright (c) 2001 Cornelius Schumacher <schumacher@kde.org> 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #include <qdatetime.h> #include <qstring.h> -#include <qptrlist.h> +#include <q3ptrlist.h> #include <qfile.h> +//Added by qt3to4: +#include <Q3ValueList> +#include <Q3CString> #include <kdebug.h> #include <klocale.h> #include <kglobal.h> extern "C" { #include <ical.h> #include <icalss.h> #include <icalparser.h> #include <icalrestriction.h> } #include "calendar.h" #include "journal.h" #include "icalformat.h" #include "icalformatimpl.h" #include "compat.h" #define _ICAL_VERSION "2.0" using namespace KCal; const int gSecondsPerMinute = 60; const int gSecondsPerHour = gSecondsPerMinute * 60; const int gSecondsPerDay = gSecondsPerHour * 24; const int gSecondsPerWeek = gSecondsPerDay * 7; ICalFormatImpl::ICalFormatImpl( ICalFormat *parent ) : mParent( parent ), mCalendarVersion( 0 ) { mCompat = new Compat; } ICalFormatImpl::~ICalFormatImpl() { delete mCompat; } class ToStringVisitor : public Incidence::Visitor { public: ToStringVisitor( ICalFormatImpl *impl ) : mImpl( impl ), mComponent( 0 ) {} bool visit( Event *e ) { mComponent = mImpl->writeEvent( e ); return true; } bool visit( Todo *e ) { mComponent = mImpl->writeTodo( e ); return true; } bool visit( Journal *e ) { mComponent = mImpl->writeJournal( e ); return true; } icalcomponent *component() { return mComponent; } private: ICalFormatImpl *mImpl; icalcomponent *mComponent; }; icalcomponent *ICalFormatImpl::writeIncidence(Incidence *incidence) { ToStringVisitor v( this ); incidence->accept(v); return v.component(); } icalcomponent *ICalFormatImpl::writeTodo(Todo *todo) { QString tmpStr; QStringList tmpStrList; icalcomponent *vtodo = icalcomponent_new(ICAL_VTODO_COMPONENT); writeIncidence(vtodo,todo); // due date if (todo->hasDueDate()) { icaltimetype due; if (todo->doesFloat()) { due = writeICalDate(todo->dtDue().date()); } else { due = writeICalDateTime(todo->dtDue()); } icalcomponent_add_property(vtodo,icalproperty_new_due(due)); } // start time if (todo->hasStartDate()) { icaltimetype start; if (todo->doesFloat()) { // kdDebug(5800) << "§§ Incidence " << todo->summary() << " floats." << endl; start = writeICalDate(todo->dtStart().date()); } else { // kdDebug(5800) << "§§ incidence " << todo->summary() << " has time." << endl; start = writeICalDateTime(todo->dtStart()); } icalcomponent_add_property(vtodo,icalproperty_new_dtstart(start)); } // completion date if (todo->isCompleted()) { if (!todo->hasCompletedDate()) { // If todo was created by KOrganizer <2.2 it has no correct completion // date. Set it to now. todo->setCompleted(QDateTime::currentDateTime()); } icaltimetype completed = writeICalDateTime(todo->completed()); icalcomponent_add_property(vtodo,icalproperty_new_completed(completed)); } icalcomponent_add_property(vtodo, icalproperty_new_percentcomplete(todo->percentComplete())); return vtodo; } icalcomponent *ICalFormatImpl::writeEvent(Event *event) { kdDebug(5800) << "Write Event '" << event->summary() << "' (" << event->uid() << ")" << endl; QString tmpStr; QStringList tmpStrList; icalcomponent *vevent = icalcomponent_new(ICAL_VEVENT_COMPONENT); writeIncidence(vevent,event); // start time icaltimetype start; if (event->doesFloat()) { // kdDebug(5800) << "§§ Incidence " << event->summary() << " floats." << endl; start = writeICalDate(event->dtStart().date()); } else { // kdDebug(5800) << "§§ incidence " << event->summary() << " has time." << endl; start = writeICalDateTime(event->dtStart()); } icalcomponent_add_property(vevent,icalproperty_new_dtstart(start)); if (event->hasEndDate()) { // end time icaltimetype end; if (event->doesFloat()) { // kdDebug(5800) << "§§ Event " << event->summary() << " floats." << endl; // +1 day because end date is non-inclusive. end = writeICalDate( event->dtEnd().date().addDays( 1 ) ); } else { // kdDebug(5800) << "§§ Event " << event->summary() << " has time." << endl; end = writeICalDateTime(event->dtEnd()); } icalcomponent_add_property(vevent,icalproperty_new_dtend(end)); } // TODO: attachments, resources #if 0 // attachments tmpStrList = anEvent->attachments(); for ( QStringList::Iterator it = tmpStrList.begin(); it != tmpStrList.end(); ++it ) addPropValue(vevent, VCAttachProp, (*it).utf8()); // resources tmpStrList = anEvent->resources(); tmpStr = tmpStrList.join(";"); if (!tmpStr.isEmpty()) addPropValue(vevent, VCResourcesProp, tmpStr.utf8()); #endif // Transparency switch( event->transparency() ) { case Event::Transparent: icalcomponent_add_property(vevent, icalproperty_new_transp(ICAL_TRANSP_TRANSPARENT)); break; case Event::Opaque: icalcomponent_add_property(vevent, icalproperty_new_transp(ICAL_TRANSP_OPAQUE)); break; } return vevent; } icalcomponent *ICalFormatImpl::writeFreeBusy(FreeBusy *freebusy, Scheduler::Method method) { icalcomponent *vfreebusy = icalcomponent_new(ICAL_VFREEBUSY_COMPONENT); writeIncidenceBase(vfreebusy,freebusy); icalcomponent_add_property(vfreebusy, icalproperty_new_dtstart( writeICalDateTime(freebusy->dtStart()))); icalcomponent_add_property(vfreebusy, icalproperty_new_dtend( writeICalDateTime(freebusy->dtEnd()))); if (method == Scheduler::Request) { icalcomponent_add_property(vfreebusy,icalproperty_new_uid( freebusy->uid().utf8())); } //Loops through all the periods in the freebusy object - QValueList<Period> list = freebusy->busyPeriods(); - QValueList<Period>::Iterator it; + Q3ValueList<Period> list = freebusy->busyPeriods(); + Q3ValueList<Period>::Iterator it; icalperiodtype period; for (it = list.begin(); it!= list.end(); ++it) { period.start = writeICalDateTime((*it).start()); period.end = writeICalDateTime((*it).end()); icalcomponent_add_property(vfreebusy, icalproperty_new_freebusy(period) ); } return vfreebusy; } icalcomponent *ICalFormatImpl::writeJournal(Journal *journal) { icalcomponent *vjournal = icalcomponent_new(ICAL_VJOURNAL_COMPONENT); writeIncidence(vjournal,journal); // start time if (journal->dtStart().isValid()) { icaltimetype start; if (journal->doesFloat()) { // kdDebug(5800) << "§§ Incidence " << event->summary() << " floats." << endl; start = writeICalDate(journal->dtStart().date()); } else { // kdDebug(5800) << "§§ incidence " << event->summary() << " has time." << endl; start = writeICalDateTime(journal->dtStart()); } icalcomponent_add_property(vjournal,icalproperty_new_dtstart(start)); } return vjournal; } void ICalFormatImpl::writeIncidence(icalcomponent *parent,Incidence *incidence) { // pilot sync stuff // TODO: move this application-specific code to kpilot if (incidence->pilotId()) { incidence->setNonKDECustomProperty("X-PILOTID", QString::number(incidence->pilotId())); incidence->setNonKDECustomProperty("X-PILOTSTAT", QString::number(incidence->syncStatus())); } if ( !incidence->IDStr().isEmpty()) { incidence->setNonKDECustomProperty("X-KOPIEXTID",incidence->IDStr() ); } writeIncidenceBase(parent,incidence); if (incidence->cancelled()) { icalcomponent_add_property(parent,icalproperty_new_status(ICAL_STATUS_CANCELLED)); } // creation date icalcomponent_add_property(parent,icalproperty_new_created( writeICalDateTime(incidence->created()))); // unique id icalcomponent_add_property(parent,icalproperty_new_uid( incidence->uid().utf8())); // revision icalcomponent_add_property(parent,icalproperty_new_sequence( incidence->revision())); // last modification date icalcomponent_add_property(parent,icalproperty_new_lastmodified( writeICalDateTime(incidence->lastModified()))); // description if (!incidence->description().isEmpty()) { icalcomponent_add_property(parent,icalproperty_new_description( incidence->description().utf8())); } // summary if (!incidence->summary().isEmpty()) { icalcomponent_add_property(parent,icalproperty_new_summary( incidence->summary().utf8())); } // location if (!incidence->location().isEmpty()) { icalcomponent_add_property(parent,icalproperty_new_location( incidence->location().utf8())); } // TODO: // status // addPropValue(parent, VCStatusProp, incidence->getStatusStr().utf8()); // secrecy enum icalproperty_class classInt; switch (incidence->secrecy()) { case Incidence::SecrecyPublic: classInt = ICAL_CLASS_PUBLIC; break; case Incidence::SecrecyConfidential: classInt = ICAL_CLASS_CONFIDENTIAL; break; case Incidence::SecrecyPrivate: classInt =ICAL_CLASS_PRIVATE ; default: classInt =ICAL_CLASS_PRIVATE ; break; } icalcomponent_add_property(parent,icalproperty_new_class(classInt)); // priority icalcomponent_add_property(parent,icalproperty_new_priority( incidence->priority())); // categories QStringList categories = incidence->categories(); QStringList::Iterator it; for(it = categories.begin(); it != categories.end(); ++it ) { icalcomponent_add_property(parent,icalproperty_new_categories((*it).utf8())); } // TODO: Ensure correct concatenation of categories properties. /* // categories tmpStrList = incidence->getCategories(); tmpStr = ""; QString catStr; for ( QStringList::Iterator it = tmpStrList.begin(); it != tmpStrList.end(); ++it ) { catStr = *it; if (catStr[0] == ' ') tmpStr += catStr.mid(1); else tmpStr += catStr; // this must be a ';' character as the vCalendar specification requires! // vcc.y has been hacked to translate the ';' to a ',' when the vcal is // read in. tmpStr += ";"; } if (!tmpStr.isEmpty()) { tmpStr.truncate(tmpStr.length()-1); icalcomponent_add_property(parent,icalproperty_new_categories( writeText(incidence->getCategories().join(";")))); } */ // related event if (!incidence->relatedToUid().isEmpty()) { icalcomponent_add_property(parent,icalproperty_new_relatedto( incidence->relatedToUid().utf8())); } // recurrence rule stuff if (incidence->doesRecur()) { icalcomponent_add_property(parent,writeRecurrenceRule(incidence->recurrence())); // recurrence excpetion dates DateList dateList = incidence->exDates(); DateList::ConstIterator exIt; for(exIt = dateList.begin(); exIt != dateList.end(); ++exIt) { icalcomponent_add_property(parent,icalproperty_new_exdate( writeICalDate(*exIt))); } } // attachments - QPtrList<Attachment> attachments = incidence->attachments(); + Q3PtrList<Attachment> attachments = incidence->attachments(); for (Attachment *at = attachments.first(); at; at = attachments.next()) icalcomponent_add_property(parent,writeAttachment(at)); // alarms - QPtrList<Alarm> alarms = incidence->alarms(); + Q3PtrList<Alarm> alarms = incidence->alarms(); Alarm* alarm; for (alarm = alarms.first(); alarm; alarm = alarms.next()) { if (alarm->enabled()) { kdDebug(5800) << "Write alarm for " << incidence->summary() << endl; icalcomponent_add_component(parent,writeAlarm(alarm)); } } if( incidence->hasRecurrenceID() ) { icalcomponent_add_property(parent, icalproperty_new_recurrenceid( writeICalDateTime( incidence->recurrenceID()))); } // duration // turned off as it always is set to PTS0 (and must not occur together with DTEND if (incidence->hasDuration()) { icaldurationtype duration; duration = writeICalDuration(incidence->duration()); icalcomponent_add_property(parent,icalproperty_new_duration(duration)); } } void ICalFormatImpl::writeIncidenceBase(icalcomponent *parent,IncidenceBase *incidenceBase) { icalcomponent_add_property(parent,icalproperty_new_dtstamp( writeICalDateTime(QDateTime::currentDateTime()))); // organizer stuff icalcomponent_add_property(parent,icalproperty_new_organizer( ("MAILTO:" + incidenceBase->organizer()).utf8())); // attendees if (incidenceBase->attendeeCount() != 0) { - QPtrList<Attendee> al = incidenceBase->attendees(); - QPtrListIterator<Attendee> ai(al); + Q3PtrList<Attendee> al = incidenceBase->attendees(); + Q3PtrListIterator<Attendee> ai(al); for (; ai.current(); ++ai) { icalcomponent_add_property(parent,writeAttendee(ai.current())); } } // custom properties writeCustomProperties(parent, incidenceBase); } void ICalFormatImpl::writeCustomProperties(icalcomponent *parent,CustomProperties *properties) { - QMap<QCString, QString> custom = properties->customProperties(); - for (QMap<QCString, QString>::Iterator c = custom.begin(); c != custom.end(); ++c) { + QMap<Q3CString, QString> custom = properties->customProperties(); + for (QMap<Q3CString, QString>::Iterator c = custom.begin(); c != custom.end(); ++c) { icalproperty *p = icalproperty_new_x(c.data().utf8()); icalproperty_set_x_name(p,c.key()); icalcomponent_add_property(parent,p); } } icalproperty *ICalFormatImpl::writeAttendee(Attendee *attendee) { icalproperty *p = icalproperty_new_attendee("mailto:" + attendee->email().utf8()); if (!attendee->name().isEmpty()) { icalproperty_add_parameter(p,icalparameter_new_cn(attendee->name().utf8())); } icalproperty_add_parameter(p,icalparameter_new_rsvp( attendee->RSVP() ? ICAL_RSVP_TRUE : ICAL_RSVP_FALSE )); icalparameter_partstat status = ICAL_PARTSTAT_NEEDSACTION; switch (attendee->status()) { default: case Attendee::NeedsAction: status = ICAL_PARTSTAT_NEEDSACTION; break; case Attendee::Accepted: status = ICAL_PARTSTAT_ACCEPTED; break; case Attendee::Declined: status = ICAL_PARTSTAT_DECLINED; break; case Attendee::Tentative: status = ICAL_PARTSTAT_TENTATIVE; break; case Attendee::Delegated: status = ICAL_PARTSTAT_DELEGATED; break; case Attendee::Completed: status = ICAL_PARTSTAT_COMPLETED; break; case Attendee::InProcess: status = ICAL_PARTSTAT_INPROCESS; break; } icalproperty_add_parameter(p,icalparameter_new_partstat(status)); icalparameter_role role = ICAL_ROLE_REQPARTICIPANT; switch (attendee->role()) { case Attendee::Chair: role = ICAL_ROLE_CHAIR; break; default: case Attendee::ReqParticipant: role = ICAL_ROLE_REQPARTICIPANT; break; case Attendee::OptParticipant: role = ICAL_ROLE_OPTPARTICIPANT; break; case Attendee::NonParticipant: role = ICAL_ROLE_NONPARTICIPANT; break; } icalproperty_add_parameter(p,icalparameter_new_role(role)); if (!attendee->uid().isEmpty()) { icalparameter* icalparameter_uid = icalparameter_new_x(attendee->uid().utf8()); icalparameter_set_xname(icalparameter_uid,"X-UID"); icalproperty_add_parameter(p,icalparameter_uid); } return p; } icalproperty *ICalFormatImpl::writeAttachment(Attachment *att) { #if 0 icalattachtype* attach = icalattachtype_new(); if (att->isUri()) icalattachtype_set_url(attach, att->uri().utf8().data()); else icalattachtype_set_base64(attach, att->data(), 0); #endif icalattach *attach; if (att->isUri()) attach = icalattach_new_from_url( att->uri().utf8().data()); else attach = icalattach_new_from_data ( (unsigned char *)att->data(), 0, 0); icalproperty *p = icalproperty_new_attach(attach); if (!att->mimeType().isEmpty()) icalproperty_add_parameter(p,icalparameter_new_fmttype(att->mimeType().utf8().data())); if (att->isBinary()) { icalproperty_add_parameter(p,icalparameter_new_value(ICAL_VALUE_BINARY)); icalproperty_add_parameter(p,icalparameter_new_encoding(ICAL_ENCODING_BASE64)); } return p; } icalproperty *ICalFormatImpl::writeRecurrenceRule(Recurrence *recur) { // kdDebug(5800) << "ICalFormatImpl::writeRecurrenceRule()" << endl; icalrecurrencetype r; icalrecurrencetype_clear(&r); int index = 0; int index2 = 0; - QPtrList<Recurrence::rMonthPos> tmpPositions; - QPtrList<int> tmpDays; + Q3PtrList<Recurrence::rMonthPos> tmpPositions; + Q3PtrList<int> tmpDays; int *tmpDay; Recurrence::rMonthPos *tmpPos; bool datetime = false; int day; int i; switch(recur->doesRecur()) { case Recurrence::rMinutely: r.freq = ICAL_MINUTELY_RECURRENCE; datetime = true; break; case Recurrence::rHourly: r.freq = ICAL_HOURLY_RECURRENCE; datetime = true; break; case Recurrence::rDaily: r.freq = ICAL_DAILY_RECURRENCE; break; case Recurrence::rWeekly: r.freq = ICAL_WEEKLY_RECURRENCE; r.week_start = static_cast<icalrecurrencetype_weekday>(recur->weekStart()%7 + 1); for (i = 0; i < 7; i++) { if (recur->days().testBit(i)) { day = (i + 1)%7 + 1; // convert from Monday=0 to Sunday=1 r.by_day[index++] = icalrecurrencetype_day_day_of_week(day); } } // r.by_day[index] = ICAL_RECURRENCE_ARRAY_MAX; break; case Recurrence::rMonthlyPos: r.freq = ICAL_MONTHLY_RECURRENCE; tmpPositions = recur->monthPositions(); for (tmpPos = tmpPositions.first(); tmpPos; tmpPos = tmpPositions.next()) { for (i = 0; i < 7; i++) { if (tmpPos->rDays.testBit(i)) { day = (i + 1)%7 + 1; // convert from Monday=0 to Sunday=1 day += tmpPos->rPos*8; if (tmpPos->negative) day = -day; r.by_day[index++] = day; } } } // r.by_day[index] = ICAL_RECURRENCE_ARRAY_MAX; break; case Recurrence::rMonthlyDay: r.freq = ICAL_MONTHLY_RECURRENCE; tmpDays = recur->monthDays(); for (tmpDay = tmpDays.first(); tmpDay; tmpDay = tmpDays.next()) { r.by_month_day[index++] = icalrecurrencetype_day_position(*tmpDay*8);//*tmpDay); } // r.by_day[index] = ICAL_RECURRENCE_ARRAY_MAX; break; case Recurrence::rYearlyMonth: case Recurrence::rYearlyPos: r.freq = ICAL_YEARLY_RECURRENCE; tmpDays = recur->yearNums(); for (tmpDay = tmpDays.first(); tmpDay; tmpDay = tmpDays.next()) { r.by_month[index++] = *tmpDay; } // r.by_set_pos[index] = ICAL_RECURRENCE_ARRAY_MAX; if (recur->doesRecur() == Recurrence::rYearlyPos) { tmpPositions = recur->monthPositions(); for (tmpPos = tmpPositions.first(); tmpPos; tmpPos = tmpPositions.next()) { for (i = 0; i < 7; i++) { if (tmpPos->rDays.testBit(i)) { day = (i + 1)%7 + 1; // convert from Monday=0 to Sunday=1 day += tmpPos->rPos*8; if (tmpPos->negative) day = -day; r.by_day[index2++] = day; } } } // r.by_day[index2] = ICAL_RECURRENCE_ARRAY_MAX; } break; case Recurrence::rYearlyDay: r.freq = ICAL_YEARLY_RECURRENCE; tmpDays = recur->yearNums(); for (tmpDay = tmpDays.first(); tmpDay; tmpDay = tmpDays.next()) { r.by_year_day[index++] = *tmpDay; } // r.by_year_day[index] = ICAL_RECURRENCE_ARRAY_MAX; break; default: r.freq = ICAL_NO_RECURRENCE; kdDebug(5800) << "ICalFormatImpl::writeRecurrence(): no recurrence" << endl; break; } r.interval = recur->frequency(); if (recur->duration() > 0) { r.count = recur->duration(); } else if (recur->duration() == -1) { r.count = 0; } else { if (datetime) r.until = writeICalDateTime(recur->endDateTime()); else r.until = writeICalDate(recur->endDate()); } // Debug output #if 0 const char *str = icalrecurrencetype_as_string(&r); if (str) { kdDebug(5800) << " String: " << str << endl; } else { kdDebug(5800) << " No String" << endl; } #endif return icalproperty_new_rrule(r); } icalcomponent *ICalFormatImpl::writeAlarm(Alarm *alarm) { icalcomponent *a = icalcomponent_new(ICAL_VALARM_COMPONENT); icalproperty_action action; icalattach *attach = 0; switch (alarm->type()) { case Alarm::Procedure: action = ICAL_ACTION_PROCEDURE; attach = icalattach_new_from_url( QFile::encodeName(alarm->programFile()).data() ); icalcomponent_add_property(a,icalproperty_new_attach(attach)); if (!alarm->programArguments().isEmpty()) { icalcomponent_add_property(a,icalproperty_new_description(alarm->programArguments().utf8())); } icalattach_unref( attach ); break; case Alarm::Audio: action = ICAL_ACTION_AUDIO; if (!alarm->audioFile().isEmpty()) { attach = icalattach_new_from_url(QFile::encodeName( alarm->audioFile() ).data()); icalcomponent_add_property(a,icalproperty_new_attach(attach)); icalattach_unref( attach ); } break; case Alarm::Email: { action = ICAL_ACTION_EMAIL; - QValueList<Person> addresses = alarm->mailAddresses(); - for (QValueList<Person>::Iterator ad = addresses.begin(); ad != addresses.end(); ++ad) { + Q3ValueList<Person> addresses = alarm->mailAddresses(); + for (Q3ValueList<Person>::Iterator ad = addresses.begin(); ad != addresses.end(); ++ad) { icalproperty *p = icalproperty_new_attendee("MAILTO:" + (*ad).email().utf8()); if (!(*ad).name().isEmpty()) { icalproperty_add_parameter(p,icalparameter_new_cn((*ad).name().utf8())); } icalcomponent_add_property(a,p); } icalcomponent_add_property(a,icalproperty_new_summary(alarm->mailSubject().utf8())); icalcomponent_add_property(a,icalproperty_new_description(alarm->text().utf8())); QStringList attachments = alarm->mailAttachments(); if (attachments.count() > 0) { for (QStringList::Iterator at = attachments.begin(); at != attachments.end(); ++at) { attach = icalattach_new_from_url(QFile::encodeName( *at ).data()); icalcomponent_add_property(a,icalproperty_new_attach(attach)); icalattach_unref( attach ); } } break; } case Alarm::Display: action = ICAL_ACTION_DISPLAY; icalcomponent_add_property(a,icalproperty_new_description(alarm->text().utf8())); break; case Alarm::Invalid: default: kdDebug(5800) << "Unknown type of alarm" << endl; action = ICAL_ACTION_NONE; break; } icalcomponent_add_property(a,icalproperty_new_action(action)); // Trigger time icaltriggertype trigger; if ( alarm->hasTime() ) { trigger.time = writeICalDateTime(alarm->time()); trigger.duration = icaldurationtype_null_duration(); } else { trigger.time = icaltime_null_time(); Duration offset; if ( alarm->hasStartOffset() ) offset = alarm->startOffset(); else offset = alarm->endOffset(); trigger.duration = icaldurationtype_from_int( offset.asSeconds() ); } icalproperty *p = icalproperty_new_trigger(trigger); if ( alarm->hasEndOffset() ) icalproperty_add_parameter(p,icalparameter_new_related(ICAL_RELATED_END)); icalcomponent_add_property(a,p); // Repeat count and duration if (alarm->repeatCount()) { icalcomponent_add_property(a,icalproperty_new_repeat(alarm->repeatCount())); icalcomponent_add_property(a,icalproperty_new_duration( icaldurationtype_from_int(alarm->snoozeTime()*60))); } // Custom properties - QMap<QCString, QString> custom = alarm->customProperties(); - for (QMap<QCString, QString>::Iterator c = custom.begin(); c != custom.end(); ++c) { + QMap<Q3CString, QString> custom = alarm->customProperties(); + for (QMap<Q3CString, QString>::Iterator c = custom.begin(); c != custom.end(); ++c) { icalproperty *p = icalproperty_new_x(c.data().utf8()); icalproperty_set_x_name(p,c.key()); icalcomponent_add_property(a,p); } return a; } Todo *ICalFormatImpl::readTodo(icalcomponent *vtodo) { Todo *todo = new Todo; readIncidence(vtodo,todo); icalproperty *p = icalcomponent_get_first_property(vtodo,ICAL_ANY_PROPERTY); // int intvalue; icaltimetype icaltime; QStringList categories; while (p) { icalproperty_kind kind = icalproperty_isa(p); switch (kind) { case ICAL_DUE_PROPERTY: // due date icaltime = icalproperty_get_due(p); if (icaltime.is_date) { todo->setDtDue(QDateTime(readICalDate(icaltime),QTime(0,0,0))); todo->setFloats(true); } else { todo->setDtDue(readICalDateTime(icaltime)); todo->setFloats(false); } todo->setHasDueDate(true); break; case ICAL_COMPLETED_PROPERTY: // completion date icaltime = icalproperty_get_completed(p); todo->setCompleted(readICalDateTime(icaltime)); break; case ICAL_PERCENTCOMPLETE_PROPERTY: // Percent completed todo->setPercentComplete(icalproperty_get_percentcomplete(p)); break; case ICAL_RELATEDTO_PROPERTY: // related todo (parent) todo->setRelatedToUid(QString::fromUtf8(icalproperty_get_relatedto(p))); mTodosRelate.append(todo); break; case ICAL_DTSTART_PROPERTY: // Flag that todo has start date. Value is read in by readIncidence(). todo->setHasStartDate(true); break; default: // kdDebug(5800) << "ICALFormat::readTodo(): Unknown property: " << kind // << endl; break; } p = icalcomponent_get_next_property(vtodo,ICAL_ANY_PROPERTY); } return todo; } Event *ICalFormatImpl::readEvent(icalcomponent *vevent) { Event *event = new Event; event->setFloats(false); readIncidence(vevent,event); icalproperty *p = icalcomponent_get_first_property(vevent,ICAL_ANY_PROPERTY); // int intvalue; icaltimetype icaltime; QStringList categories; QString transparency; while (p) { icalproperty_kind kind = icalproperty_isa(p); switch (kind) { case ICAL_DTEND_PROPERTY: // start date and time icaltime = icalproperty_get_dtend(p); if (icaltime.is_date) { event->setFloats( true ); // End date is non-inclusive QDate endDate = readICalDate( icaltime ).addDays( -1 ); mCompat->fixFloatingEnd( endDate ); if ( endDate < event->dtStart().date() ) { endDate = event->dtStart().date(); } event->setDtEnd( QDateTime( endDate, QTime( 0, 0, 0 ) ) ); } else { event->setDtEnd(readICalDateTime(icaltime)); } break; // TODO: // at this point, there should be at least a start or end time. // fix up for events that take up no time but have a time associated #if 0 if (!(vo = isAPropertyOf(vevent, VCDTstartProp))) anEvent->setDtStart(anEvent->dtEnd()); if (!(vo = isAPropertyOf(vevent, VCDTendProp))) anEvent->setDtEnd(anEvent->dtStart()); #endif // TODO: exdates #if 0 // recurrence exceptions if ((vo = isAPropertyOf(vevent, VCExDateProp)) != 0) { anEvent->setExDates(s = fakeCString(vObjectUStringZValue(vo))); deleteStr(s); } #endif #if 0 // secrecy if ((vo = isAPropertyOf(vevent, VCClassProp)) != 0) { anEvent->setSecrecy(s = fakeCString(vObjectUStringZValue(vo))); deleteStr(s); } else anEvent->setSecrecy("PUBLIC"); // attachments tmpStrList.clear(); initPropIterator(&voi, vevent); while (moreIteration(&voi)) { vo = nextVObject(&voi); if (strcmp(vObjectName(vo), VCAttachProp) == 0) { tmpStrList.append(s = fakeCString(vObjectUStringZValue(vo))); deleteStr(s); } } anEvent->setAttachments(tmpStrList); // resources if ((vo = isAPropertyOf(vevent, VCResourcesProp)) != 0) { QString resources = (s = fakeCString(vObjectUStringZValue(vo))); deleteStr(s); tmpStrList.clear(); index1 = 0; index2 = 0; QString resource; while ((index2 = resources.find(';', index1)) != -1) { resource = resources.mid(index1, (index2 - index1)); tmpStrList.append(resource); index1 = index2; } anEvent->setResources(tmpStrList); } #endif case ICAL_RELATEDTO_PROPERTY: // releated event (parent) event->setRelatedToUid(QString::fromUtf8(icalproperty_get_relatedto(p))); mEventsRelate.append(event); break; case ICAL_TRANSP_PROPERTY: // Transparency if(icalproperty_get_transp(p) == ICAL_TRANSP_TRANSPARENT ) event->setTransparency( Event::Transparent ); else event->setTransparency( Event::Opaque ); break; default: // kdDebug(5800) << "ICALFormat::readEvent(): Unknown property: " << kind // << endl; break; } p = icalcomponent_get_next_property(vevent,ICAL_ANY_PROPERTY); } QString msade = event->nonKDECustomProperty("X-MICROSOFT-CDO-ALLDAYEVENT"); if (!msade.isNull()) { bool floats = (msade == QString::fromLatin1("TRUE")); kdDebug(5800) << "ICALFormat::readEvent(): all day event: " << floats << endl; event->setFloats(floats); if (floats) { QDateTime endDate = event->dtEnd(); event->setDtEnd(endDate.addDays(-1)); } } @@ -1150,385 +1153,385 @@ void ICalFormatImpl::readIncidence(icalcomponent *parent,Incidence *incidence) int intvalue; icaltimetype icaltime; icaldurationtype icalduration; struct icalrecurrencetype rectype; QStringList categories; while (p) { icalproperty_kind kind = icalproperty_isa(p); switch (kind) { case ICAL_CREATED_PROPERTY: icaltime = icalproperty_get_created(p); incidence->setCreated(readICalDateTime(icaltime)); break; case ICAL_SEQUENCE_PROPERTY: // sequence intvalue = icalproperty_get_sequence(p); incidence->setRevision(intvalue); break; case ICAL_LASTMODIFIED_PROPERTY: // last modification date icaltime = icalproperty_get_lastmodified(p); incidence->setLastModified(readICalDateTime(icaltime)); break; case ICAL_DTSTART_PROPERTY: // start date and time icaltime = icalproperty_get_dtstart(p); if (icaltime.is_date) { incidence->setDtStart(QDateTime(readICalDate(icaltime),QTime(0,0,0))); incidence->setFloats(true); } else { incidence->setDtStart(readICalDateTime(icaltime)); } break; case ICAL_DURATION_PROPERTY: // start date and time icalduration = icalproperty_get_duration(p); incidence->setDuration(readICalDuration(icalduration)); break; case ICAL_DESCRIPTION_PROPERTY: // description text = icalproperty_get_description(p); incidence->setDescription(QString::fromUtf8(text)); break; case ICAL_SUMMARY_PROPERTY: // summary { text = icalproperty_get_summary(p); incidence->setSummary(QString::fromUtf8(text)); } break; case ICAL_STATUS_PROPERTY: // summary { if ( ICAL_STATUS_CANCELLED == icalproperty_get_status(p) ) incidence->setCancelled( true ); } break; case ICAL_LOCATION_PROPERTY: // location text = icalproperty_get_location(p); incidence->setLocation(QString::fromUtf8(text)); break; case ICAL_RECURRENCEID_PROPERTY: icaltime = icalproperty_get_recurrenceid(p); incidence->setRecurrenceID( readICalDateTime(icaltime) ); //qDebug(" RecurrenceID %s",incidence->recurrenceID().toString().latin1() ); break; #if 0 // status if ((vo = isAPropertyOf(vincidence, VCStatusProp)) != 0) { incidence->setStatus(s = fakeCString(vObjectUStringZValue(vo))); deleteStr(s); } else incidence->setStatus("NEEDS ACTION"); #endif case ICAL_PRIORITY_PROPERTY: // priority intvalue = icalproperty_get_priority(p); incidence->setPriority(intvalue); break; case ICAL_CATEGORIES_PROPERTY: // categories text = icalproperty_get_categories(p); categories.append(QString::fromUtf8(text)); break; //******************************************* case ICAL_RRULE_PROPERTY: // we do need (maybe )start datetime of incidence for recurrence // such that we can read recurrence only after we read incidence completely readrec = true; rectype = icalproperty_get_rrule(p); break; case ICAL_EXDATE_PROPERTY: icaltime = icalproperty_get_exdate(p); incidence->addExDate(readICalDate(icaltime)); break; case ICAL_CLASS_PROPERTY: { int inttext = icalproperty_get_class(p); if (inttext == ICAL_CLASS_PUBLIC ) { incidence->setSecrecy(Incidence::SecrecyPublic); } else if (inttext == ICAL_CLASS_CONFIDENTIAL ) { incidence->setSecrecy(Incidence::SecrecyConfidential); } else { incidence->setSecrecy(Incidence::SecrecyPrivate); } } break; case ICAL_ATTACH_PROPERTY: // attachments incidence->addAttachment(readAttachment(p)); break; default: // kdDebug(5800) << "ICALFormat::readIncidence(): Unknown property: " << kind // << endl; break; } p = icalcomponent_get_next_property(parent,ICAL_ANY_PROPERTY); } if ( readrec ) { readRecurrenceRule(rectype,incidence); } // kpilot stuff // TODO: move this application-specific code to kpilot QString kp = incidence->nonKDECustomProperty("X-PILOTID"); if (!kp.isNull()) { incidence->setPilotId(kp.toInt()); } kp = incidence->nonKDECustomProperty("X-PILOTSTAT"); if (!kp.isNull()) { incidence->setSyncStatus(kp.toInt()); } kp = incidence->nonKDECustomProperty("X-KOPIEXTID"); if (!kp.isNull()) { incidence->setIDStr(kp); } // Cancel backwards compatibility mode for subsequent changes by the application if ( readrec ) incidence->recurrence()->setCompatVersion(); // add categories incidence->setCategories(categories); // iterate through all alarms for (icalcomponent *alarm = icalcomponent_get_first_component(parent,ICAL_VALARM_COMPONENT); alarm; alarm = icalcomponent_get_next_component(parent,ICAL_VALARM_COMPONENT)) { readAlarm(alarm,incidence); } } void ICalFormatImpl::readIncidenceBase(icalcomponent *parent,IncidenceBase *incidenceBase) { icalproperty *p = icalcomponent_get_first_property(parent,ICAL_ANY_PROPERTY); while (p) { icalproperty_kind kind = icalproperty_isa(p); switch (kind) { case ICAL_UID_PROPERTY: // unique id incidenceBase->setUid(QString::fromUtf8(icalproperty_get_uid(p))); break; case ICAL_ORGANIZER_PROPERTY: // organizer incidenceBase->setOrganizer(QString::fromUtf8(icalproperty_get_organizer(p))); break; case ICAL_ATTENDEE_PROPERTY: // attendee incidenceBase->addAttendee(readAttendee(p)); break; default: break; } p = icalcomponent_get_next_property(parent,ICAL_ANY_PROPERTY); } // custom properties readCustomProperties(parent, incidenceBase); } void ICalFormatImpl::readCustomProperties(icalcomponent *parent,CustomProperties *properties) { - QMap<QCString, QString> customProperties; + QMap<Q3CString, QString> customProperties; icalproperty *p = icalcomponent_get_first_property(parent,ICAL_X_PROPERTY); while (p) { QString value = QString::fromUtf8(icalproperty_get_x(p)); customProperties[icalproperty_get_x_name(p)] = value; //qDebug("ICalFormatImpl::readCustomProperties %s %s",value.latin1(), icalproperty_get_x_name(p) ); p = icalcomponent_get_next_property(parent,ICAL_X_PROPERTY); } properties->setCustomProperties(customProperties); } void ICalFormatImpl::readRecurrenceRule(struct icalrecurrencetype rrule,Incidence *incidence) { // kdDebug(5800) << "Read recurrence for " << incidence->summary() << endl; Recurrence *recur = incidence->recurrence(); recur->setCompatVersion(mCalendarVersion); recur->unsetRecurs(); struct icalrecurrencetype r = rrule; dumpIcalRecurrence(r); readRecurrence( r, recur, incidence); } void ICalFormatImpl::readRecurrence( const struct icalrecurrencetype &r, Recurrence* recur, Incidence *incidence) { int wkst; int index = 0; short day = 0; QBitArray qba(7); int frequ = r.freq; int interv = r.interval; // preprocessing for odd recurrence definitions if ( r.freq == ICAL_MONTHLY_RECURRENCE ) { if ( r.by_month[0] != ICAL_RECURRENCE_ARRAY_MAX) { interv = 12; } } if ( r.freq == ICAL_YEARLY_RECURRENCE ) { if ( r.by_month[0] != ICAL_RECURRENCE_ARRAY_MAX && r.by_day[0] != ICAL_RECURRENCE_ARRAY_MAX ) { frequ = ICAL_MONTHLY_RECURRENCE; interv = 12* r.interval; } } switch (frequ) { case ICAL_MINUTELY_RECURRENCE: if (!icaltime_is_null_time(r.until)) { recur->setMinutely(interv,readICalDateTime(r.until)); } else { if (r.count == 0) recur->setMinutely(interv,-1); else recur->setMinutely(interv,r.count); } break; case ICAL_HOURLY_RECURRENCE: if (!icaltime_is_null_time(r.until)) { recur->setHourly(interv,readICalDateTime(r.until)); } else { if (r.count == 0) recur->setHourly(interv,-1); else recur->setHourly(interv,r.count); } break; case ICAL_DAILY_RECURRENCE: if (!icaltime_is_null_time(r.until)) { recur->setDaily(interv,readICalDate(r.until)); } else { if (r.count == 0) recur->setDaily(interv,-1); else recur->setDaily(interv,r.count); } break; case ICAL_WEEKLY_RECURRENCE: // kdDebug(5800) << "WEEKLY_RECURRENCE" << endl; wkst = (r.week_start + 5)%7 + 1; if (!icaltime_is_null_time(r.until)) { recur->setWeekly(interv,qba,readICalDate(r.until),wkst); } else { if (r.count == 0) recur->setWeekly(interv,qba,-1,wkst); else recur->setWeekly(interv,qba,r.count,wkst); } if ( r.by_day[0] == ICAL_RECURRENCE_ARRAY_MAX) { int wday = incidence->dtStart().date().dayOfWeek ()-1; //qDebug("weekly error found "); qba.setBit(wday); } else { while((day = r.by_day[index++]) != ICAL_RECURRENCE_ARRAY_MAX) { // kdDebug(5800) << " " << day << endl; qba.setBit((day+5)%7); // convert from Sunday=1 to Monday=0 } } break; case ICAL_MONTHLY_RECURRENCE: if (r.by_day[0] != ICAL_RECURRENCE_ARRAY_MAX) { if (!icaltime_is_null_time(r.until)) { recur->setMonthly(Recurrence::rMonthlyPos,interv, readICalDate(r.until)); } else { if (r.count == 0) recur->setMonthly(Recurrence::rMonthlyPos,interv,-1); else recur->setMonthly(Recurrence::rMonthlyPos,interv,r.count); } bool useSetPos = false; short pos = 0; while((day = r.by_day[index++]) != ICAL_RECURRENCE_ARRAY_MAX) { // kdDebug(5800) << "----a " << index << ": " << day << endl; pos = icalrecurrencetype_day_position(day); if (pos) { day = icalrecurrencetype_day_day_of_week(day); QBitArray ba(7); // don't wipe qba ba.setBit((day+5)%7); // convert from Sunday=1 to Monday=0 recur->addMonthlyPos(pos,ba); } else { qba.setBit((day+5)%7); // convert from Sunday=1 to Monday=0 useSetPos = true; } } if (useSetPos) { if (r.by_set_pos[0] != ICAL_RECURRENCE_ARRAY_MAX) { recur->addMonthlyPos(r.by_set_pos[0],qba); } } } else if (r.by_month_day[0] != ICAL_RECURRENCE_ARRAY_MAX) { if (!icaltime_is_null_time(r.until)) { recur->setMonthly(Recurrence::rMonthlyDay,interv, readICalDate(r.until)); } else { if (r.count == 0) recur->setMonthly(Recurrence::rMonthlyDay,interv,-1); else recur->setMonthly(Recurrence::rMonthlyDay,interv,r.count); } while((day = r.by_month_day[index++]) != ICAL_RECURRENCE_ARRAY_MAX) { // kdDebug(5800) << "----b " << day << endl; recur->addMonthlyDay(day); } } break; case ICAL_YEARLY_RECURRENCE: if (r.by_year_day[0] != ICAL_RECURRENCE_ARRAY_MAX) { //qDebug(" YEARLY DAY OF YEAR"); if (!icaltime_is_null_time(r.until)) { recur->setYearly(Recurrence::rYearlyDay,interv, readICalDate(r.until)); } else { if (r.count == 0) recur->setYearly(Recurrence::rYearlyDay,interv,-1); else recur->setYearly(Recurrence::rYearlyDay,interv,r.count); } while((day = r.by_year_day[index++]) != ICAL_RECURRENCE_ARRAY_MAX) { recur->addYearlyNum(day); } } else if ( true /*r.by_month[0] != ICAL_RECURRENCE_ARRAY_MAX*/) { if (r.by_day[0] != ICAL_RECURRENCE_ARRAY_MAX) { qDebug("YEARLY POS NOT SUPPORTED BY GUI"); if (!icaltime_is_null_time(r.until)) { recur->setYearly(Recurrence::rYearlyPos,interv, readICalDate(r.until)); } else { if (r.count == 0) recur->setYearly(Recurrence::rYearlyPos,interv,-1); else recur->setYearly(Recurrence::rYearlyPos,interv,r.count); } bool useSetPos = false; short pos = 0; while((day = r.by_day[index++]) != ICAL_RECURRENCE_ARRAY_MAX) { // kdDebug(5800) << "----a " << index << ": " << day << endl; pos = icalrecurrencetype_day_position(day); if (pos) { day = icalrecurrencetype_day_day_of_week(day); QBitArray ba(7); // don't wipe qba ba.setBit((day+5)%7); // convert from Sunday=1 to Monday=0 recur->addYearlyMonthPos(pos,ba); } else { qba.setBit((day+5)%7); // convert from Sunday=1 to Monday=0 useSetPos = true; } diff --git a/libkcal/icalformatimpl.h b/libkcal/icalformatimpl.h index 203c302..3a35b4c 100644 --- a/libkcal/icalformatimpl.h +++ b/libkcal/icalformatimpl.h @@ -1,109 +1,111 @@ /* This file is part of libkcal. Copyright (c) 2001 Cornelius Schumacher <schumacher@kde.org> 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #ifndef ICALFORMATIMPL_H #define ICALFORMATIMPL_H #include <qstring.h> +//Added by qt3to4: +#include <Q3PtrList> #include "scheduler.h" #include "freebusy.h" extern "C" { #include <ical.h> #include <icalss.h> } namespace KCal { class Compat; /** This class provides the libical dependent functions for ICalFormat. */ class ICalFormatImpl { public: /** Create new iCal format for calendar object */ ICalFormatImpl( ICalFormat *parent ); virtual ~ICalFormatImpl(); bool populate( Calendar *, icalcomponent *fs); icalcomponent *writeIncidence(Incidence *incidence); icalcomponent *writeTodo(Todo *todo); icalcomponent *writeEvent(Event *event); icalcomponent *writeFreeBusy(FreeBusy *freebusy, Scheduler::Method method); icalcomponent *writeJournal(Journal *journal); void writeIncidence(icalcomponent *parent,Incidence *incidence); icalproperty *writeAttendee(Attendee *attendee); icalproperty *writeAttachment(Attachment *attach); icalproperty *writeRecurrenceRule(Recurrence *); icalcomponent *writeAlarm(Alarm *alarm); QString extractErrorProperty(icalcomponent *); Todo *readTodo(icalcomponent *vtodo); Event *readEvent(icalcomponent *vevent); FreeBusy *readFreeBusy(icalcomponent *vfreebusy); Journal *readJournal(icalcomponent *vjournal); Attendee *readAttendee(icalproperty *attendee); Attachment *readAttachment(icalproperty *attach); void readIncidence(icalcomponent *parent,Incidence *incidence); void readRecurrenceRule(struct icalrecurrencetype rrule,Incidence *event); void readRecurrence( const struct icalrecurrencetype &r, Recurrence* recur,Incidence *event ); void readAlarm(icalcomponent *alarm,Incidence *incidence); /** Return the PRODID string loaded from calendar file */ const QString &loadedProductId() { return mLoadedProductId; } icaltimetype writeICalDate(const QDate &); QDate readICalDate(icaltimetype); icaltimetype writeICalDateTime(const QDateTime &); QDateTime readICalDateTime(icaltimetype); icaldurationtype writeICalDuration(int seconds); int readICalDuration(icaldurationtype); icalcomponent *createCalendarComponent(Calendar * = 0); icalcomponent *createScheduleComponent(IncidenceBase *,Scheduler::Method); private: void writeIncidenceBase(icalcomponent *parent,IncidenceBase *); void readIncidenceBase(icalcomponent *parent,IncidenceBase *); void writeCustomProperties(icalcomponent *parent,CustomProperties *); void readCustomProperties(icalcomponent *parent,CustomProperties *); void dumpIcalRecurrence(icalrecurrencetype); ICalFormat *mParent; Calendar *mCalendar; QString mLoadedProductId; // PRODID string loaded from calendar file int mCalendarVersion; // determines backward compatibility mode on read - QPtrList<Event> mEventsRelate; // events with relations - QPtrList<Todo> mTodosRelate; // todos with relations + Q3PtrList<Event> mEventsRelate; // events with relations + Q3PtrList<Todo> mTodosRelate; // todos with relations static const int mSecondsPerWeek; static const int mSecondsPerDay; static const int mSecondsPerHour; static const int mSecondsPerMinute; Compat *mCompat; }; } #endif diff --git a/libkcal/imipscheduler.cpp b/libkcal/imipscheduler.cpp index e186f8e..e6d56a6 100644 --- a/libkcal/imipscheduler.cpp +++ b/libkcal/imipscheduler.cpp @@ -1,58 +1,60 @@ /* This file is part of libkcal. Copyright (c) 2001 Cornelius Schumacher <schumacher@kde.org> 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ // // IMIPScheduler - iMIP implementation of iTIP methods // #include "event.h" #include "icalformat.h" #include "imipscheduler.h" +//Added by qt3to4: +#include <Q3PtrList> using namespace KCal; IMIPScheduler::IMIPScheduler(Calendar *calendar) : Scheduler(calendar) { } IMIPScheduler::~IMIPScheduler() { } bool IMIPScheduler::publish (IncidenceBase *incidence,const QString &recipients) { return false; } bool IMIPScheduler::performTransaction(IncidenceBase *incidence,Method method) { mFormat->createScheduleMessage(incidence,method); return false; } -QPtrList<ScheduleMessage> IMIPScheduler::retrieveTransactions() +Q3PtrList<ScheduleMessage> IMIPScheduler::retrieveTransactions() { - QPtrList<ScheduleMessage> messageList; + Q3PtrList<ScheduleMessage> messageList; return messageList; } diff --git a/libkcal/imipscheduler.h b/libkcal/imipscheduler.h index f142060..5a2d38e 100644 --- a/libkcal/imipscheduler.h +++ b/libkcal/imipscheduler.h @@ -1,49 +1,49 @@ /* This file is part of libkcal. Copyright (c) 2001 Cornelius Schumacher <schumacher@kde.org> 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #ifndef IMIPSCHEDULER_H #define IMIPSCHEDULER_H // // iMIP implementation of iTIP methods // -#include <qptrlist.h> +#include <q3ptrlist.h> #include "scheduler.h" namespace KCal { /* This class implements the iTIP interface using the email interface specified as iMIP. */ class IMIPScheduler : public Scheduler { public: IMIPScheduler(Calendar *); virtual ~IMIPScheduler(); bool publish (IncidenceBase *incidence,const QString &recipients); bool performTransaction(IncidenceBase *incidence,Method method); - QPtrList<ScheduleMessage> retrieveTransactions(); + Q3PtrList<ScheduleMessage> retrieveTransactions(); }; } #endif // IMIPSCHEDULER_H diff --git a/libkcal/incidence.cpp b/libkcal/incidence.cpp index 7dd9bd2..8fcdc69 100644 --- a/libkcal/incidence.cpp +++ b/libkcal/incidence.cpp @@ -1,872 +1,874 @@ /* This file is part of libkcal. Copyright (c) 2001 Cornelius Schumacher <schumacher@kde.org> 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #include <kglobal.h> #include <klocale.h> #include <kdebug.h> #include "calformat.h" #include "incidence.h" #include "todo.h" +//Added by qt3to4: +#include <Q3PtrList> using namespace KCal; Incidence::Incidence() : IncidenceBase(), mRelatedTo(0), mSecrecy(SecrecyPublic), mPriority(3) { mRecurrence = 0;//new Recurrence(this); mCancelled = false; recreate(); mHasStartDate = true; mAlarms.setAutoDelete(true); mAttachments.setAutoDelete(true); mHasRecurrenceID = false; mHoliday = false; mBirthday = false; mAnniversary = false; } Incidence::Incidence( const Incidence &i ) : IncidenceBase( i ) { // TODO: reenable attributes currently commented out. mRevision = i.mRevision; mCreated = i.mCreated; mDescription = i.mDescription; mSummary = i.mSummary; mCategories = i.mCategories; // Incidence *mRelatedTo; Incidence *mRelatedTo; mRelatedTo = 0; mRelatedToUid = i.mRelatedToUid; // QPtrList<Incidence> mRelations; QPtrList<Incidence> mRelations; mExDates = i.mExDates; - QPtrListIterator<Attachment> itat( i.mAttachments ); + Q3PtrListIterator<Attachment> itat( i.mAttachments ); Attachment *at; while( (at = itat.current()) ) { Attachment *a = new Attachment( *at ); mAttachments.append( a ); ++itat; } mAttachments.setAutoDelete( true ); mResources = i.mResources; mSecrecy = i.mSecrecy; mPriority = i.mPriority; mLocation = i.mLocation; mCancelled = i.mCancelled; mHasStartDate = i.mHasStartDate; - QPtrListIterator<Alarm> it( i.mAlarms ); + Q3PtrListIterator<Alarm> it( i.mAlarms ); const Alarm *a; while( (a = it.current()) ) { Alarm *b = new Alarm( *a ); b->setParent( this ); mAlarms.append( b ); ++it; } mAlarms.setAutoDelete(true); mHasRecurrenceID = i.mHasRecurrenceID; mRecurrenceID = i.mRecurrenceID; if ( i.mRecurrence ) mRecurrence = new Recurrence( *(i.mRecurrence), this ); else mRecurrence = 0; mHoliday = i.mHoliday ; mBirthday = i.mBirthday; mAnniversary = i.mAnniversary; } Incidence::~Incidence() { Incidence *ev; - QPtrList<Incidence> Relations = relations(); + Q3PtrList<Incidence> Relations = relations(); for (ev=Relations.first();ev;ev=Relations.next()) { if (ev->relatedTo() == this) ev->setRelatedTo(0); } if (relatedTo()) relatedTo()->removeRelation(this); if ( mRecurrence ) delete mRecurrence; } QString Incidence::durationText() { return "---"; } QString Incidence::durationText4Time( int offset ) { int min = offset/60; int hours = min /60; min = min % 60; int days = hours /24; hours = hours % 24; if ( doesFloat() || ( min == 0 && hours == 0 ) ) { if ( days == 1 ) return "1" + i18n(" day"); else return QString::number( days )+ i18n(" days"); } QString message = QString::number ( hours ) +":"; if ( min < 10 ) message += "0"; message += QString::number ( min ); if ( days > 0 ) { if ( days == 1 ) message = "1" + i18n(" day") + " "+message; else message = QString::number( days )+ i18n(" days") + " "+message; } return message; } bool Incidence::isHoliday() const { return mHoliday; } bool Incidence::isBirthday() const { return mBirthday ; } bool Incidence::isAnniversary() const { return mAnniversary ; } bool Incidence::hasRecurrenceID() const { return mHasRecurrenceID; } void Incidence::setHasRecurrenceID( bool b ) { mHasRecurrenceID = b; } void Incidence::setRecurrenceID(QDateTime d) { mRecurrenceID = d; mHasRecurrenceID = true; updated(); } QDateTime Incidence::recurrenceID () const { return mRecurrenceID; } bool Incidence::cancelled() const { return mCancelled; } void Incidence::setCancelled( bool b ) { mCancelled = b; updated(); } bool Incidence::hasStartDate() const { return mHasStartDate; } void Incidence::setHasStartDate(bool f) { if (mReadOnly) return; mHasStartDate = f; updated(); } // A string comparison that considers that null and empty are the same static bool stringCompare( const QString& s1, const QString& s2 ) { if ( s1.isEmpty() && s2.isEmpty() ) return true; return s1 == s2; } bool KCal::operator==( const Incidence& i1, const Incidence& i2 ) { if( i1.alarms().count() != i2.alarms().count() ) { return false; // no need to check further } if ( i1.alarms().count() > 0 ) { if ( !( *(i1.alarms().first()) == *(i2.alarms().first())) ) { qDebug("alarm not equal "); return false; } } #if 0 - QPtrListIterator<Alarm> a1( i1.alarms() ); - QPtrListIterator<Alarm> a2( i2.alarms() ); + Q3PtrListIterator<Alarm> a1( i1.alarms() ); + Q3PtrListIterator<Alarm> a2( i2.alarms() ); for( ; a1.current() && a2.current(); ++a1, ++a2 ) { if( *a1.current() == *a2.current() ) { continue; } else { return false; } } #endif if ( i1.hasRecurrenceID() == i2.hasRecurrenceID() ) { if ( i1.hasRecurrenceID() ) { if ( i1.recurrenceID() != i2.recurrenceID() ) return false; } } else { return false; } if ( ! operator==( (const IncidenceBase&)i1, (const IncidenceBase&)i2 ) ) return false; if ( i1.hasStartDate() == i2.hasStartDate() ) { if ( i1.hasStartDate() ) { if ( i1.dtStart() != i2.dtStart() ) return false; } } else { return false; } if ( i1.mRecurrence != 0 && i2.mRecurrence != 0 ) { if (!( *i1.mRecurrence == *i2.mRecurrence) ) { //qDebug("recurrence is NOT equal "); return false; } } else { // one ( or both ) recurrence is 0 if ( i1.mRecurrence == 0 ) { if ( i2.mRecurrence != 0 && i2.mRecurrence->doesRecur() != Recurrence::rNone ) return false; } else { // i1.mRecurrence != 0 // i2.mRecurrence == 0 if ( i1.mRecurrence->doesRecur() != Recurrence::rNone ) return false; } } return // i1.created() == i2.created() && stringCompare( i1.description(), i2.description() ) && stringCompare( i1.summary(), i2.summary() ) && i1.categories() == i2.categories() && // no need to compare mRelatedTo stringCompare( i1.relatedToUid(), i2.relatedToUid() ) && // i1.relations() == i2.relations() && i1.exDates() == i2.exDates() && i1.attachments() == i2.attachments() && i1.resources() == i2.resources() && i1.secrecy() == i2.secrecy() && i1.priority() == i2.priority() && i1.cancelled() == i2.cancelled() && stringCompare( i1.location(), i2.location() ); } Incidence* Incidence::recreateCloneException( QDate d ) { Incidence* newInc = clone(); newInc->recreate(); if ( doesRecur() ) { addExDate( d ); newInc->recurrence()->unsetRecurs(); if ( typeID() == eventID ) { int len = dtStart().secsTo( ((Event*)this)->dtEnd()); QTime tim = dtStart().time(); newInc->setDtStart( QDateTime(d, tim) ); ((Event*)newInc)->setDtEnd( newInc->dtStart().addSecs( len ) ); } else { int len = dtStart().secsTo( ((Todo*)this)->dtDue()); QTime tim = ((Todo*)this)->dtDue().time(); ((Todo*)newInc)->setDtDue( QDateTime(d, tim) ); ((Todo*)newInc)->setDtStart( ((Todo*)newInc)->dtDue().addSecs( -len ) ); ((Todo*)this)->setRecurDates(); } newInc->setExDates( DateList () ); } return newInc; } void Incidence::recreate() { setCreated(QDateTime::currentDateTime()); setUid(CalFormat::createUniqueId()); setRevision(0); setIDStr( ":" ); setLastModified(QDateTime::currentDateTime()); } void Incidence::cloneRelations( Incidence * newInc ) { // newInc is already a clone of this incidence Incidence * inc; Incidence * cloneInc; - QPtrList<Incidence> Relations = relations(); + Q3PtrList<Incidence> Relations = relations(); for (inc=Relations.first();inc;inc=Relations.next()) { cloneInc = inc->clone(); cloneInc->recreate(); cloneInc->setRelatedTo( newInc ); inc->cloneRelations( cloneInc ); } } void Incidence::setReadOnly( bool readOnly ) { IncidenceBase::setReadOnly( readOnly ); if ( mRecurrence ) mRecurrence->setRecurReadOnly( readOnly); } void Incidence::setLastModifiedSubInvalid() { mLastModifiedSub = QDateTime(); if ( mRelatedTo ) mRelatedTo->setLastModifiedSubInvalid(); } QString Incidence::lastModifiedSubSortKey() const { if ( mLastModifiedSubSortKey.isEmpty() ) return lastModifiedSortKey(); return mLastModifiedSubSortKey; } QDateTime Incidence::lastModifiedSub() { if ( !mRelations.count() ) return lastModified(); if ( mLastModifiedSub.isValid() ) return mLastModifiedSub; mLastModifiedSub = lastModified(); Incidence * inc; - QPtrList<Incidence> Relations = relations(); + Q3PtrList<Incidence> Relations = relations(); for (inc=Relations.first();inc;inc=Relations.next()) { if ( inc->lastModifiedSub() > mLastModifiedSub ) mLastModifiedSub = inc->lastModifiedSub(); } mLastModifiedSubSortKey.sprintf("%04d%02d%02d%02d%02d%02d", mLastModifiedSub.date().year(), mLastModifiedSub.date().month(), mLastModifiedSub.date().day(), mLastModifiedSub.time().hour(), mLastModifiedSub.time().minute(), mLastModifiedSub.time().second() ); return mLastModifiedSub; } void Incidence::setCreated(QDateTime created) { if (mReadOnly) return; mCreated = getEvenTime(created); } QDateTime Incidence::created() const { return mCreated; } void Incidence::setRevision(int rev) { if (mReadOnly) return; mRevision = rev; updated(); } int Incidence::revision() const { return mRevision; } void Incidence::setDtStart(const QDateTime &dtStart) { QDateTime dt = getEvenTime(dtStart); if ( mRecurrence ) mRecurrence->setRecurStart( dt); IncidenceBase::setDtStart( dt ); } void Incidence::setDescription(const QString &description) { if (mReadOnly) return; mDescription = description; updated(); } QString Incidence::description() const { return mDescription; } void Incidence::setSummary(const QString &summary) { if (mReadOnly) return; mSummary = summary; updated(); } QString Incidence::summary() const { return mSummary; } void Incidence::checkCategories() { mHoliday = mCategories.contains("Holiday") || mCategories.contains(i18n("Holiday")); mBirthday = mCategories.contains("Birthday") || mCategories.contains(i18n("Birthday")); mAnniversary = mCategories.contains("Anniversary") || mCategories.contains(i18n("Anniversary")); } void Incidence::addCategories(const QStringList &categories, bool addToRelations ) //addToRelations = false { if (mReadOnly) return; int i; for( i = 0; i < categories.count(); ++i ) { if ( !mCategories.contains (categories[i])) mCategories.append( categories[i] ); } checkCategories(); updated(); if ( addToRelations ) { Incidence * inc; - QPtrList<Incidence> Relations = relations(); + Q3PtrList<Incidence> Relations = relations(); for (inc=Relations.first();inc;inc=Relations.next()) { inc->addCategories( categories, true ); } } } void Incidence::setCategories(const QStringList &categories, bool setForRelations ) //setForRelations = false { if (mReadOnly) return; mCategories = categories; checkCategories(); updated(); if ( setForRelations ) { Incidence * inc; - QPtrList<Incidence> Relations = relations(); + Q3PtrList<Incidence> Relations = relations(); for (inc=Relations.first();inc;inc=Relations.next()) { inc->setCategories( categories, true ); } } } // TODO: remove setCategories(QString) function void Incidence::setCategories(const QString &catStr) { if (mReadOnly) return; mCategories.clear(); if (catStr.isEmpty()) return; mCategories = QStringList::split(",",catStr); QStringList::Iterator it; for(it = mCategories.begin();it != mCategories.end(); ++it) { *it = (*it).stripWhiteSpace(); } checkCategories(); updated(); } // using this makes filtering 3 times faster QStringList* Incidence::categoriesP() { return &mCategories; } QStringList Incidence::categories() const { return mCategories; } QString Incidence::categoriesStr() { return mCategories.join(","); } QString Incidence::categoriesStrWithSpace() { return mCategories.join(", "); } void Incidence::setRelatedToUid(const QString &relatedToUid) { if (mReadOnly) return; mRelatedToUid = relatedToUid; } void Incidence::clearRelations() { mRelatedTo = 0; mRelations.clear(); } QString Incidence::relatedToUid() const { return mRelatedToUid; } void Incidence::resetRelatedTo() { QString store = mRelatedToUid; setRelatedTo( 0 ); mRelatedToUid = store; } void Incidence::setRelatedTo(Incidence *relatedTo) { //qDebug("Incidence::setRelatedTo %d ", relatedTo); //qDebug("setRelatedTo(Incidence *relatedTo) %s %s", summary().latin1(), relatedTo->summary().latin1() ); if (mReadOnly || mRelatedTo == relatedTo) return; if(mRelatedTo) { // updated(); mRelatedTo->removeRelation(this); } mRelatedTo = relatedTo; if (mRelatedTo) { mRelatedTo->addRelation(this); mRelatedToUid = mRelatedTo->uid(); } else { mRelatedToUid = ""; } } Incidence *Incidence::relatedTo() const { return mRelatedTo; } -QPtrList<Incidence> Incidence::relations() const +Q3PtrList<Incidence> Incidence::relations() const { return mRelations; } -void Incidence::addRelationsToList(QPtrList<Incidence> *rel) +void Incidence::addRelationsToList(Q3PtrList<Incidence> *rel) { Incidence* inc; - QPtrList<Incidence> Relations = relations(); + Q3PtrList<Incidence> Relations = relations(); for (inc=Relations.first();inc;inc=Relations.next()) { inc->addRelationsToList( rel ); } if ( rel->findRef( this ) == -1 ) rel->append( this ); } void Incidence::addRelation(Incidence *event) { setLastModifiedSubInvalid(); if( mRelations.findRef( event ) == -1 ) { mRelations.append(event); //updated(); } } void Incidence::removeRelation(Incidence *event) { setLastModifiedSubInvalid(); mRelations.removeRef(event); // if (event->getRelatedTo() == this) event->setRelatedTo(0); } bool Incidence::recursOn(const QDate &qd) const { if (mRecurrence && mRecurrence->recursOnPure(qd) && !isException(qd)) return true; else return false; } void Incidence::setExDates(const DateList &exDates) { if (mReadOnly) return; mExDates = exDates; recurrence()->setRecurExDatesCount(mExDates.count()); updated(); } void Incidence::addExDate(const QDate &date) { if (mReadOnly) return; mExDates.append(date); recurrence()->setRecurExDatesCount(mExDates.count()); updated(); } DateList Incidence::exDates() const { return mExDates; } bool Incidence::isException(const QDate &date) const { DateList::ConstIterator it; for( it = mExDates.begin(); it != mExDates.end(); ++it ) { if ( (*it) == date ) { return true; } } return false; } void Incidence::addAttachment(Attachment *attachment) { if (mReadOnly || !attachment) return; mAttachments.append(attachment); updated(); } void Incidence::deleteAttachment(Attachment *attachment) { mAttachments.removeRef(attachment); } void Incidence::deleteAttachments(const QString& mime) { Attachment *at = mAttachments.first(); while (at) { if (at->mimeType() == mime) mAttachments.remove(); else at = mAttachments.next(); } } -QPtrList<Attachment> Incidence::attachments() const +Q3PtrList<Attachment> Incidence::attachments() const { return mAttachments; } -QPtrList<Attachment> Incidence::attachments(const QString& mime) const +Q3PtrList<Attachment> Incidence::attachments(const QString& mime) const { - QPtrList<Attachment> attachments; - QPtrListIterator<Attachment> it( mAttachments ); + Q3PtrList<Attachment> attachments; + Q3PtrListIterator<Attachment> it( mAttachments ); Attachment *at; while ( (at = it.current()) ) { if (at->mimeType() == mime) attachments.append(at); ++it; } return attachments; } void Incidence::setResources(const QStringList &resources) { if (mReadOnly) return; mResources = resources; updated(); } QStringList Incidence::resources() const { return mResources; } void Incidence::setPriority(int priority) { if (mReadOnly) return; mPriority = priority; updated(); } int Incidence::priority() const { return mPriority; } void Incidence::setSecrecy(int sec) { if (mReadOnly) return; mSecrecy = sec; updated(); } int Incidence::secrecy() const { return mSecrecy; } QString Incidence::secrecyStr() const { return secrecyName(mSecrecy); } QString Incidence::secrecyName(int secrecy) { switch (secrecy) { case SecrecyPublic: return i18n("Public"); break; case SecrecyPrivate: return i18n("Private"); break; case SecrecyConfidential: return i18n("Confidential"); break; default: return i18n("Undefined"); break; } } QStringList Incidence::secrecyList() { QStringList list; list << secrecyName(SecrecyPublic); list << secrecyName(SecrecyPrivate); list << secrecyName(SecrecyConfidential); return list; } -QPtrList<Alarm> Incidence::alarms() const +Q3PtrList<Alarm> Incidence::alarms() const { return mAlarms; } Alarm* Incidence::newAlarm() { Alarm* alarm = new Alarm(this); mAlarms.append(alarm); // updated(); return alarm; } void Incidence::addAlarm(Alarm *alarm) { mAlarms.append(alarm); updated(); } void Incidence::removeAlarm(Alarm *alarm) { mAlarms.removeRef(alarm); updated(); } void Incidence::clearAlarms() { mAlarms.clear(); updated(); } bool Incidence::isAlarmEnabled() const { Alarm* alarm; - for (QPtrListIterator<Alarm> it(mAlarms); (alarm = it.current()) != 0; ++it) { + for (Q3PtrListIterator<Alarm> it(mAlarms); (alarm = it.current()) != 0; ++it) { if (alarm->enabled()) return true; } return false; } #include <stdlib.h> Recurrence *Incidence::recurrence() { if ( ! mRecurrence ) { mRecurrence = new Recurrence(this); mRecurrence->setRecurStart( dtStart() ); mRecurrence->setRecurReadOnly( isReadOnly()); //qDebug("creating new recurence "); //abort(); } return mRecurrence; } void Incidence::setRecurrence( Recurrence * r) { if ( mRecurrence ) delete mRecurrence; mRecurrence = r; } void Incidence::setLocation(const QString &location) { if (mReadOnly) return; mLocation = location; updated(); } QString Incidence::location() const { return mLocation; } QString Incidence::recurrenceText() const { if ( mRecurrence ) return mRecurrence->recurrenceText(); return i18n("No"); } ushort Incidence::doesRecur() const { if ( mRecurrence ) return mRecurrence->doesRecur(); else return Recurrence::rNone; } QDateTime Incidence::getNextOccurence( const QDateTime& dt, bool* ok ) const { QDateTime incidenceStart = dt; *ok = false; if ( doesRecur() ) { bool last; mRecurrence->getPreviousDateTime( incidenceStart , &last ); int count = 0; if ( !last ) { while ( !last ) { ++count; incidenceStart = mRecurrence->getNextDateTime( incidenceStart, &last ); if ( recursOn( incidenceStart.date() ) ) { last = true; // exit while llop } else { if ( last ) { // no alarm on last recurrence return QDateTime (); } int year = incidenceStart.date().year(); // workaround for bug in recurrence if ( count == 100 || year < 1000 || year > 5000 ) { return QDateTime (); } incidenceStart = incidenceStart.addSecs( 1 ); } } } else { return QDateTime (); } } else { if ( hasStartDate () ) { incidenceStart = dtStart(); } if ( typeID() == todoID ) { if ( ((Todo*)this)->hasDueDate() ) incidenceStart = ((Todo*)this)->dtDue(); } } if ( incidenceStart > dt ) *ok = true; return incidenceStart; } QDateTime Incidence::dtStart() const { if ( doesRecur() ) { if ( typeID() == todoID ) { ((Todo*)this)->checkSetCompletedFalse(); } } return mDtStart; } diff --git a/libkcal/incidence.h b/libkcal/incidence.h index f89942f..2940129 100644 --- a/libkcal/incidence.h +++ b/libkcal/incidence.h @@ -1,327 +1,329 @@ /* This file is part of libkcal. Copyright (c) 2001 Cornelius Schumacher <schumacher@kde.org> 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #ifndef INCIDENCE_H #define INCIDENCE_H // // Incidence - base class of calendaring components // #include <qdatetime.h> #include <qstringlist.h> -#include <qvaluelist.h> +#include <q3valuelist.h> +//Added by qt3to4: +#include <Q3PtrList> #include "recurrence.h" #include "alarm.h" #include "attachment.h" #include "listbase.h" #include "incidencebase.h" namespace KCal { class Event; class Todo; class Journal; /** This class provides the base class common to all calendar components. */ class Incidence : public IncidenceBase { public: /** This class provides the interface for a visitor of calendar components. It serves as base class for concrete visitors, which implement certain actions on calendar components. It allows to add functions, which operate on the concrete types of calendar components, without changing the calendar component classes. */ class Visitor { public: /** Destruct Incidence::Visitor */ virtual ~Visitor() {} /** Reimplement this function in your concrete subclass of IncidenceVisitor to perform actions on an Event object. */ virtual bool visit(Event *) { return false; } /** Reimplement this function in your concrete subclass of IncidenceVisitor to perform actions on an Todo object. */ virtual bool visit(Todo *) { return false; } /** Reimplement this function in your concrete subclass of IncidenceVisitor to perform actions on an Journal object. */ virtual bool visit(Journal *) { return false; } protected: /** Constructor is protected to prevent direct creation of visitor base class. */ Visitor() {} }; /** This class implements a visitor for adding an Incidence to a resource supporting addEvent(), addTodo() and addJournal() calls. */ template<class T> class AddVisitor : public Visitor { public: AddVisitor( T *r ) : mResource( r ) {} bool visit( Event *e ) { return mResource->addEvent( e ); } bool visit( Todo *t ) { return mResource->addTodo( t ); } bool visit( Journal *j ) { return mResource->addJournal( j ); } private: T *mResource; }; /** enumeration for describing an event's secrecy. */ enum { SecrecyPublic = 0, SecrecyPrivate = 1, SecrecyConfidential = 2 }; typedef ListBase<Incidence> List; Incidence(); Incidence(const Incidence &); ~Incidence(); /** Accept IncidenceVisitor. A class taking part in the visitor mechanism has to provide this implementation: <pre> bool accept(Visitor &v) { return v.visit(this); } </pre> */ virtual bool accept(Visitor &) { return false; } virtual Incidence *clone() = 0; virtual void cloneRelations( Incidence * ); - void addRelationsToList(QPtrList<Incidence> *rel); + void addRelationsToList(Q3PtrList<Incidence> *rel); void clearRelations(); virtual QDateTime getNextAlarmDateTime( bool * ok, int * offset, QDateTime start_dt ) const = 0; void setReadOnly( bool ); /** Recreate event. The event is made a new unique event, but already stored event information is preserved. Sets uniquie id, creation date, last modification date and revision number. */ void recreate(); Incidence* recreateCloneException(QDate); /** set creation date */ void setCreated(QDateTime); /** return time and date of creation. */ QDateTime created() const; /** set the number of revisions this event has seen */ void setRevision(int rev); /** return the number of revisions this event has seen */ int revision() const; /** Set starting date/time. */ virtual void setDtStart(const QDateTime &dtStart); /** Return the incidence's ending date/time as a QDateTime. */ virtual QDateTime dtEnd() const { return QDateTime(); } /** sets the event's lengthy description. */ void setDescription(const QString &description); /** returns a reference to the event's description. */ QString description() const; /** sets the event's short summary. */ void setSummary(const QString &summary); /** returns a reference to the event's summary. */ QString summary() const; /** set event's applicable categories */ void setCategories(const QStringList &categories, bool setForRelations = false); void addCategories(const QStringList &categories, bool addToRelations = false); /** set event's categories based on a comma delimited string */ void setCategories(const QString &catStr); /** return categories in a list */ QStringList categories() const; QStringList* categoriesP(); /** return categories as a comma separated string */ QString categoriesStr(); QString categoriesStrWithSpace(); /** point at some other event to which the event relates. This function should * only be used when constructing a calendar before the related Event * exists. */ void setRelatedToUid(const QString &); /** what event does this one relate to? This function should * only be used when constructing a calendar before the related Event * exists. */ QString relatedToUid() const; /** point at some other event to which the event relates */ void setRelatedTo(Incidence *relatedTo); void resetRelatedTo(); /** what event does this one relate to? */ Incidence *relatedTo() const; /** All events that are related to this event */ - QPtrList<Incidence> relations() const; + Q3PtrList<Incidence> relations() const; /** Add an event which is related to this event */ void addRelation(Incidence *); /** Remove event that is related to this event */ void removeRelation(Incidence *); /** returns the list of dates which are exceptions to the recurrence rule */ DateList exDates() const; /** sets the list of dates which are exceptions to the recurrence rule */ void setExDates(const DateList &_exDates); void setExDates(const char *dates); /** Add a date to the list of exceptions of the recurrence rule. */ void addExDate(const QDate &date); /** returns true if there is an exception for this date in the recurrence rule set, or false otherwise. */ bool isException(const QDate &qd) const; /** add attachment to this event */ void addAttachment(Attachment *attachment); /** remove and delete a specific attachment */ void deleteAttachment(Attachment *attachment); /** remove and delete all attachments with this mime type */ void deleteAttachments(const QString& mime); /** return list of all associated attachments */ - QPtrList<Attachment> attachments() const; + Q3PtrList<Attachment> attachments() const; /** find a list of attachments with this mime type */ - QPtrList<Attachment> attachments(const QString& mime) const; + Q3PtrList<Attachment> attachments(const QString& mime) const; /** sets the event's status the value specified. See the enumeration * above for possible values. */ void setSecrecy(int); /** return the event's secrecy. */ int secrecy() const; /** return the event's secrecy in string format. */ QString secrecyStr() const; /** return list of all availbale secrecy classes */ static QStringList secrecyList(); /** return human-readable name of secrecy class */ static QString secrecyName(int); /** returns TRUE if the date specified is one on which the event will * recur. */ bool recursOn(const QDate &qd) const; // VEVENT and VTODO, but not VJOURNAL (move to EventBase class?): /** set resources used, such as Office, Car, etc. */ void setResources(const QStringList &resources); /** return list of current resources */ QStringList resources() const; /** set the event's priority, 0 is undefined, 1 highest (decreasing order) */ void setPriority(int priority); /** get the event's priority */ int priority() const; /** All alarms that are associated with this incidence */ - QPtrList<Alarm> alarms() const; + Q3PtrList<Alarm> alarms() const; /** Create a new alarm which is associated with this incidence */ Alarm* newAlarm(); /** Add an alarm which is associated with this incidence */ void addAlarm(Alarm*); /** Remove an alarm that is associated with this incidence */ void removeAlarm(Alarm*); /** Remove all alarms that are associated with this incidence */ void clearAlarms(); /** return whether any alarm associated with this incidence is enabled */ bool isAlarmEnabled() const; /** Return the recurrence rule associated with this incidence. If there is none, returns an appropriate (non-0) object. */ Recurrence *recurrence(); void setRecurrence(Recurrence * r); /** Forward to Recurrence::doesRecur(). */ ushort doesRecur() const; /** set the event's/todo's location. Do _not_ use it with journal */ void setLocation(const QString &location); /** return the event's/todo's location. Do _not_ use it with journal */ QString location() const; /** returns TRUE or FALSE depending on whether the todo has a start date */ bool hasStartDate() const; /** sets the event's hasStartDate value. */ void setHasStartDate(bool f); QDateTime getNextOccurence( const QDateTime& dt, bool* yes ) const; bool cancelled() const; void setCancelled( bool b ); bool hasRecurrenceID() const; void setHasRecurrenceID( bool b ); void setRecurrenceID(QDateTime); QDateTime recurrenceID () const; QDateTime dtStart() const; bool isHoliday() const; bool isBirthday() const; bool isAnniversary() const; QDateTime lastModifiedSub(); QString lastModifiedSubSortKey() const; QString recurrenceText() const; void setLastModifiedSubInvalid(); virtual QString durationText(); QString durationText4Time( int secs ); Recurrence *mRecurrence; protected: - QPtrList<Alarm> mAlarms; - QPtrList<Incidence> mRelations; + Q3PtrList<Alarm> mAlarms; + Q3PtrList<Incidence> mRelations; QDateTime mRecurrenceID; bool mHasRecurrenceID; private: void checkCategories(); QString mLastModifiedSubSortKey; bool mHoliday, mBirthday, mAnniversary; int mRevision; bool mCancelled; // base components of jounal, event and todo QDateTime mCreated; QDateTime mLastModifiedSub; QString mDescription; QString mSummary; QStringList mCategories; Incidence *mRelatedTo; QString mRelatedToUid; DateList mExDates; - QPtrList<Attachment> mAttachments; + Q3PtrList<Attachment> mAttachments; QStringList mResources; bool mHasStartDate; // if todo has associated start date int mSecrecy; int mPriority; // 1 = highest, 2 = less, etc. //QPtrList<Alarm> mAlarms; QString mLocation; }; bool operator==( const Incidence&, const Incidence& ); } #endif diff --git a/libkcal/incidencebase.cpp b/libkcal/incidencebase.cpp index 56c0560..f11ec54 100644 --- a/libkcal/incidencebase.cpp +++ b/libkcal/incidencebase.cpp @@ -1,500 +1,502 @@ /* This file is part of libkcal. Copyright (c) 2001 Cornelius Schumacher <schumacher@kde.org> 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #include <kglobal.h> #include <klocale.h> #include <kdebug.h> #include <kidmanager.h> #include "calformat.h" #include "syncdefines.h" #include "incidencebase.h" +//Added by qt3to4: +#include <Q3PtrList> using namespace KCal; IncidenceBase::IncidenceBase() : mReadOnly(false), mFloats(true), mDuration(0), mHasDuration(false), mPilotId(0), mSyncStatus(SYNCMOD) { blockLastModified = false; setUid(CalFormat::createUniqueId()); mOrganizer = ""; mFloats = false; mDuration = 0; mHasDuration = false; mPilotId = 0; mExternalId = ":"; mTempSyncStat = SYNC_TEMPSTATE_INITIAL; mSyncStatus = 0; mAttendees.setAutoDelete( true ); mCalEnabled = true; mAlarmEnabled = true; mCalID = 0; } IncidenceBase::IncidenceBase(const IncidenceBase &i) : CustomProperties( i ) { blockLastModified = false; mReadOnly = i.mReadOnly; mDtStart = i.mDtStart; mDuration = i.mDuration; mHasDuration = i.mHasDuration; mOrganizer = i.mOrganizer; mUid = i.mUid; mCalEnabled = i.mCalEnabled; mAlarmEnabled = i.mAlarmEnabled; mCalID = i.mCalID; - QPtrList<Attendee> attendees = i.attendees(); + Q3PtrList<Attendee> attendees = i.attendees(); for( Attendee *a = attendees.first(); a; a = attendees.next() ) { mAttendees.append( new Attendee( *a ) ); } mFloats = i.mFloats; mLastModified = i.mLastModified; mPilotId = i.mPilotId; mTempSyncStat = i.mTempSyncStat; mSyncStatus = i.mSyncStatus; mExternalId = i.mExternalId; // The copied object is a new one, so it isn't observed by the observer // of the original object. mObservers.clear(); mAttendees.setAutoDelete( true ); } IncidenceBase::~IncidenceBase() { } bool KCal::operator==( const IncidenceBase& i1, const IncidenceBase& i2 ) { // do not compare mSyncStatus and mExternalId if( i1.attendees().count() != i2.attendees().count() ) { return false; // no need to check further } if ( i1.attendees().count() > 0 ) { Attendee * a1 = i1.attendees().first(), *a2 =i2.attendees().first() ; while ( a1 ) { if ( !( (*a1) == (*a2)) ) { //qDebug("Attendee not equal "); return false; } a1 = i1.attendees().next(); a2 = i2.attendees().next(); } } //if ( i1.dtStart() != i2.dtStart() ) // return false; #if 0 qDebug("1 %d ",i1.doesFloat() == i2.doesFloat() ); qDebug("1 %d ",i1.duration() == i2.duration() ); qDebug("3 %d ",i1.hasDuration() == i2.hasDuration() ); qDebug("1 %d ",i1.pilotId() == i2.pilotId() ); qDebug("1 %d %d %d",i1.syncStatus() == i2.syncStatus() , i1.syncStatus(),i2.syncStatus() ); qDebug("6 %d ",i1.organizer() == i2.organizer() ); #endif if ( i1.hasDuration() == i2.hasDuration() ) { if ( i1.hasDuration() ) { if ( i1.duration() != i2.duration() ) return false; } } else { return false; } return ( i1.organizer() == i2.organizer() && // i1.uid() == i2.uid() && // Don't compare lastModified, otherwise the operator is not // of much use. We are not comparing for identity, after all. i1.doesFloat() == i2.doesFloat() && i1.pilotId() == i2.pilotId() );// && i1.syncStatus() == i2.syncStatus() ); // no need to compare mObserver } QDateTime IncidenceBase::getEvenTime( QDateTime dt ) { QTime t = dt.time(); dt.setTime( QTime (t.hour (), t.minute (), t.second () ) ); return dt; } bool IncidenceBase::isTagged() const { return mIsTagged; } void IncidenceBase::setTagged( bool b) { mIsTagged = b; } void IncidenceBase::setCalID( int id ) { if ( mCalID > 0 ) { updated(); } mCalID = id; } void IncidenceBase::setCalID_block( int id ) { if ( mCalID > 0 ) { blockLastModified = true; updated(); blockLastModified = false; } mCalID = id; } int IncidenceBase::calID() const { return mCalID; } void IncidenceBase::setCalEnabled( bool b ) { mCalEnabled = b; } bool IncidenceBase::calEnabled() const { return mCalEnabled; } void IncidenceBase::setAlarmEnabled( bool b ) { mAlarmEnabled = b; } bool IncidenceBase::alarmEnabled() const { return mAlarmEnabled; } void IncidenceBase::setUid(const QString &uid) { mUid = uid; updated(); } QString IncidenceBase::uid() const { return mUid; } void IncidenceBase::setLastModifiedSubInvalid() { // virtual method } void IncidenceBase::setLastModified(const QDateTime &lm) { if ( blockLastModified ) return; // DON'T! updated() because we call this from // Calendar::updateEvent(). mLastModified = getEvenTime(lm); mLastModifiedKey.sprintf("%04d%02d%02d%02d%02d%02d", mLastModified.date().year(), mLastModified.date().month(), mLastModified.date().day(), mLastModified.time().hour(), mLastModified.time().minute(), mLastModified.time().second() ); setLastModifiedSubInvalid(); //qDebug("IncidenceBase::setLastModified %s ",lm.toString().latin1()); } QString IncidenceBase::lastModifiedSortKey() const { return mLastModifiedKey; } QDateTime IncidenceBase::lastModified() const { return mLastModified; } void IncidenceBase::setOrganizer(const QString &o) { // we don't check for readonly here, because it is // possible that by setting the organizer we are changing // the event's readonly status... mOrganizer = o; if (mOrganizer.left(7).upper() == "MAILTO:") mOrganizer = mOrganizer.remove(0,7); updated(); } QString IncidenceBase::organizer() const { return mOrganizer; } void IncidenceBase::setReadOnly( bool readOnly ) { mReadOnly = readOnly; } void IncidenceBase::setDtStart(const QDateTime &dtStart) { // if (mReadOnly) return; mDtStart = getEvenTime(dtStart); updated(); } QDateTime IncidenceBase::dtStart() const { return mDtStart; } QString IncidenceBase::dtStartTimeStr() const { return KGlobal::locale()->formatTime(dtStart().time()); } QString IncidenceBase::dtStartDateStr(bool shortfmt) const { return KGlobal::locale()->formatDate(dtStart().date(),shortfmt); } QString IncidenceBase::dtStartStr(bool shortfmt) const { if ( doesFloat() ) return KGlobal::locale()->formatDate(dtStart().date(),shortfmt); return KGlobal::locale()->formatDateTime(dtStart(), shortfmt); } bool IncidenceBase::doesFloat() const { return mFloats; } void IncidenceBase::setFloats(bool f) { if (mReadOnly) return; mFloats = f; updated(); } bool IncidenceBase::addAttendee(Attendee *a, bool doupdate) { if (mReadOnly) return false; if (a->name().left(7).upper() == "MAILTO:") a->setName(a->name().remove(0,7)); - QPtrListIterator<Attendee> qli(mAttendees); + Q3PtrListIterator<Attendee> qli(mAttendees); qli.toFirst(); while (qli) { if (*qli.current() == *a) return false; ++qli; } mAttendees.append(a); if (doupdate) updated(); return true; } #if 0 void IncidenceBase::removeAttendee(Attendee *a) { if (mReadOnly) return; mAttendees.removeRef(a); updated(); } void IncidenceBase::removeAttendee(const char *n) { Attendee *a; if (mReadOnly) return; for (a = mAttendees.first(); a; a = mAttendees.next()) if (a->getName() == n) { mAttendees.remove(); break; } } #endif void IncidenceBase::clearAttendees() { if (mReadOnly) return; mAttendees.clear(); } #if 0 Attendee *IncidenceBase::getAttendee(const char *n) const { - QPtrListIterator<Attendee> qli(mAttendees); + Q3PtrListIterator<Attendee> qli(mAttendees); qli.toFirst(); while (qli) { if (qli.current()->getName() == n) return qli.current(); ++qli; } return 0L; } #endif Attendee *IncidenceBase::attendeeByMail(const QString &email) { - QPtrListIterator<Attendee> qli(mAttendees); + Q3PtrListIterator<Attendee> qli(mAttendees); qli.toFirst(); while (qli) { if (qli.current()->email().lower() == email.lower()) return qli.current(); ++qli; } return 0L; } Attendee *IncidenceBase::attendeeByMails(const QStringList &emails, const QString& email) { - QPtrListIterator<Attendee> qli(mAttendees); + Q3PtrListIterator<Attendee> qli(mAttendees); QStringList mails = emails; if (!email.isEmpty()) { mails.append(email); } qli.toFirst(); while (qli) { for ( QStringList::Iterator it = mails.begin(); it != mails.end(); ++it ) { if (qli.current()->email().lower() == (*it).lower()) return qli.current(); } ++qli; } return 0L; } void IncidenceBase::setDuration(int seconds) { mDuration = seconds; setHasDuration(true); } int IncidenceBase::duration() const { return mDuration; } void IncidenceBase::setHasDuration(bool b) { mHasDuration = b; } bool IncidenceBase::hasDuration() const { return mHasDuration; } void IncidenceBase::setSyncStatus(int stat) { if (mReadOnly) return; mSyncStatus = stat; } int IncidenceBase::syncStatus() const { return mSyncStatus; } void IncidenceBase::setPilotId( int id ) { if (mReadOnly) return; mPilotId = id; } int IncidenceBase::pilotId() const { return mPilotId; } int IncidenceBase::tempSyncStat() const { return mTempSyncStat; } void IncidenceBase::setTempSyncStat( int id ) { if (mReadOnly) return; mTempSyncStat = id; } void IncidenceBase::removeID(const QString &prof) { if ( prof.isEmpty() ) mExternalId = ":"; else mExternalId = KIdManager::removeId ( mExternalId, prof); } void IncidenceBase::setID( const QString & prof , const QString & id ) { mExternalId = KIdManager::setId ( mExternalId, prof, id ); } QString IncidenceBase::getID( const QString & prof) { return KIdManager::getId ( mExternalId, prof ); } // example :Sharp_DTM;22;23566:TP;-1;8654:TPP;18;0: // format name;III;JJJ: III >= 0, may be -1. JJJ always >= 0 void IncidenceBase::setCsum( const QString & prof , const QString & id ) { mExternalId = KIdManager::setCsum ( mExternalId, prof, id ); } QString IncidenceBase::getCsum( const QString & prof) { return KIdManager::getCsum ( mExternalId, prof ); } void IncidenceBase::setIDStr( const QString & s ) { if (mReadOnly) return; mExternalId = s; } QString IncidenceBase::IDStr() const { return mExternalId ; } void IncidenceBase::registerObserver( IncidenceBase::Observer *observer ) { if( !mObservers.contains(observer) ) mObservers.append( observer ); } void IncidenceBase::unRegisterObserver( IncidenceBase::Observer *observer ) { mObservers.remove( observer ); } void IncidenceBase::updated() { - QPtrListIterator<Observer> it(mObservers); + Q3PtrListIterator<Observer> it(mObservers); while( it.current() ) { Observer *o = it.current(); ++it; o->incidenceUpdated( this ); } } diff --git a/libkcal/incidencebase.h b/libkcal/incidencebase.h index 3edc03b..d97f524 100644 --- a/libkcal/incidencebase.h +++ b/libkcal/incidencebase.h @@ -1,190 +1,192 @@ /* This file is part of libkcal. Copyright (c) 2001 Cornelius Schumacher <schumacher@kde.org> 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #ifndef KCAL_INCIDENCEBASE_H #define KCAL_INCIDENCEBASE_H // // Incidence - base class of calendaring components // #include <qdatetime.h> #include <qstringlist.h> -#include <qvaluelist.h> -#include <qptrlist.h> +#include <q3valuelist.h> +#include <q3ptrlist.h> +//Added by qt3to4: +#include <Q3CString> #include "customproperties.h" #include "attendee.h" namespace KCal { -typedef QValueList<QDate> DateList; +typedef Q3ValueList<QDate> DateList; enum IncTypeID { eventID,todoID,journalID,freebusyID }; /** This class provides the base class common to all calendar components. */ class IncidenceBase : public CustomProperties { public: class Observer { public: virtual void incidenceUpdated( IncidenceBase * ) = 0; }; IncidenceBase(); IncidenceBase(const IncidenceBase &); virtual ~IncidenceBase(); - virtual QCString type() const = 0; + virtual Q3CString type() const = 0; virtual IncTypeID typeID() const = 0; /** Set the unique id for the event */ void setUid(const QString &); /** Return the unique id for the event */ QString uid() const; /** Sets the time the incidence was last modified. */ void setLastModified(const QDateTime &lm); /** Return the time the incidence was last modified. */ QDateTime lastModified() const; QString lastModifiedSortKey() const; /** sets the organizer for the event */ void setOrganizer(const QString &o); QString organizer() const; /** Set readonly status. */ virtual void setReadOnly( bool ); /** Return if the object is read-only. */ bool isReadOnly() const { return mReadOnly; } /** for setting the event's starting date/time with a QDateTime. */ virtual void setDtStart(const QDateTime &dtStart); /** returns an event's starting date/time as a QDateTime. */ virtual QDateTime dtStart() const; /** returns an event's starting time as a string formatted according to the users locale settings */ QString dtStartTimeStr() const; /** returns an event's starting date as a string formatted according to the users locale settings */ QString dtStartDateStr(bool shortfmt=true) const; /** returns an event's starting date and time as a string formatted according to the users locale settings */ QString dtStartStr(bool shortfmt=true) const; virtual void setDuration(int seconds); int duration() const; void setHasDuration(bool); bool hasDuration() const; /** Return true or false depending on whether the incidence "floats," * i.e. has a date but no time attached to it. */ bool doesFloat() const; /** Set whether the incidence floats, i.e. has a date but no time attached to it. */ void setFloats(bool f); /** Add Attendee to this incidence. IncidenceBase takes ownership of the Attendee object. */ bool addAttendee(Attendee *a, bool doupdate=true ); // void removeAttendee(Attendee *a); // void removeAttendee(const char *n); /** Remove all Attendees. */ void clearAttendees(); /** Return list of attendees. */ - QPtrList<Attendee> attendees() const { return mAttendees; }; + Q3PtrList<Attendee> attendees() const { return mAttendees; }; /** Return number of attendees. */ int attendeeCount() const { return mAttendees.count(); }; /** Return the Attendee with this email */ Attendee* attendeeByMail(const QString &); /** Return first Attendee with one of this emails */ Attendee* attendeeByMails(const QStringList &, const QString& email = QString::null); /** pilot syncronization states */ enum { SYNCNONE = 0, SYNCMOD = 1, SYNCDEL = 3 }; /** Set synchronisation satus. */ void setSyncStatus(int stat); /** Return synchronisation status. */ int syncStatus() const; /** Set Pilot Id. */ void setPilotId(int id); /** Return Pilot Id. */ int pilotId() const; void setTempSyncStat(int id); int tempSyncStat() const; void setIDStr( const QString & ); QString IDStr() const; void setID( const QString &, const QString & ); QString getID( const QString & ); void setCsum( const QString &, const QString & ); QString getCsum( const QString & ); void removeID(const QString &); void registerObserver( Observer * ); void unRegisterObserver( Observer * ); void updated(); void setCalID( int id ); void setCalID_block( int id ); int calID() const; void setCalEnabled( bool ); bool calEnabled() const; void setAlarmEnabled( bool ); bool alarmEnabled() const; bool isTagged() const; void setTagged( bool ); virtual void setLastModifiedSubInvalid(); protected: bool blockLastModified; bool mIsTagged; QDateTime mDtStart; bool mReadOnly; QDateTime getEvenTime( QDateTime ); private: // base components QString mOrganizer; QString mLastModifiedKey; QString mUid; int mCalID; bool mCalEnabled; bool mAlarmEnabled; QDateTime mLastModified; - QPtrList<Attendee> mAttendees; + Q3PtrList<Attendee> mAttendees; bool mFloats; int mDuration; bool mHasDuration; QString mExternalId; int mTempSyncStat; // PILOT SYNCHRONIZATION STUFF int mPilotId; // unique id for pilot sync int mSyncStatus; // status (for sync) - QPtrList<Observer> mObservers; + Q3PtrList<Observer> mObservers; }; bool operator==( const IncidenceBase&, const IncidenceBase& ); } #endif diff --git a/libkcal/journal.h b/libkcal/journal.h index 1cd0a22..c83356f 100644 --- a/libkcal/journal.h +++ b/libkcal/journal.h @@ -1,51 +1,53 @@ /* This file is part of libkcal. Copyright (c) 2001 Cornelius Schumacher <schumacher@kde.org> 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #ifndef JOURNAL_H #define JOURNAL_H // // Journal component, representing a VJOURNAL object // #include "incidence.h" +//Added by qt3to4: +#include <Q3CString> namespace KCal { /** This class provides a Journal in the sense of RFC2445. */ class Journal : public Incidence { public: Journal(); ~Journal(); - QCString type() const { return "Journal"; } + Q3CString type() const { return "Journal"; } IncTypeID typeID() const { return journalID; } Incidence *clone(); QDateTime getNextAlarmDateTime( bool * ok, int * offset ,QDateTime start_dt ) const; private: bool accept(Visitor &v) { return v.visit(this); } }; bool operator==( const Journal&, const Journal& ); } #endif diff --git a/libkcal/kincidenceformatter.cpp b/libkcal/kincidenceformatter.cpp index 733b897..bce68b0 100644 --- a/libkcal/kincidenceformatter.cpp +++ b/libkcal/kincidenceformatter.cpp @@ -1,443 +1,445 @@ #include "kincidenceformatter.h" #include <kstaticdeleter.h> #include <kglobal.h> #include <klocale.h> #ifdef DEKTOP_VERSION #include <kabc/stdaddressbook.h> +//Added by qt3to4: +#include <Q3PtrList> #define size count #endif KIncidenceFormatter* KIncidenceFormatter::mInstance = 0; static KStaticDeleter<KIncidenceFormatter> insd; QString KIncidenceFormatter::getFormattedText( Incidence * inc, bool details, bool created , bool modified ) { // #ifndef QT_NO_INPUTDIALOG // return QInputDialog::getItem( caption, label, items, current, editable ); // #else // return QString::null; // #endif mDetails = details; mCreated = created ; mModified = modified; mText = ""; if ( inc->typeID() == eventID ) setEvent((Event *) inc ); else if ( inc->typeID() == todoID ) setTodo((Todo *) inc ); return mText; } KIncidenceFormatter* KIncidenceFormatter::instance() { if (!mInstance) { mInstance = insd.setObject(new KIncidenceFormatter()); } return mInstance; } KIncidenceFormatter::~KIncidenceFormatter() { if (mInstance == this) mInstance = insd.setObject(0); //qDebug("KIncidenceFormatter::~KIncidenceFormatter "); } KIncidenceFormatter::KIncidenceFormatter() { mColorMode = 0; } void KIncidenceFormatter::setEvent(Event *event) { int mode = 0; mCurrentIncidence = event; bool shortDate = true; if ( mode == 0 ) { addTag("h3",deTag(event->summary())); formatReadOnly(event); } else { if ( mColorMode == 1 ) { mText +="<font color=\"#00A000\">"; } if ( mColorMode == 2 ) { mText +="<font color=\"#C00000\">"; } // mText +="<font color=\"#F00000\">" + i18n("O-due!") + "</font>"; if ( mode == 1 ) { addTag("h2",i18n( "Local: " ) +deTag(event->summary())); } else { addTag("h2",i18n( "Remote: " ) +deTag(event->summary())); } formatReadOnly(event); addTag("h3",i18n( "Last modified: " ) + KGlobal::locale()->formatDateTime(event->lastModified(),shortDate, true ) ); if ( mColorMode ) mText += "</font>"; } if (event->cancelled ()) { mText +="<font color=\"#B00000\">"; addTag("i",i18n("This event has been cancelled!")); mText.append("<br>"); mText += "</font>"; } if (event->doesFloat()) { if (event->isMultiDay()) { mText.append(i18n("<p><b>From:</b> %1 </p><p><b>To:</b> %2</p>") .arg(event->dtStartDateStr(shortDate)) .arg(event->dtEndDateStr(shortDate))); mText.append(i18n("<p><b>Duration:</b> %1 days</p>") .arg(event->dtStart().daysTo(event->dtEnd())+1)); } else { mText.append(i18n("<p><b>On:</b> %1</p>").arg(event->dtStartDateStr( shortDate ))); } } else { if (event->isMultiDay()) { mText.append(i18n("<p><b>From:</b> %1</p> ") .arg(event->dtStartStr( shortDate))); mText.append(i18n("<p><b>To:</b> %1</p>") .arg(event->dtEndStr(shortDate))); } else { mText.append(i18n("<p><b>From:</b> %1 <b>To:</b> %2</p>") .arg(event->dtStartTimeStr()) .arg(event->dtEndTimeStr())); mText.append(i18n("<p><b>On:</b> %1</p> ") .arg(event->dtStartDateStr( shortDate ))); } } if (!event->location().isEmpty()) { addTag("b",i18n("Location: ")); mText.append(deTag(event->location())+"<br>"); } if (event->doesRecur()) { QString recurText = event->recurrence()->recurrenceText(); addTag("p","<em>" + i18n("This is a %1 recurring event.").arg(recurText ) + "</em>"); bool ok; QDate start = QDate::currentDate(); QDateTime next; next = event->getNextOccurence( QDateTime::currentDateTime() , &ok ); if ( ok ) { addTag("p",i18n("<b>Next recurrence is on:</b>") ); addTag("p", KGlobal::locale()->formatDate( next.date(), shortDate )); } else { bool last; QDate nextd; nextd = event->recurrence()->getPreviousDate( QDate::currentDate() , &last ); if ( last ) { addTag("p",i18n("<b>Last recurrence was on:</b>") ); addTag("p", KGlobal::locale()->formatDate( nextd, shortDate )); } } } if (event->isAlarmEnabled()) { Alarm *alarm =event->alarms().first() ; QDateTime t = alarm->time(); if (event->doesRecur()) { bool ok = false; int offset = 0; QDateTime next = event->getNextAlarmDateTime(& ok, &offset, QDateTime::currentDateTime() ) ; if ( ok ) { t = next; } } QString s =i18n("( %1 before )").arg( alarm->offsetText() ); addTag("p",i18n("<b>Alarm on: </b>") + s + ": "+KGlobal::locale()->formatDateTime( t, shortDate )); //addTag("p", KGlobal::locale()->formatDateTime( t, shortDate )); //addTag("p",s); } addTag("p",i18n("<b>Access: </b>") +event->secrecyStr() ); // mText.append(event->secrecyStr()+"<br>"); formatCategories(event); formatAttendees(event); if ( mCreated ) { #ifdef DESKTOP_VERSION addTag("p",i18n("<b>Created: ") +" </b>"+KGlobal::locale()->formatDateTime( event->created(), shortDate )); #else addTag("p",i18n("<b>Created: ") +" </b>"); addTag("p", KGlobal::locale()->formatDateTime( event->created(), shortDate )); #endif } if ( mModified ) { #ifdef DESKTOP_VERSION addTag("p",i18n("<b>Last modified: ") +" </b>"+KGlobal::locale()->formatDateTime( event->lastModified(), shortDate )); #else addTag("p",i18n("<b>Last modified: ") +" </b>"); addTag("p", KGlobal::locale()->formatDateTime( event->lastModified(), shortDate )); #endif } if ( mDetails ) { if (!event->description().isEmpty()) { addTag("p",i18n("<b>Details: </b>")); addTag("p",deTag(event->description())); } } } void KIncidenceFormatter::setTodo(Todo *event ) { int mode = 0; mCurrentIncidence = event; bool shortDate = true; if (mode == 0 ) { addTag("h3",deTag(event->summary())); formatReadOnly(event); } else { if ( mColorMode == 1 ) { mText +="<font color=\"#00A000\">"; } if ( mColorMode == 2 ) { mText +="<font color=\"#B00000\">"; } if ( mode == 1 ) { addTag("h2",i18n( "Local: " ) +deTag(event->summary())); } else { addTag("h2",i18n( "Remote: " ) +deTag(event->summary())); } formatReadOnly(event); addTag("h3",i18n( "Last modified: " ) + KGlobal::locale()->formatDateTime(event->lastModified(),shortDate, true ) ); if ( mColorMode ) mText += "</font>"; } if ( event->percentComplete() == 100 && event->hasCompletedDate() ) { mText +="<font color=\"#B00000\">"; addTag("i", i18n("<p><i>Completed on %1</i></p>").arg( event->completedStr(shortDate) ) ); mText += "</font>"; } else { mText.append(i18n("<p><i>%1 % completed</i></p>") .arg(event->percentComplete())); } if (event->cancelled ()) { mText +="<font color=\"#B00000\">"; addTag("i",i18n("This todo has been cancelled!")); mText.append("<br>"); mText += "</font>"; } if (event->doesRecur()) { QString recurText = event->recurrence()->recurrenceText(); addTag("p","<em>" + i18n("This is a %1 recurring todo.").arg(recurText ) + "</em>"); } if (event->hasStartDate()) { mText.append(i18n("<p><b>Start on:</b> %1</p>").arg(event->dtStartStr(shortDate))); } if (event->hasDueDate()) { mText.append(i18n("<p><b>Due on:</b> %1</p>").arg(event->dtDueStr(shortDate))); } if (!event->location().isEmpty()) { addTag("b",i18n("Location: ")); mText.append(deTag(event->location())+"<br>"); } mText.append(i18n("<p><b>Priority:</b> %2</p>") .arg(QString::number(event->priority()))); if (event->isAlarmEnabled()) { Alarm *alarm =event->alarms().first() ; QDateTime t = alarm->time(); if (event->doesRecur()) { bool ok = false; int offset = 0; QDateTime next = event->getNextAlarmDateTime(& ok, &offset, QDateTime::currentDateTime() ) ; if ( ok ) { t = next; } } QString s =i18n("( %1 before )").arg( alarm->offsetText() ); addTag("p",i18n("<b>Alarm on: ") + s +" </b>"); addTag("p", KGlobal::locale()->formatDateTime( t, shortDate )); //addTag("p",s); } addTag("p",i18n("<b>Access: </b>") +event->secrecyStr() ); formatCategories(event); formatAttendees(event); if ( mCreated ) { #ifdef DESKTOP_VERSION addTag("p",i18n("<b>Created: ") +" </b>"+KGlobal::locale()->formatDateTime( event->created(), shortDate )); #else addTag("p",i18n("<b>Created: ") +" </b>"); addTag("p", KGlobal::locale()->formatDateTime( event->created(), shortDate )); #endif } if ( mModified ) { #ifdef DESKTOP_VERSION addTag("p",i18n("<b>Last modified: ") +" </b>"+KGlobal::locale()->formatDateTime( event->lastModified(), shortDate )); #else addTag("p",i18n("<b>Last modified: ") +" </b>"); addTag("p", KGlobal::locale()->formatDateTime( event->lastModified(), shortDate )); #endif } if ( mDetails ) { if (!event->description().isEmpty()) { addTag("p",i18n("<b>Details: </b>")); addTag("p",deTag(event->description())); } } } void KIncidenceFormatter::setJournal(Journal* ) { } void KIncidenceFormatter::formatCategories(Incidence *event) { if (!event->categoriesStr().isEmpty()) { addTag("p",i18n("<b>Categories: </b>")+event->categoriesStrWithSpace() ); //mText.append(event->categoriesStr()); } } void KIncidenceFormatter::addTag(const QString & tag,const QString & text) { - int number=text.contains("\n"); + int number=text.count("\n"); QString str = "<" + tag + ">"; QString tmpText=text; QString tmpStr=str; if(number !=-1) { if (number > 0) { int pos=0; QString tmp; for(int i=0;i<=number;i++) { pos=tmpText.find("\n"); tmp=tmpText.left(pos); tmpText=tmpText.right(tmpText.length()-pos-1); tmpStr+=tmp+"<br>"; } } else tmpStr += tmpText; tmpStr+="</" + tag + ">"; mText.append(tmpStr); } else { str += text + "</" + tag + ">"; mText.append(str); } } void KIncidenceFormatter::formatAttendees(Incidence *event) { - QPtrList<Attendee> attendees = event->attendees(); + Q3PtrList<Attendee> attendees = event->attendees(); if (attendees.count()) { QString iconPath = KGlobal::iconLoader()->iconPath("mailappt",KIcon::Small); QString NOiconPath = KGlobal::iconLoader()->iconPath("nomailappt",KIcon::Small); addTag("h3",i18n("Organizer")); mText.append("<ul><li>"); #if 0 //ndef KORG_NOKABC KABC::AddressBook *add_book = KABC::StdAddressBook::self(); KABC::Addressee::List addressList; addressList = add_book->findByEmail(event->organizer()); KABC::Addressee o = addressList.first(); if (!o.isEmpty() && addressList.size()<2) { mText += "<a href=\"uid:" + o.uid() + "\">"; mText += o.formattedName(); mText += "</a>\n"; } else { mText.append(event->organizer()); } #else mText.append(event->organizer()); #endif - if (iconPath) { + if (!iconPath.isEmpty()) { mText += " <a href=\"mailto:" + event->organizer() + "\">"; mText += "<IMG src=\"" + iconPath + "\">"; mText += "</a>\n"; } mText.append("</li></ul>"); addTag("h3",i18n("Attendees")); Attendee *a; mText.append("<ul>"); for(a=attendees.first();a;a=attendees.next()) { #if 0 //ndef KORG_NOKABC if (a->name().isEmpty()) { addressList = add_book->findByEmail(a->email()); KABC::Addressee o = addressList.first(); if (!o.isEmpty() && addressList.size()<2) { mText += "<a href=\"uid:" + o.uid() + "\">"; mText += o.formattedName(); mText += "</a>\n"; } else { mText += "<li>"; mText.append(a->email()); mText += "\n"; } } else { mText += "<li><a href=\"uid:" + a->uid() + "\">"; if (!a->name().isEmpty()) mText += a->name(); else mText += a->email(); mText += "</a>\n"; } #else //qDebug("nokabc "); mText += "<li><a href=\"uid:" + a->uid() + "\">"; if (!a->name().isEmpty()) mText += a->name(); else mText += a->email(); mText += "</a>\n"; #endif if (!a->email().isEmpty()) { - if (iconPath) { + if (!iconPath.isEmpty()) { mText += "<a href=\"mailto:" + a->name() +" "+ "<" + a->email() + ">" + "\">"; if ( a->RSVP() ) mText += "<IMG src=\"" + iconPath + "\">"; else mText += "<IMG src=\"" + NOiconPath + "\">"; mText += "</a>\n"; } } if (a->status() != Attendee::NeedsAction ) mText +="[" + a->statusStr() + "] "; if (a->role() == Attendee::Chair ) mText +="(" + a->roleStr().left(1) + ".)"; } mText.append("</li></ul>"); } } void KIncidenceFormatter::formatReadOnly(Incidence *event) { if (event->isReadOnly()) { addTag("p","<em>(" + i18n("read-only") + ")</em>"); } } QString KIncidenceFormatter::deTag(QString text) { #if QT_VERSION >= 0x030000 text.replace( '<' , "<" ); text.replace( '>' , ">" ); #else if ( text.find ('<') >= 0 ) { text.replace( QRegExp("<") , "<" ); } if ( text.find ('>') >= 0 ) { text.replace( QRegExp(">") , ">" ); } #endif return text; } diff --git a/libkcal/libkcal.pro b/libkcal/libkcal.pro index 33c63c3..1f43b10 100644 --- a/libkcal/libkcal.pro +++ b/libkcal/libkcal.pro @@ -1,108 +1,112 @@ TEMPLATE = lib CONFIG += qt warn_on -TARGET = microkcal +TARGET = xmicrokcal include( ../variables.pri ) INCLUDEPATH += ../libkdepim ../microkde versit ../microkde/kdecore #../qtcompat INCLUDEPATH += ../libical/src/libical INCLUDEPATH += ../libical/src/libicalss DESTDIR = ../bin DEFINES += DESKTOP_VERSION unix: { LIBS += ../libical/lib/libical.a LIBS += ../libical/lib/libicalss.a OBJECTS_DIR = obj/unix MOC_DIR = moc/unix } win32: { DEFINES += _WIN32_ LIBS += ../libical/lib/ical.lib LIBS += ../libical/lib/icalss.lib OBJECTS_DIR = obj/win MOC_DIR = moc/win } INTERFACES = \ HEADERS = \ alarm.h \ attachment.h \ attendee.h \ calendar.h \ calendarlocal.h \ calfilter.h \ calformat.h \ calstorage.h \ compat.h \ customproperties.h \ dummyscheduler.h \ kincidenceformatter.h \ duration.h \ event.h \ exceptions.h \ filestorage.h \ freebusy.h \ icaldrag.h \ icalformat.h \ icalformatimpl.h \ imipscheduler.h \ incidence.h \ incidencebase.h \ journal.h \ period.h \ person.h \ qtopiaformat.h \ recurrence.h \ scheduler.h \ todo.h \ dndfactory.h \ vcaldrag.h \ vcalformat.h \ versit/port.h \ versit/vcc.h \ versit/vobject.h \ phoneformat.h \ SOURCES = \ alarm.cpp \ attachment.cpp \ attendee.cpp \ calendar.cpp \ calendarlocal.cpp \ calfilter.cpp \ calformat.cpp \ compat.cpp \ customproperties.cpp \ dummyscheduler.cpp \ kincidenceformatter.cpp \ duration.cpp \ event.cpp \ exceptions.cpp \ filestorage.cpp \ freebusy.cpp \ icaldrag.cpp \ icalformat.cpp \ icalformatimpl.cpp \ imipscheduler.cpp \ incidence.cpp \ incidencebase.cpp \ journal.cpp \ period.cpp \ person.cpp \ qtopiaformat.cpp \ recurrence.cpp \ scheduler.cpp \ todo.cpp \ dndfactory.cpp \ vcaldrag.cpp \ vcalformat.cpp \ versit/vcc.c \ versit/vobject.c \ phoneformat.cpp \ +#The following line was inserted by qt3to4 +QT += xml qt3support +#The following line was inserted by qt3to4 +QT += diff --git a/libkcal/libkcalE.pro b/libkcal/libkcalE.pro index 737be53..fe46656 100644 --- a/libkcal/libkcalE.pro +++ b/libkcal/libkcalE.pro @@ -1,93 +1,93 @@ TEMPLATE = lib CONFIG += qt warn_on -TARGET = microkcal +TARGET = xmicrokcal INCLUDEPATH += ../libkdepim ../microkde ../qtcompat versit ../microkde/kdecore $(QPEDIR)/include INCLUDEPATH += ../libical/src/libical INCLUDEPATH += ../libical/src/libicalss OBJECTS_DIR = obj/$(PLATFORM) MOC_DIR = moc/$(PLATFORM) DESTDIR = $(QPEDIR)/lib #LIBS += ../libical/lib/$(PLATFORM)/libical.a #LIBS += ../libical/lib/$(PLATFORM)/libicalss.a LIBS += ../dest$(LIBICAL_PATH)/libical.a LIBS += ../dest$(LIBICAL_PATH)/libicalss.a INTERFACES = \ HEADERS = \ alarm.h \ attachment.h \ attendee.h \ calendar.h \ calendarlocal.h \ calfilter.h \ calformat.h \ calstorage.h \ compat.h \ customproperties.h \ dummyscheduler.h \ duration.h \ event.h \ exceptions.h \ filestorage.h \ freebusy.h \ icaldrag.h \ icalformat.h \ icalformatimpl.h \ imipscheduler.h \ incidence.h \ incidencebase.h \ kincidenceformatter.h \ journal.h \ period.h \ person.h \ qtopiaformat.h \ sharpformat.h \ phoneformat.h \ recurrence.h \ scheduler.h \ todo.h \ vcaldrag.h \ vcalformat.h \ versit/port.h \ versit/vcc.h \ versit/vobject.h \ SOURCES = \ alarm.cpp \ attachment.cpp \ attendee.cpp \ calendar.cpp \ calendarlocal.cpp \ calfilter.cpp \ calformat.cpp \ compat.cpp \ customproperties.cpp \ dummyscheduler.cpp \ duration.cpp \ event.cpp \ exceptions.cpp \ filestorage.cpp \ freebusy.cpp \ icaldrag.cpp \ icalformat.cpp \ icalformatimpl.cpp \ imipscheduler.cpp \ incidence.cpp \ incidencebase.cpp \ kincidenceformatter.cpp \ journal.cpp \ period.cpp \ person.cpp \ qtopiaformat.cpp \ sharpformat.cpp \ phoneformat.cpp \ recurrence.cpp \ scheduler.cpp \ todo.cpp \ vcaldrag.cpp \ vcalformat.cpp \ versit/vcc.c \ versit/vobject.c \ diff --git a/libkcal/listbase.h b/libkcal/listbase.h index 085b13d..6c942ef 100644 --- a/libkcal/listbase.h +++ b/libkcal/listbase.h @@ -1,97 +1,99 @@ /* This file is part of libkcal. Copyright (c) 2003 Cornelius Schumacher <schumacher@kde.org> 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #ifndef KCAL_LISTBASE_H #define KCAL_LISTBASE_H -#include <qvaluelist.h> +#include <q3valuelist.h> +//Added by qt3to4: +#include <Q3PtrList> namespace KCal { class Event; class Todo; /** This class provides a template for lists of pointers. It extends QValueList<T *> by auto delete funtionality known from QPtrList. */ template<class T> -class ListBase : public QValueList<T *> +class ListBase : public Q3ValueList<T *> { public: ListBase() - : QValueList<T *>(), mAutoDelete( false ) + : Q3ValueList<T *>(), mAutoDelete( false ) { } ListBase( const ListBase &l ) - : QValueList<T *>( l ), mAutoDelete( false ) + : Q3ValueList<T *>( l ), mAutoDelete( false ) { } ~ListBase() { if ( mAutoDelete ) { - QValueListIterator<T *> it; - for( it = QValueList<T*>::begin(); it != QValueList<T*>::end(); ++it ) { + Q3ValueListIterator<T *> it; + for( it = Q3ValueList<T*>::begin(); it != Q3ValueList<T*>::end(); ++it ) { delete *it; } } } ListBase &operator=( const ListBase &l ) { if ( this == &l ) return *this; - QValueList<T *>::operator=( l ); + Q3ValueList<T *>::operator=( l ); return *this; } void setAutoDelete( bool autoDelete ) { mAutoDelete = autoDelete; } bool removeRef( T *t ) { - QValueListIterator<T *> it = find( t ); - if ( it == QValueList<T*>::end() ) { + Q3ValueListIterator<T *> it = find( t ); + if ( it == Q3ValueList<T*>::end() ) { return false; } else { if ( mAutoDelete ) delete t; remove( it ); return true; } } - void fill ( QPtrList<T> list ) { - QPtrListIterator<T> it (list); + void fill ( Q3PtrList<T> list ) { + Q3PtrListIterator<T> it (list); T *item; while ( (item = it.current()) != 0 ) { append( item ); ++it; } } private: bool mAutoDelete; }; } #endif diff --git a/libkcal/phoneformat.cpp b/libkcal/phoneformat.cpp index 900fc04..794e4b4 100644 --- a/libkcal/phoneformat.cpp +++ b/libkcal/phoneformat.cpp @@ -1,620 +1,621 @@ /* This file is part of libkcal. Copyright (c) 2004 Lutz Rogowski <rogowski@kde.org> 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #include <qdatetime.h> #include <qstring.h> #include <qapplication.h> -#include <qptrlist.h> +#include <q3ptrlist.h> #include <qregexp.h> #include <qmessagebox.h> #include <qclipboard.h> #include <qfile.h> -#include <qtextstream.h> +#include <q3textstream.h> #include <qtextcodec.h> #include <qdir.h> #include <qlabel.h> +#include <QDesktopWidget> #include <kdebug.h> #include <klocale.h> #include <kglobal.h> #include <kmessagebox.h> #include <phoneaccess.h> #include "calendar.h" #include "alarm.h" #include "recurrence.h" #include "calendarlocal.h" #include "phoneformat.h" #include "syncdefines.h" using namespace KCal; class PhoneParser : public QObject { public: PhoneParser( ) { ; } static QString dtToString( const QDateTime& dti, bool useTZ = false ) { QString datestr; QString timestr; int offset = KGlobal::locale()->localTimeOffset( dti ); QDateTime dt; if (useTZ) dt = dti.addSecs ( -(offset*60)); else dt = dti; if(dt.date().isValid()){ const QDate& date = dt.date(); datestr.sprintf("%04d%02d%02d", date.year(), date.month(), date.day()); } if(dt.time().isValid()){ const QTime& time = dt.time(); timestr.sprintf("T%02d%02d%02d", time.hour(), time.minute(), time.second()); } return datestr + timestr; } }; PhoneFormat::PhoneFormat(QString profileName, QString device,QString connection, QString model ) { mProfileName = profileName; PhoneAccess::writeConfig( device, connection, model ); } PhoneFormat::~PhoneFormat() { } #if 0 int PhoneFormat::initDevice(GSM_StateMachine *s) { GSM_ReadConfig(NULL, &s->Config[0], 0); s->ConfigNum = 1; GSM_Config *cfg = &s->Config[0]; if ( ! mConnection.isEmpty() ) { cfg->Connection = strdup(mConnection.latin1()); cfg->DefaultConnection = false; qDebug("Connection set %s ", cfg->Connection ); } if ( ! mDevice.isEmpty() ) { cfg->Device = strdup(mDevice.latin1()); cfg->DefaultDevice = false; qDebug("Device set %s ", cfg->Device); } if ( ! mModel.isEmpty() ) { strcpy(cfg->Model,mModel.latin1() ); cfg->DefaultModel = false; qDebug("Model set %s ",cfg->Model ); } int error=GSM_InitConnection(s,3); return error; } #endif ulong PhoneFormat::getCsumTodo( Todo* todo ) { QStringList attList; if ( todo->hasDueDate() ) attList << PhoneParser::dtToString ( todo->dtDue() ); attList << todo->summary(); QString completedString = "no"; if ( todo->isCompleted() ) completedString = "yes"; attList << completedString; int prio = todo->priority(); if( prio == 2 ) prio = 1; if (prio == 4 ) prio = 5 ; attList << QString::number( prio ); QString alarmString = "na"; Alarm *alarm; if ( todo->alarms().count() > 0 ) { alarm = todo->alarms().first(); if ( alarm->enabled() ) { alarmString = QString::number(alarm->offset() ); } } attList << alarmString; attList << todo->categoriesStr(); attList << todo->secrecyStr(); return PhoneFormat::getCsum(attList ); } ulong PhoneFormat::getCsumEvent( Event* event ) { QStringList attList; attList << PhoneParser::dtToString ( event->dtStart() ); attList << PhoneParser::dtToString ( event->dtEnd() ); attList << event->summary(); attList << event->location(); QString alarmString = "na"; Alarm *alarm; if ( event->alarms().count() > 0 ) { alarm = event->alarms().first(); if ( alarm->enabled() ) { alarmString = QString::number( alarm->offset() ); } } attList << alarmString; Recurrence* rec = event->recurrence(); QStringList list; bool writeEndDate = false; switch ( rec->doesRecur() ) { case Recurrence::rDaily: // 0 list.append( "0" ); list.append( QString::number( rec->frequency() ));//12 list.append( "0" ); list.append( "0" ); writeEndDate = true; break; case Recurrence::rWeekly:// 1 list.append( "1" ); list.append( QString::number( rec->frequency()) );//12 list.append( "0" ); { int days = 0; QBitArray weekDays = rec->days(); int i; for( i = 1; i <= 7; ++i ) { if ( weekDays[i-1] ) { days += 1 << (i-1); } } list.append( QString::number( days ) ); } //pending weekdays writeEndDate = true; break; case Recurrence::rMonthlyPos:// 2 list.append( "2" ); list.append( QString::number( rec->frequency()) );//12 writeEndDate = true; { int count = 1; - QPtrList<Recurrence::rMonthPos> rmp; + Q3PtrList<Recurrence::rMonthPos> rmp; rmp = rec->monthPositions(); if ( rmp.first()->negative ) count = 5 - rmp.first()->rPos - 1; else count = rmp.first()->rPos - 1; list.append( QString::number( count ) ); } list.append( "0" ); break; case Recurrence::rMonthlyDay:// 3 list.append( "3" ); list.append( QString::number( rec->frequency()) );//12 list.append( "0" ); list.append( "0" ); writeEndDate = true; break; case Recurrence::rYearlyMonth://4 list.append( "4" ); list.append( QString::number( rec->frequency()) );//12 list.append( "0" ); list.append( "0" ); writeEndDate = true; break; default: list.append( "255" ); list.append( QString() ); list.append( "0" ); list.append( QString() ); list.append( "0" ); list.append( "20991231T000000" ); break; } if ( writeEndDate ) { if ( rec->endDate().isValid() ) { // 15 + 16 list.append( "1" ); - list.append( PhoneParser::dtToString( rec->endDate()) ); + list.append( PhoneParser::dtToString( (QDateTime)rec->endDate()) ); } else { list.append( "0" ); list.append( "20991231T000000" ); } } attList << list.join(""); attList << event->categoriesStr(); //qDebug("csum cat %s", event->categoriesStr().latin1()); attList << event->secrecyStr(); return PhoneFormat::getCsum(attList ); } ulong PhoneFormat::getCsum( const QStringList & attList) { int max = attList.count(); ulong cSum = 0; int j,k,i; int add; for ( i = 0; i < max ; ++i ) { QString s = attList[i]; if ( ! s.isEmpty() ){ j = s.length(); for ( k = 0; k < j; ++k ) { int mul = k +1; add = s[k].unicode (); if ( k < 16 ) mul = mul * mul; int ii = i+1; add = add * mul *ii*ii*ii; cSum += add; } } } //QString dump = attList.join(","); //qDebug("csum: %d %s", cSum,dump.latin1()); return cSum; } //extern "C" GSM_Error GSM_InitConnection(GSM_StateMachine *s, int ReplyNum); #include <stdlib.h> #define DEBUGMODE false bool PhoneFormat::load( Calendar *calendar, Calendar *existingCal) { QString fileName; #ifdef DESKTOP_VERSION fileName = locateLocal("tmp", "phonefile.vcs"); #else fileName = "/tmp/phonefile.vcs"; #endif QString command; if ( ! PhoneAccess::readFromPhone( fileName )) { return false; } VCalFormat vfload; vfload.setLocalTime ( true ); qDebug("loading file ..."); if ( ! vfload.load( calendar, fileName ) ) return false; - QPtrList<Event> er = calendar->rawEvents(); + Q3PtrList<Event> er = calendar->rawEvents(); Event* ev = er.first(); qDebug("reading events... "); while ( ev ) { QStringList cat = ev->categories(); if ( cat.contains( "MeetingDEF" )) { ev->setCategories( QStringList() ); } else if ( cat.contains( "Birthday" )) { ev->setFloats( true ); QDate da = ev->dtStart().date(); ev->setDtStart( QDateTime( da) ); ev->setDtEnd( QDateTime( da.addDays(1)) ); } uint cSum; cSum = PhoneFormat::getCsumEvent( ev ); int id = ev->pilotId(); Event *event; event = existingCal->event( mProfileName ,QString::number( id ) ); if ( event ) { event = (Event*)event->clone(); copyEvent( event, ev ); calendar->deleteEvent( ev ); calendar->addEvent( event); } else event = ev; event->setCsum( mProfileName, QString::number( cSum )); event->setTempSyncStat( SYNC_TEMPSTATE_NEW_EXTERNAL ); event->setID( mProfileName,QString::number( id ) ); ev = er.next(); } { qDebug("reading todos... "); - QPtrList<Todo> tr = calendar->rawTodos(); + Q3PtrList<Todo> tr = calendar->rawTodos(); Todo* ev = tr.first(); while ( ev ) { QStringList cat = ev->categories(); if ( cat.contains( "MeetingDEF" )) { ev->setCategories( QStringList() ); } int id = ev->pilotId(); uint cSum; cSum = PhoneFormat::getCsumTodo( ev ); Todo *event; event = existingCal->todo( mProfileName ,QString::number( id ) ); if ( event ) { //qDebug("copy todo %s ", event->summary().latin1()); event = (Todo*)event->clone(); copyTodo( event, ev ); calendar->deleteTodo( ev ); calendar->addTodo( event); } else event = ev; event->setCsum( mProfileName, QString::number( cSum )); event->setTempSyncStat( SYNC_TEMPSTATE_NEW_EXTERNAL ); event->setID( mProfileName,QString::number( id ) ); ev = tr.next(); } } return true; } void PhoneFormat::copyEvent( Event* to, Event* from ) { if ( from->dtStart().isValid() ) to->setDtStart( from->dtStart() ); if ( from->dtEnd().isValid() ) to->setDtEnd( from->dtEnd() ); if ( !from->location().isEmpty() ) to->setLocation( from->location() ); if ( !from->description().isEmpty() ) to->setDescription( from->description() ); if ( !from->summary().isEmpty() ) to->setSummary( from->summary() ); if ( from->alarms().count() ) { to->clearAlarms(); Alarm *a = from->alarms().first(); Alarm *b = to->newAlarm( ); b->setEnabled( a->enabled() ); b->setStartOffset(Duration( a->offset() ) ); } QStringList cat = to->categories(); QStringList catFrom = from->categories(); QString nCat; int iii; for ( iii = 0; iii < catFrom.count();++iii ) { nCat = catFrom[iii]; if ( !nCat.isEmpty() ) if ( !cat.contains( nCat )) { cat << nCat; } } to->setCategories( cat ); if ( from->doesRecur() ) { Recurrence * r = new Recurrence( *from->recurrence(),to); to->setRecurrence( r ) ; } } void PhoneFormat::copyTodo( Todo* to, Todo* from ) { if ( from->hasStartDate() ) { to->setHasStartDate( true ); to->setDtStart( from->dtStart() ); } if ( from->hasDueDate() ){ to->setHasDueDate( true ); to->setDtDue( from->dtDue() ); } if ( !from->location().isEmpty() ) to->setLocation( from->location() ); if ( !from->description().isEmpty() ) to->setDescription( from->description() ); if ( !from->summary().isEmpty() ) to->setSummary( from->summary() ); if ( from->alarms().count() ) { to->clearAlarms(); Alarm *a = from->alarms().first(); Alarm *b = to->newAlarm( ); b->setEnabled( a->enabled() ); b->setStartOffset(Duration( a->offset() ) ); } QStringList cat = to->categories(); QStringList catFrom = from->categories(); QString nCat; int iii; for ( iii = 0; iii < catFrom.count();++iii ) { nCat = catFrom[iii]; if ( !nCat.isEmpty() ) if ( !cat.contains( nCat )) { cat << nCat; } } to->setCategories( cat ); if ( from->isCompleted() ) { to->setCompleted( true ); if( from->completed().isValid() ) to->setCompleted( from->completed() ); } else { // set percentcomplete only, if to->isCompleted() if ( to->isCompleted() ) to->setPercentComplete(from->percentComplete()); } if( to->priority() == 2 && from->priority() == 1 ) ; //skip else if (to->priority() == 4 && from->priority() == 5 ) ; else to->setPriority(from->priority()); } -#include <qcstring.h> +#include <q3cstring.h> void PhoneFormat::afterSave( Incidence* inc,const QString& id ,const QString& csum) { inc->setID( mProfileName, id ); inc->setCsum( mProfileName, csum); inc->setTempSyncStat( SYNC_TEMPSTATE_NEW_ID ); } bool PhoneFormat::writeToPhone( Calendar * calendar) { #ifdef DESKTOP_VERSION QString fileName = locateLocal("tmp", "phonefile.vcs"); #else QString fileName = "/tmp/phonefile.vcs"; #endif VCalFormat vfsave; vfsave.setLocalTime ( true ); QString id = calendar->timeZoneId(); calendar->setLocalTime(); if ( ! vfsave.save( calendar, fileName ) ) return false; calendar->setTimeZoneId( id ); return PhoneAccess::writeToPhone( fileName ); } bool PhoneFormat::save( Calendar *calendar) { // 1 remove events which should be deleted - QPtrList<Event> er = calendar->rawEvents(); + Q3PtrList<Event> er = calendar->rawEvents(); Event* ev = er.first(); while ( ev ) { if ( ev->tempSyncStat() == SYNC_TEMPSTATE_DELETE ) { calendar->deleteEvent( ev ); } else { } ev = er.next(); } // 2 remove todos which should be deleted - QPtrList<Todo> tl = calendar->rawTodos(); + Q3PtrList<Todo> tl = calendar->rawTodos(); Todo* to = tl.first(); while ( to ) { if ( to->tempSyncStat() == SYNC_TEMPSTATE_DELETE ) { calendar->deleteTodo( to ); } else { if ( to->isCompleted()) { calendar->deleteTodo( to ); } } to = tl.next(); } // 3 save file if ( !writeToPhone( calendar ) ) return false; QLabel status ( i18n(" Opening device ..."), 0 ); int w = status.sizeHint().width()+20 ; if ( w < 200 ) w = 230; int h = status.sizeHint().height()+20 ; int dw = QApplication::desktop()->width(); int dh = QApplication::desktop()->height(); status.setCaption(i18n("Writing to phone...") ); status.setGeometry( (dw-w)/2, (dh - h )/2 ,w,h ); QString message; status.show(); status.raise(); qApp->processEvents(); // 5 reread data message = i18n(" Rereading all data ... "); status.setText ( message ); qApp->processEvents(); CalendarLocal* calendarTemp = new CalendarLocal(); calendarTemp->setTimeZoneId( calendar->timeZoneId()); if ( ! load( calendarTemp,calendar) ){ qDebug("error reloading calendar "); delete calendarTemp; return false; } // 6 compare data //algo 6 compare event er = calendar->rawEvents(); ev = er.first(); message = i18n(" Comparing event # "); - QPtrList<Event> er1 = calendarTemp->rawEvents(); + Q3PtrList<Event> er1 = calendarTemp->rawEvents(); Event* ev1; int procCount = 0; while ( ev ) { //qDebug("event new ID %s",ev->summary().latin1()); status.setText ( message + QString::number ( ++procCount ) ); qApp->processEvents(); ev1 = er1.first(); while ( ev1 ) { if ( ev->contains( ev1 ) ) { afterSave( ev ,ev1->getID(mProfileName),ev1->getCsum(mProfileName)); er1.remove( ev1 ); break; } ev1 = er1.next(); } if ( ! ev1 ) { // ev->removeID(mProfileName); qDebug("ERROR: No event found on phone for %s ", ev->summary().latin1()); } ev = er.next(); } //algo 6 compare todo tl = calendar->rawTodos(); to = tl.first(); procCount = 0; - QPtrList<Todo> tl1 = calendarTemp->rawTodos(); + Q3PtrList<Todo> tl1 = calendarTemp->rawTodos(); Todo* to1 ; message = i18n(" Comparing todo # "); while ( to ) { status.setText ( message + QString::number ( ++procCount ) ); qApp->processEvents(); Todo* to1 = tl1.first(); while ( to1 ) { if ( to->contains( to1 ) ) { afterSave( to ,to1->getID(mProfileName),to1->getCsum(mProfileName)); tl1.remove( to1 ); break; } to1 = tl1.next(); } if ( ! to1 ) { //to->removeID(mProfileName); qDebug("ERROR: No todo found on phone for %s ", to->summary().latin1()); } to = tl.next(); } delete calendarTemp; return true; } QString PhoneFormat::toString( Calendar * ) { return QString::null; } bool PhoneFormat::fromString( Calendar *calendar, const QString & text) { return false; } diff --git a/libkcal/qtopiaformat.cpp b/libkcal/qtopiaformat.cpp index 0a4a031..2dfe1a4 100644 --- a/libkcal/qtopiaformat.cpp +++ b/libkcal/qtopiaformat.cpp @@ -1,333 +1,333 @@ /* This file is part of libkcal. Copyright (c) 2003 Cornelius Schumacher <schumacher@kde.org> 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #include <qdatetime.h> #include <qstring.h> -#include <qptrlist.h> +#include <q3ptrlist.h> #include <qregexp.h> #include <qclipboard.h> #include <qfile.h> -#include <qtextstream.h> +#include <q3textstream.h> #include <qxml.h> #include <kdebug.h> #include <klocale.h> #include "calendar.h" #include "calendarlocal.h" #include "qtopiaformat.h" using namespace KCal; class QtopiaParser : public QXmlDefaultHandler { public: QtopiaParser( Calendar *calendar ) : mCalendar( calendar ) { oldCategories = 0; } bool startElement( const QString &, const QString &, const QString & qName, const QXmlAttributes &attributes ) { if ( qName == "event" ) { Event *event = new Event; QString uid = "Qtopia" + attributes.value( "uid" ); // event->setUid( uid ); event->setSummary( attributes.value( "description" ) ); event->setLocation( attributes.value( "location" ) ); event->setDescription( attributes.value( "note" ) ); event->setDtStart( toDateTime( attributes.value( "start" ) ) ); event->setDtEnd( toDateTime( attributes.value( "end" ) ) ); if ( attributes.value( "type" ) == "AllDay" ) { event->setFloats( true ); } else { event->setFloats( false ); } QString rtype = attributes.value( "rtype" ); if ( !rtype.isEmpty() ) { QDate startDate = event->dtStart().date(); QString freqStr = attributes.value( "rfreq" ); int freq = freqStr.toInt(); QString hasEndDateStr = attributes.value( "rhasenddate" ); bool hasEndDate = hasEndDateStr == "1"; QString endDateStr = attributes.value( "enddt" ); QDate endDate = toDateTime( endDateStr ).date(); QString weekDaysStr = attributes.value( "rweekdays" ); int weekDaysNum = weekDaysStr.toInt(); if ( weekDaysNum == 0 ) weekDaysNum = (1 << (event->dtStart().date().dayOfWeek()-1)); QBitArray weekDays( 7 ); weekDays.fill( false ); int i; for( i = 0; i < 7; ++i ) { weekDays.setBit( i , ( 1 << i ) & weekDaysNum ); qDebug("%d %d %d ",i, weekDaysNum, weekDays.at(i) ); } QString posStr = attributes.value( "rposition" ); int pos = posStr.toInt(); Recurrence *r = event->recurrence(); if ( rtype == "Daily" ) { if ( hasEndDate ) r->setDaily( freq, endDate ); else r->setDaily( freq, -1 ); } else if ( rtype == "Weekly" ) { // fix needed here // rweekdays not set in XML file if ( hasEndDate ) r->setWeekly( freq, weekDays, endDate ); else r->setWeekly( freq, weekDays, -1 ); } else if ( rtype == "MonthlyDate" ) { if ( hasEndDate ) r->setMonthly( Recurrence::rMonthlyDay, freq, endDate ); else r->setMonthly( Recurrence::rMonthlyDay, freq, -1 ); r->addMonthlyDay( startDate.day() ); } else if ( rtype == "MonthlyDay" ) { if ( hasEndDate ) r->setMonthly( Recurrence::rMonthlyPos, freq, endDate ); else r->setMonthly( Recurrence::rMonthlyPos, freq, -1 ); QBitArray days( 7 ); days.fill( false ); days.setBit( startDate.dayOfWeek() - 1 ); r->addMonthlyPos( pos, days ); } else if ( rtype == "Yearly" ) { if ( hasEndDate ) r->setYearly( Recurrence::rYearlyMonth, freq, endDate ); else r->setYearly( Recurrence::rYearlyMonth, freq, -1 ); r->addYearlyNum( startDate.month() ); } } QString categoryList = attributes.value( "categories" ); event->setCategories( lookupCategories( categoryList ) ); QString alarmStr = attributes.value( "alarm" ); if ( !alarmStr.isEmpty() ) { Alarm *alarm = new Alarm( event ); alarm->setType( Alarm::Display ); alarm->setEnabled( true ); int alarmOffset = alarmStr.toInt(); alarm->setStartOffset( alarmOffset * -60 ); event->addAlarm( alarm ); } // the following may not be //Event *oldEvent = mCalendar->event( uid ); //if ( oldEvent ) mCalendar->deleteEvent( oldEvent ); mCalendar->addEventNoDup( event ); } else if ( qName == "Task" ) { Todo *todo = new Todo; QString uid = "Qtopia" + attributes.value( "Uid" ); //todo->setUid( uid ); QString description = attributes.value( "Description" ); int pos = description.find( '\n' ); if ( pos > 0 ) { QString summary = description.left( pos ); todo->setSummary( summary ); todo->setDescription( description ); } else { todo->setSummary( description ); } int priority = attributes.value( "Priority" ).toInt(); if ( priority == 0 ) priority = 3; todo->setPriority( priority ); QString categoryList = attributes.value( "Categories" ); todo->setCategories( lookupCategories( categoryList ) ); QString completedStr = attributes.value( "Completed" ); if ( completedStr == "1" ) todo->setCompleted( true ); QString hasDateStr = attributes.value( "HasDate" ); if ( hasDateStr == "1" ) { int year = attributes.value( "DateYear" ).toInt(); int month = attributes.value( "DateMonth" ).toInt(); int day = attributes.value( "DateDay" ).toInt(); todo->setDtDue( QDateTime( QDate( year, month, day ) ) ); todo->setHasDueDate( true ); } // Todo *oldTodo = mCalendar->todo( uid ); //if ( oldTodo ) mCalendar->deleteTodo( oldTodo ); mCalendar->addTodoNoDup( todo ); } else if ( qName == "Category" ) { QString id = attributes.value( "id" ); QString name = attributes.value( "name" ); setCategory( id, name ); } return true; } bool warning ( const QXmlParseException &exception ) { printException( exception ); return true; } bool error ( const QXmlParseException &exception ) { printException( exception ); return false; } bool fatalError ( const QXmlParseException &exception ) { printException( exception ); return false; } QString errorString () { return "QtopiaParser: Error!"; } void setCategoriesList ( QStringList * c ) { oldCategories = c; } protected: void printException( const QXmlParseException &exception ) { kdError() << "XML Parse Error (line " << exception.lineNumber() << ", col " << exception.columnNumber() << "): " << exception.message() << "(public ID: '" << exception.publicId() << "' system ID: '" << exception.systemId() << "')" << endl; } QDateTime toDateTime( const QString &value ) { QDateTime dt; dt.setTime_t( value.toUInt() ); return dt; } QStringList lookupCategories( const QString &categoryList ) { QStringList categoryIds = QStringList::split( ";", categoryList ); QStringList categories; QStringList::ConstIterator it; for( it = categoryIds.begin(); it != categoryIds.end(); ++it ) { QString cate = category( *it ); if ( oldCategories ) { if ( ! oldCategories->contains( cate ) ) oldCategories->append( cate ); } categories.append(cate ); } return categories; } private: Calendar *mCalendar; QStringList * oldCategories; static QString category( const QString &id ) { QMap<QString,QString>::ConstIterator it = mCategoriesMap.find( id ); if ( it == mCategoriesMap.end() ) return id; else return *it; } static void setCategory( const QString &id, const QString &name ) { mCategoriesMap.insert( id, name ); } static QMap<QString,QString> mCategoriesMap; }; QMap<QString,QString> QtopiaParser::mCategoriesMap; QtopiaFormat::QtopiaFormat() { mCategories = 0; } QtopiaFormat::~QtopiaFormat() { } #include <qdom.h> bool QtopiaFormat::load( Calendar *calendar, const QString &fileName ) { clearException(); // qDebug("load QtopiaFormat: %s ",fileName.latin1() ); QtopiaParser handler( calendar ); handler.setCategoriesList( mCategories ); QFile xmlFile( fileName ); QXmlInputSource source( xmlFile ); QXmlSimpleReader reader; reader.setContentHandler( &handler ); return reader.parse( source ); } bool QtopiaFormat::save( Calendar *calendar, const QString &fileName ) { clearException(); QString text = toString( calendar ); if ( text.isNull() ) return false; // TODO: write backup file QFile file( fileName ); - if (!file.open( IO_WriteOnly ) ) { + if (!file.open( QIODevice::WriteOnly ) ) { setException(new ErrorFormat(ErrorFormat::SaveError, i18n("Could not open file '%1'").arg(fileName))); return false; } - QTextStream ts( &file ); + Q3TextStream ts( &file ); ts << text; file.close(); return true; } bool QtopiaFormat::fromString( Calendar *, const QString & ) { return false; } QString QtopiaFormat::toString( Calendar * ) { return QString::null; } diff --git a/libkcal/recurrence.cpp b/libkcal/recurrence.cpp index 6ee5499..9a4e540 100644 --- a/libkcal/recurrence.cpp +++ b/libkcal/recurrence.cpp @@ -1,1352 +1,1355 @@ /* This file is part of libkcal. Copyright (c) 1998 Preston Brown Copyright (c) 2001 Cornelius Schumacher <schumacher@kde.org> Copyright (c) 2002 David Jarvie <software@astrojar.org.uk> 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #include <limits.h> #include <kdebug.h> #include <kglobal.h> #include <klocale.h> #include "incidence.h" #include "recurrence.h" +//Added by qt3to4: +#include <Q3ValueList> +#include <Q3PtrList> using namespace KCal; Recurrence::Feb29Type Recurrence::mFeb29YearlyDefaultType = Recurrence::rMar1; Recurrence::Recurrence(Incidence *parent, int compatVersion) : recurs(rNone), // by default, it's not a recurring event rWeekStart(1), // default is Monday rDays(7), mFloats(parent ? parent->doesFloat() : false), mRecurReadOnly(false), mRecurExDatesCount(0), mFeb29YearlyType(mFeb29YearlyDefaultType), mCompatVersion(compatVersion ? compatVersion : INT_MAX), mCompatRecurs(rNone), mCompatDuration(0), mParent(parent) { rMonthDays.setAutoDelete( true ); rMonthPositions.setAutoDelete( true ); rYearNums.setAutoDelete( true ); } Recurrence::Recurrence(const Recurrence &r, Incidence *parent) : recurs(r.recurs), rWeekStart(r.rWeekStart), - rDays(r.rDays.copy()), + rDays(r.rDays), rFreq(r.rFreq), rDuration(r.rDuration), rEndDateTime(r.rEndDateTime), mRecurStart(r.mRecurStart), mFloats(r.mFloats), mRecurReadOnly(r.mRecurReadOnly), mRecurExDatesCount(r.mRecurExDatesCount), mFeb29YearlyType(r.mFeb29YearlyType), mCompatVersion(r.mCompatVersion), mCompatRecurs(r.mCompatRecurs), mCompatDuration(r.mCompatDuration), mParent(parent) { - for (QPtrListIterator<rMonthPos> mp(r.rMonthPositions); mp.current(); ++mp) { + for (Q3PtrListIterator<rMonthPos> mp(r.rMonthPositions); mp.current(); ++mp) { rMonthPos *tmp = new rMonthPos; tmp->rPos = mp.current()->rPos; tmp->negative = mp.current()->negative; - tmp->rDays = mp.current()->rDays.copy(); + tmp->rDays = mp.current()->rDays; rMonthPositions.append(tmp); } - for (QPtrListIterator<int> md(r.rMonthDays); md.current(); ++md) { + for (Q3PtrListIterator<int> md(r.rMonthDays); md.current(); ++md) { int *tmp = new int; *tmp = *md.current(); rMonthDays.append(tmp); } - for (QPtrListIterator<int> yn(r.rYearNums); yn.current(); ++yn) { + for (Q3PtrListIterator<int> yn(r.rYearNums); yn.current(); ++yn) { int *tmp = new int; *tmp = *yn.current(); rYearNums.append(tmp); } rMonthDays.setAutoDelete( true ); rMonthPositions.setAutoDelete( true ); rYearNums.setAutoDelete( true ); } Recurrence::~Recurrence() { } bool Recurrence::operator==( const Recurrence& r2 ) const { // the following line is obvious if ( recurs == rNone && r2.recurs == rNone ) return true; // we need the above line, because two non recurring events may // differ in the other settings, because one (or both) // may be not initialized properly if ( recurs != r2.recurs || rFreq != r2.rFreq || rDuration != r2.rDuration || !rDuration && rEndDateTime != r2.rEndDateTime || mRecurStart != r2.mRecurStart || mFloats != r2.mFloats || mRecurReadOnly != r2.mRecurReadOnly || mRecurExDatesCount != r2.mRecurExDatesCount ) return false; // no need to compare mCompat* and mParent // OK to compare the pointers switch ( recurs ) { case rWeekly: return rDays == r2.rDays && rWeekStart == r2.rWeekStart; case rMonthlyPos: { - QPtrList<rMonthPos> MonthPositions = rMonthPositions; - QPtrList<rMonthPos> MonthPositions2 = r2.rMonthPositions; + Q3PtrList<rMonthPos> MonthPositions = rMonthPositions; + Q3PtrList<rMonthPos> MonthPositions2 = r2.rMonthPositions; if ( !MonthPositions.count() ) return false; if ( !MonthPositions2.count() ) return false; return MonthPositions.first()->rPos == MonthPositions2.first()->rPos; } case rMonthlyDay: { - QPtrList<int> MonthDays = rMonthDays ; - QPtrList<int> MonthDays2 = r2.rMonthDays ; + Q3PtrList<int> MonthDays = rMonthDays ; + Q3PtrList<int> MonthDays2 = r2.rMonthDays ; if ( !MonthDays.count() ) return false; if ( !MonthDays2.count() ) return false; return *MonthDays.first() == *MonthDays2.first() ; } case rYearlyPos: { - QPtrList<int> YearNums = rYearNums; - QPtrList<int> YearNums2 = r2.rYearNums; + Q3PtrList<int> YearNums = rYearNums; + Q3PtrList<int> YearNums2 = r2.rYearNums; if ( *YearNums.first() != *YearNums2.first() ) return false; - QPtrList<rMonthPos> MonthPositions = rMonthPositions; - QPtrList<rMonthPos> MonthPositions2 = r2.rMonthPositions; + Q3PtrList<rMonthPos> MonthPositions = rMonthPositions; + Q3PtrList<rMonthPos> MonthPositions2 = r2.rMonthPositions; if ( !MonthPositions.count() ) return false; if ( !MonthPositions2.count() ) return false; return MonthPositions.first()->rPos == MonthPositions2.first()->rPos; } case rYearlyMonth: { - QPtrList<int> YearNums = rYearNums; - QPtrList<int> YearNums2 = r2.rYearNums; + Q3PtrList<int> YearNums = rYearNums; + Q3PtrList<int> YearNums2 = r2.rYearNums; return ( *YearNums.first() == *YearNums2.first() && mFeb29YearlyType == r2.mFeb29YearlyType); } case rYearlyDay: { - QPtrList<int> YearNums = rYearNums; - QPtrList<int> YearNums2 = r2.rYearNums; + Q3PtrList<int> YearNums = rYearNums; + Q3PtrList<int> YearNums2 = r2.rYearNums; return ( *YearNums.first() == *YearNums2.first() ); } case rNone: case rMinutely: case rHourly: case rDaily: default: return true; } } /* bool Recurrence::compareLists( const QPtrList<int> &l1 ,const QPtrList<int> &l2) { if ( l1.count() != l2.count() ) return false; int count = l1.count(); int i; for ( i = 0; i < count ; ++i ) { // if ( l1.at(i) != l2.at(i) ) return false; qDebug("compüare "); } return true; } */ QString Recurrence::recurrenceText() const { QString recurText; if ( recurs == Recurrence::rMinutely ) recurText = i18n("minutely"); else if ( recurs == Recurrence::rHourly ) recurText = i18n("hourly"); else if ( recurs == Recurrence::rDaily ) recurText = i18n("daily"); else if ( recurs == Recurrence::rWeekly ) recurText = i18n("weekly"); else if ( recurs == Recurrence::rMonthlyPos ) recurText = i18n("monthly"); else if ( recurs == Recurrence::rMonthlyDay ) recurText = i18n("monthly"); else if ( recurs == Recurrence::rYearlyMonth ) recurText = i18n("yearly"); else if ( recurs == Recurrence::rYearlyDay ) recurText = i18n("day-yearly"); else if ( recurs == Recurrence::rYearlyPos ) recurText = i18n("position-yearly"); if ( !recurText.isEmpty() ) { if ( rFreq > 1 ){ recurText = i18n("(%1) ").arg(rFreq ) + recurText; } } else recurText = i18n("No"); return recurText; } void Recurrence::setCompatVersion(int version) { mCompatVersion = version ? version : INT_MAX; } ushort Recurrence::doesRecur() const { return recurs; } bool Recurrence::recursOnPure(const QDate &qd) const { switch(recurs) { case rMinutely: return recursSecondly(qd, rFreq*60); case rHourly: return recursSecondly(qd, rFreq*3600); case rDaily: return recursDaily(qd); case rWeekly: return recursWeekly(qd); case rMonthlyPos: case rMonthlyDay: return recursMonthly(qd); case rYearlyMonth: return recursYearlyByMonth(qd); case rYearlyDay: return recursYearlyByDay(qd); case rYearlyPos: return recursYearlyByPos(qd); default: return false; case rNone: return false; } // case return false; } bool Recurrence::recursAtPure(const QDateTime &dt) const { switch(recurs) { case rMinutely: return recursMinutelyAt(dt, rFreq); case rHourly: return recursMinutelyAt(dt, rFreq*60); default: if (dt.time() != mRecurStart.time()) return false; switch(recurs) { case rDaily: return recursDaily(dt.date()); case rWeekly: return recursWeekly(dt.date()); case rMonthlyPos: case rMonthlyDay: return recursMonthly(dt.date()); case rYearlyMonth: return recursYearlyByMonth(dt.date()); case rYearlyDay: return recursYearlyByDay(dt.date()); case rYearlyPos: return recursYearlyByPos(dt.date()); default: return false; case rNone: return false; } } // case return false; } QDate Recurrence::endDate() const { int count = 0; QDate end; if (recurs != rNone) { if (rDuration < 0) return QDate(); // infinite recurrence if (rDuration == 0) return rEndDateTime.date(); // The end date is determined by the recurrence count QDate dStart = mRecurStart.date(); switch (recurs) { case rMinutely: return mRecurStart.addSecs((rDuration-1+mRecurExDatesCount)*rFreq*60).date(); case rHourly: return mRecurStart.addSecs((rDuration-1+mRecurExDatesCount)*rFreq*3600).date(); case rDaily: return dStart.addDays((rDuration-1+mRecurExDatesCount)*rFreq); case rWeekly: count = weeklyCalc(END_DATE_AND_COUNT, end); break; case rMonthlyPos: case rMonthlyDay: count = monthlyCalc(END_DATE_AND_COUNT, end); break; case rYearlyMonth: count = yearlyMonthCalc(END_DATE_AND_COUNT, end); break; case rYearlyDay: count = yearlyDayCalc(END_DATE_AND_COUNT, end); break; case rYearlyPos: count = yearlyPosCalc(END_DATE_AND_COUNT, end); break; default: // catch-all. Should never get here. kdDebug(5800) << "Control should never reach here in endDate()!" << endl; break; } } if (!count) return QDate(); // error - there is no recurrence return end; } QDateTime Recurrence::endDateTime() const { int count = 0; QDate end; if (recurs != rNone) { if (rDuration < 0) return QDateTime(); // infinite recurrence if (rDuration == 0) return rEndDateTime; // The end date is determined by the recurrence count QDate dStart = mRecurStart.date(); switch (recurs) { case rMinutely: return mRecurStart.addSecs((rDuration-1+mRecurExDatesCount)*rFreq*60); case rHourly: return mRecurStart.addSecs((rDuration-1+mRecurExDatesCount)*rFreq*3600); case rDaily: - return dStart.addDays((rDuration-1+mRecurExDatesCount)*rFreq); + return (QDateTime)dStart.addDays((rDuration-1+mRecurExDatesCount)*rFreq); case rWeekly: count = weeklyCalc(END_DATE_AND_COUNT, end); break; case rMonthlyPos: case rMonthlyDay: count = monthlyCalc(END_DATE_AND_COUNT, end); break; case rYearlyMonth: count = yearlyMonthCalc(END_DATE_AND_COUNT, end); break; case rYearlyDay: count = yearlyDayCalc(END_DATE_AND_COUNT, end); break; case rYearlyPos: count = yearlyPosCalc(END_DATE_AND_COUNT, end); break; default: // catch-all. Should never get here. kdDebug(5800) << "Control should never reach here in endDate()!" << endl; break; } } if (!count) return QDateTime(); // error - there is no recurrence return QDateTime(end, mRecurStart.time()); } int Recurrence::durationTo(const QDate &date) const { QDate d = date; return recurCalc(COUNT_TO_DATE, d); } int Recurrence::durationTo(const QDateTime &datetime) const { QDateTime dt = datetime; return recurCalc(COUNT_TO_DATE, dt); } void Recurrence::unsetRecurs() { if (mRecurReadOnly) return; recurs = rNone; rMonthPositions.clear(); rMonthDays.clear(); rYearNums.clear(); } void Recurrence::setRecurStart(const QDateTime &start) { mRecurStart = start; mFloats = false; switch (recurs) { case rMinutely: case rHourly: break; case rDaily: case rWeekly: case rMonthlyPos: case rMonthlyDay: case rYearlyMonth: case rYearlyDay: case rYearlyPos: default: rEndDateTime.setTime(start.time()); break; } } void Recurrence::setRecurStart(const QDate &start) { mRecurStart.setDate(start); mRecurStart.setTime(QTime(0,0,0)); switch (recurs) { case rMinutely: case rHourly: break; case rDaily: case rWeekly: case rMonthlyPos: case rMonthlyDay: case rYearlyMonth: case rYearlyDay: case rYearlyPos: default: mFloats = true; break; } } void Recurrence::setFloats(bool f) { switch (recurs) { case rDaily: case rWeekly: case rMonthlyPos: case rMonthlyDay: case rYearlyMonth: case rYearlyDay: case rYearlyPos: break; case rMinutely: case rHourly: default: return; // can't set sub-daily to floating } mFloats = f; if (f) { mRecurStart.setTime(QTime(0,0,0)); rEndDateTime.setTime(QTime(0,0,0)); } } int Recurrence::frequency() const { return rFreq; } int Recurrence::duration() const { return rDuration; } void Recurrence::setDuration(int _rDuration) { if (mRecurReadOnly) return; if (_rDuration > 0) { rDuration = _rDuration; // Compatibility mode is only needed when reading the calendar in ICalFormatImpl, // so explicitly setting the duration means no backwards compatibility is needed. mCompatDuration = 0; } } QString Recurrence::endDateStr(bool shortfmt) const { return KGlobal::locale()->formatDate(rEndDateTime.date(),shortfmt); } const QBitArray &Recurrence::days() const { return rDays; } -const QPtrList<Recurrence::rMonthPos> &Recurrence::monthPositions() const +const Q3PtrList<Recurrence::rMonthPos> &Recurrence::monthPositions() const { return rMonthPositions; } -const QPtrList<Recurrence::rMonthPos> &Recurrence::yearMonthPositions() const +const Q3PtrList<Recurrence::rMonthPos> &Recurrence::yearMonthPositions() const { return rMonthPositions; } -const QPtrList<int> &Recurrence::monthDays() const +const Q3PtrList<int> &Recurrence::monthDays() const { return rMonthDays; } void Recurrence::setMinutely(int _rFreq, int _rDuration) { if (mRecurReadOnly || _rDuration == 0 || _rDuration < -1) return; setDailySub(rMinutely, _rFreq, _rDuration); } void Recurrence::setMinutely(int _rFreq, const QDateTime &_rEndDateTime) { if (mRecurReadOnly) return; rEndDateTime = _rEndDateTime; setDailySub(rMinutely, _rFreq, 0); } void Recurrence::setHourly(int _rFreq, int _rDuration) { if (mRecurReadOnly || _rDuration == 0 || _rDuration < -1) return; setDailySub(rHourly, _rFreq, _rDuration); } void Recurrence::setHourly(int _rFreq, const QDateTime &_rEndDateTime) { if (mRecurReadOnly) return; rEndDateTime = _rEndDateTime; setDailySub(rHourly, _rFreq, 0); } void Recurrence::setDaily(int _rFreq, int _rDuration) { if (mRecurReadOnly || _rDuration == 0 || _rDuration < -1) return; setDailySub(rDaily, _rFreq, _rDuration); } void Recurrence::setDaily(int _rFreq, const QDate &_rEndDate) { if (mRecurReadOnly) return; rEndDateTime.setDate(_rEndDate); rEndDateTime.setTime(mRecurStart.time()); setDailySub(rDaily, _rFreq, 0); } void Recurrence::setWeekly(int _rFreq, const QBitArray &_rDays, int _rDuration, int _rWeekStart) { if (mRecurReadOnly || _rDuration == 0 || _rDuration < -1) return; recurs = rWeekly; rFreq = _rFreq; rDays = _rDays; rWeekStart = _rWeekStart; rDuration = _rDuration; if (mCompatVersion < 310 && _rDuration > 0) { // Backwards compatibility for KDE < 3.1. // rDuration was set to the number of time periods to recur, // with week start always on a Monday. // Convert this to the number of occurrences. mCompatDuration = _rDuration; int weeks = ((mCompatDuration-1+mRecurExDatesCount)*7) + (7 - mRecurStart.date().dayOfWeek()); QDate end(mRecurStart.date().addDays(weeks * rFreq)); rDuration = INT_MAX; // ensure that weeklyCalc() does its job correctly rDuration = weeklyCalc(COUNT_TO_DATE, end); } else { mCompatDuration = 0; } rMonthPositions.clear(); rMonthDays.clear(); if (mParent) mParent->updated(); } void Recurrence::setWeekly(int _rFreq, const QBitArray &_rDays, const QDate &_rEndDate, int _rWeekStart) { if (mRecurReadOnly) return; recurs = rWeekly; rFreq = _rFreq; rDays = _rDays; rWeekStart = _rWeekStart; rEndDateTime.setDate(_rEndDate); rEndDateTime.setTime(mRecurStart.time()); rDuration = 0; // set to 0 because there is an end date mCompatDuration = 0; rMonthPositions.clear(); rMonthDays.clear(); rYearNums.clear(); if (mParent) mParent->updated(); } void Recurrence::setMonthly(short type, int _rFreq, int _rDuration) { if (mRecurReadOnly || _rDuration == 0 || _rDuration < -1) return; recurs = type; rFreq = _rFreq; rDuration = _rDuration; if (mCompatVersion < 310) mCompatDuration = (_rDuration > 0) ? _rDuration : 0; rYearNums.clear(); if (mParent) mParent->updated(); } void Recurrence::setMonthly(short type, int _rFreq, const QDate &_rEndDate) { if (mRecurReadOnly) return; recurs = type; rFreq = _rFreq; rEndDateTime.setDate(_rEndDate); rEndDateTime.setTime(mRecurStart.time()); rDuration = 0; // set to 0 because there is an end date mCompatDuration = 0; rYearNums.clear(); if (mParent) mParent->updated(); } void Recurrence::addMonthlyPos(short _rPos, const QBitArray &_rDays) { if (recurs == rMonthlyPos) addMonthlyPos_(_rPos, _rDays); } void Recurrence::addMonthlyPos_(short _rPos, const QBitArray &_rDays) { if (mRecurReadOnly || _rPos == 0 || _rPos > 5 || _rPos < -5) // invalid week number return; for (rMonthPos* it = rMonthPositions.first(); it; it = rMonthPositions.next()) { int itPos = it->negative ? -it->rPos : it->rPos; if (_rPos == itPos) { // This week is already in the list. // Combine the specified days with those in the list. it->rDays |= _rDays; if (mParent) mParent->updated(); return; } } // Add the new position to the list rMonthPos *tmpPos = new rMonthPos; if (_rPos > 0) { tmpPos->rPos = _rPos; tmpPos->negative = false; } else { tmpPos->rPos = -_rPos; // take abs() tmpPos->negative = true; } tmpPos->rDays = _rDays; tmpPos->rDays.detach(); rMonthPositions.append(tmpPos); if (mCompatVersion < 310 && mCompatDuration > 0) { // Backwards compatibility for KDE < 3.1. // rDuration was set to the number of time periods to recur. // Convert this to the number of occurrences. int monthsAhead = (mCompatDuration-1+mRecurExDatesCount) * rFreq; int month = mRecurStart.date().month() - 1 + monthsAhead; QDate end(mRecurStart.date().year() + month/12, month%12 + 1, 31); rDuration = INT_MAX; // ensure that recurCalc() does its job correctly rDuration = recurCalc(COUNT_TO_DATE, end); } if (mParent) mParent->updated(); } void Recurrence::addMonthlyDay(short _rDay) { if (mRecurReadOnly || (recurs != rMonthlyDay && recurs != rYearlyMonth) || _rDay == 0 || _rDay > 31 || _rDay < -31) // invalid day number return; for (int* it = rMonthDays.first(); it; it = rMonthDays.next()) { if (_rDay == *it) return; // this day is already in the list - avoid duplication } int *tmpDay = new int; *tmpDay = _rDay; rMonthDays.append(tmpDay); if (mCompatVersion < 310 && mCompatDuration > 0) { // Backwards compatibility for KDE < 3.1. // rDuration was set to the number of time periods to recur. // Convert this to the number of occurrences. int monthsAhead = (mCompatDuration-1+mRecurExDatesCount) * rFreq; int month = mRecurStart.date().month() - 1 + monthsAhead; QDate end(mRecurStart.date().year() + month/12, month%12 + 1, 31); rDuration = INT_MAX; // ensure that recurCalc() does its job correctly rDuration = recurCalc(COUNT_TO_DATE, end); } if (mParent) mParent->updated(); } void Recurrence::setYearly(int type, int _rFreq, int _rDuration) { if (mRecurReadOnly || _rDuration == 0 || _rDuration < -1) return; if (mCompatVersion < 310) mCompatDuration = (_rDuration > 0) ? _rDuration : 0; setYearly_(type, mFeb29YearlyDefaultType, _rFreq, _rDuration); } void Recurrence::setYearly(int type, int _rFreq, const QDate &_rEndDate) { if (mRecurReadOnly) return; rEndDateTime.setDate(_rEndDate); rEndDateTime.setTime(mRecurStart.time()); mCompatDuration = 0; setYearly_(type, mFeb29YearlyDefaultType, _rFreq, 0); } void Recurrence::setYearlyByDate(Feb29Type type, int _rFreq, int _rDuration) { if (mRecurReadOnly || _rDuration == 0 || _rDuration < -1) return; if (mCompatVersion < 310) mCompatDuration = (_rDuration > 0) ? _rDuration : 0; setYearly_(rYearlyMonth, type, _rFreq, _rDuration); } void Recurrence::setYearlyByDate(Feb29Type type, int _rFreq, const QDate &_rEndDate) { if (mRecurReadOnly) return; rEndDateTime.setDate(_rEndDate); rEndDateTime.setTime(mRecurStart.time()); mCompatDuration = 0; setYearly_(rYearlyMonth, type, _rFreq, 0); } void Recurrence::addYearlyMonthPos(short _rPos, const QBitArray &_rDays) { if (recurs == rYearlyPos) addMonthlyPos_(_rPos, _rDays); } -const QPtrList<int> &Recurrence::yearNums() const +const Q3PtrList<int> &Recurrence::yearNums() const { return rYearNums; } void Recurrence::addYearlyMonth(short _rPos ) { if (mRecurReadOnly || recurs != rYearlyMonth) // invalid day/month number return; rMonthPos *tmpPos = new rMonthPos; if ( _rPos > 0) { tmpPos->rPos = _rPos; tmpPos->negative = false; } else { tmpPos->rPos = -_rPos; // take abs() tmpPos->negative = true; } rMonthPositions.append(tmpPos); } void Recurrence::addYearlyNum(short _rNum) { if (mRecurReadOnly || (recurs != rYearlyMonth && recurs != rYearlyDay && recurs != rYearlyPos) || _rNum <= 0) // invalid day/month number return; if (mCompatVersion < 310 && mCompatRecurs == rYearlyDay) { // Backwards compatibility for KDE < 3.1. // Dates were stored as day numbers, with a fiddle to take account of leap years. // Convert the day number to a month. if (_rNum <= 0 || _rNum > 366 || (_rNum == 366 && mRecurStart.date().daysInYear() < 366)) return; // invalid day number _rNum = QDate(mRecurStart.date().year(), 1, 1).addDays(_rNum - 1).month(); } else if ((recurs == rYearlyMonth || recurs == rYearlyPos) && _rNum > 12 || recurs == rYearlyDay && _rNum > 366) return; // invalid day number uint i = 0; for (int* it = rYearNums.first(); it && _rNum >= *it; it = rYearNums.next()) { if (_rNum == *it) return; // this day/month is already in the list - avoid duplication ++i; } int *tmpNum = new int; *tmpNum = _rNum; rYearNums.insert(i, tmpNum); // insert the day/month in a sorted position if (mCompatVersion < 310 && mCompatDuration > 0) { // Backwards compatibility for KDE < 3.1. // rDuration was set to the number of time periods to recur. // Convert this to the number of occurrences. QDate end(mRecurStart.date().year() + (mCompatDuration-1+mRecurExDatesCount)*rFreq, 12, 31); rDuration = INT_MAX; // ensure that recurCalc() does its job correctly rDuration = recurCalc(COUNT_TO_DATE, end); } if (mParent) mParent->updated(); } QDateTime Recurrence::getNextDateTime(const QDateTime &preDateTime, bool *last) const { if (last) *last = false; int freq; switch (recurs) { case rMinutely: freq = rFreq * 60; break; case rHourly: freq = rFreq * 3600; break; case rDaily: case rWeekly: case rMonthlyPos: case rMonthlyDay: case rYearlyMonth: case rYearlyDay: case rYearlyPos: { QDate preDate = preDateTime.date(); if (!mFloats && mRecurStart.time() > preDateTime.time()) preDate = preDate.addDays(-1); return QDateTime(getNextDateNoTime(preDate, last), mRecurStart.time()); } default: return QDateTime(); } // It's a sub-daily recurrence if (preDateTime < mRecurStart) return mRecurStart; int count = mRecurStart.secsTo(preDateTime) / freq + 2; if (rDuration > 0) { if (count > rDuration) return QDateTime(); if (last && count == rDuration) *last = true; } QDateTime endtime = mRecurStart.addSecs((count - 1)*freq); if (rDuration == 0) { if (endtime > rEndDateTime) return QDateTime(); if (last && endtime == rEndDateTime) *last = true; } return endtime; } QDate Recurrence::getNextDate(const QDate &preDate, bool *last) const { if (last) *last = false; switch (recurs) { case rMinutely: case rHourly: return getNextDateTime(QDateTime(preDate, QTime(23,59,59)), last).date(); case rDaily: case rWeekly: case rMonthlyPos: case rMonthlyDay: case rYearlyMonth: case rYearlyDay: case rYearlyPos: qDebug("Recurrence::getNextDate: MAY BE BROKEN "); return getNextDateNoTime(preDate, last); default: return QDate(); } } QDateTime Recurrence::getPreviousDateTime(const QDateTime &afterDateTime, bool *last) const { if (last) *last = false; int freq; switch (recurs) { case rMinutely: freq = rFreq * 60; break; case rHourly: freq = rFreq * 3600; break; case rDaily: case rWeekly: case rMonthlyPos: case rMonthlyDay: case rYearlyMonth: case rYearlyDay: case rYearlyPos: { QDate afterDate = afterDateTime.date(); if (!mFloats && mRecurStart.time() < afterDateTime.time()) afterDate = afterDate.addDays(1); return QDateTime(getPreviousDateNoTime(afterDate, last), mRecurStart.time()); } default: return QDateTime(); } // It's a sub-daily recurrence if (afterDateTime <= mRecurStart) return QDateTime(); int count = (mRecurStart.secsTo(afterDateTime) - 1) / freq + 1; if (rDuration > 0) { if (count > rDuration) count = rDuration; if (last && count == rDuration) *last = true; } QDateTime endtime = mRecurStart.addSecs((count - 1)*freq); if (rDuration == 0) { if (endtime > rEndDateTime) endtime = rEndDateTime; if (last && endtime == rEndDateTime) *last = true; } return endtime; } QDate Recurrence::getPreviousDate(const QDate &afterDate, bool *last) const { if (last) *last = false; switch (recurs) { case rMinutely: case rHourly: return getPreviousDateTime(QDateTime(afterDate, QTime(0,0,0)), last).date(); case rDaily: case rWeekly: case rMonthlyPos: case rMonthlyDay: case rYearlyMonth: case rYearlyDay: case rYearlyPos: return getPreviousDateNoTime(afterDate, last); default: return QDate(); } } /***************************** PROTECTED FUNCTIONS ***************************/ bool Recurrence::recursSecondly(const QDate &qd, int secondFreq) const { if ((qd >= mRecurStart.date()) && ((rDuration > 0) && (qd <= endDate()) || ((rDuration == 0) && (qd <= rEndDateTime.date())) || (rDuration == -1))) { // The date queried falls within the range of the event. if (secondFreq < 24*3600) return true; // the event recurs at least once each day int after = mRecurStart.secsTo(QDateTime(qd)) - 1; if (after / secondFreq != (after + 24*3600) / secondFreq) return true; } return false; } bool Recurrence::recursMinutelyAt(const QDateTime &dt, int minuteFreq) const { if ((dt >= mRecurStart) && ((rDuration > 0) && (dt <= endDateTime()) || ((rDuration == 0) && (dt <= rEndDateTime)) || (rDuration == -1))) { // The time queried falls within the range of the event. if (((mRecurStart.secsTo(dt) / 60) % minuteFreq) == 0) return true; } return false; } bool Recurrence::recursDaily(const QDate &qd) const { QDate dStart = mRecurStart.date(); if ((dStart.daysTo(qd) % rFreq) == 0) { // The date is a day which recurs if (qd >= dStart && ((rDuration > 0 && qd <= endDate()) || (rDuration == 0 && qd <= rEndDateTime.date()) || rDuration == -1)) { // The date queried falls within the range of the event. return true; } } return false; } bool Recurrence::recursWeekly(const QDate &qd) const { QDate dStart = mRecurStart.date(); if ((dStart.daysTo(qd)/7) % rFreq == 0) { // The date is in a week which recurs if (qd >= dStart && ((rDuration > 0 && qd <= endDate()) || (rDuration == 0 && qd <= rEndDateTime.date()) || rDuration == -1)) { // The date queried falls within the range of the event. // check if the bits set match today. int i = qd.dayOfWeek()-1; if (rDays.testBit((uint) i)) return true; } } return false; } bool Recurrence::recursMonthly(const QDate &qd) const { QDate dStart = mRecurStart.date(); int year = qd.year(); int month = qd.month(); int day = qd.day(); // calculate how many months ahead this date is from the original // event's date int monthsAhead = (year - dStart.year()) * 12 + (month - dStart.month()); if ((monthsAhead % rFreq) == 0) { // The date is in a month which recurs if (qd >= dStart && ((rDuration > 0 && qd <= endDate()) || (rDuration == 0 && qd <= rEndDateTime.date()) || rDuration == -1)) { // The date queried falls within the range of the event. - QValueList<int> days; + Q3ValueList<int> days; int daysInMonth = qd.daysInMonth(); if (recurs == rMonthlyDay) getMonthlyDayDays(days, daysInMonth); else if (recurs == rMonthlyPos) getMonthlyPosDays(days, daysInMonth, QDate(year, month, 1).dayOfWeek()); - for (QValueList<int>::Iterator it = days.begin(); it != days.end(); ++it) { + for (Q3ValueList<int>::Iterator it = days.begin(); it != days.end(); ++it) { if (*it == day) return true; } // no dates matched } } return false; } bool Recurrence::recursYearlyByMonth(const QDate &qd) const { QDate dStart = mRecurStart.date(); int startDay = dStart.day(); int qday = qd.day(); int qmonth = qd.month(); int qyear = qd.year(); bool match = (qday == startDay); if (!match && startDay == 29 && dStart.month() == 2) { // It's a recurrence on February 29th switch (mFeb29YearlyType) { case rFeb28: if (qday == 28 && qmonth == 2 && !QDate::leapYear(qyear)) match = true; break; case rMar1: if (qday == 1 && qmonth == 3 && !QDate::leapYear(qyear)) { qmonth = 2; match = true; } break; case rFeb29: break; } } if (match) { // The day of the month matches. Calculate how many years ahead // this date is from the original event's date. int yearsAhead = (qyear - dStart.year()); if (yearsAhead % rFreq == 0) { // The date is in a year which recurs if (qd >= dStart && ((rDuration > 0 && qd <= endDate()) || (rDuration == 0 && qd <= rEndDateTime.date()) || rDuration == -1)) { // The date queried falls within the range of the event. int i = qmonth; - for (QPtrListIterator<int> qlin(rYearNums); qlin.current(); ++qlin) { + for (Q3PtrListIterator<int> qlin(rYearNums); qlin.current(); ++qlin) { if (i == *qlin.current()) return true; } } } } return false; } bool Recurrence::recursYearlyByPos(const QDate &qd) const { QDate dStart = mRecurStart.date(); int year = qd.year(); int month = qd.month(); int day = qd.day(); // calculate how many years ahead this date is from the original // event's date int yearsAhead = (year - dStart.year()); if (yearsAhead % rFreq == 0) { // The date is in a year which recurs if (qd >= dStart && ((rDuration > 0 && qd <= endDate()) || (rDuration == 0 && qd <= rEndDateTime.date()) || rDuration == -1)) { // The date queried falls within the range of the event. - for (QPtrListIterator<int> qlin(rYearNums); qlin.current(); ++qlin) { + for (Q3PtrListIterator<int> qlin(rYearNums); qlin.current(); ++qlin) { if (month == *qlin.current()) { // The month recurs - QValueList<int> days; + Q3ValueList<int> days; getMonthlyPosDays(days, qd.daysInMonth(), QDate(year, month, 1).dayOfWeek()); - for (QValueList<int>::Iterator it = days.begin(); it != days.end(); ++it) { + for (Q3ValueList<int>::Iterator it = days.begin(); it != days.end(); ++it) { if (*it == day) return true; } } } } } return false; } bool Recurrence::recursYearlyByDay(const QDate &qd) const { QDate dStart = mRecurStart.date(); // calculate how many years ahead this date is from the original // event's date int yearsAhead = (qd.year() - dStart.year()); if (yearsAhead % rFreq == 0) { // The date is in a year which recurs if (qd >= dStart && ((rDuration > 0 && qd <= endDate()) || (rDuration == 0 && qd <= rEndDateTime.date()) || rDuration == -1)) { // The date queried falls within the range of the event. int i = qd.dayOfYear(); - for (QPtrListIterator<int> qlin(rYearNums); qlin.current(); ++qlin) { + for (Q3PtrListIterator<int> qlin(rYearNums); qlin.current(); ++qlin) { if (i == *qlin.current()) return true; } } } return false; } /* Get the date of the next recurrence, after the specified date. * If 'last' is non-null, '*last' is set to true if the next recurrence is the * last recurrence, else false. * Reply = date of next recurrence, or invalid date if none. */ QDate Recurrence::getNextDateNoTime(const QDate &preDate, bool *last) const { if (last) *last = false; QDate dStart = mRecurStart.date(); if (preDate < dStart) return dStart; QDate earliestDate = preDate.addDays(1); QDate nextDate; switch (recurs) { case rDaily: nextDate = dStart.addDays((dStart.daysTo(preDate)/rFreq + 1) * rFreq); break; case rWeekly: { QDate start = dStart.addDays(-((dStart.dayOfWeek() - rWeekStart + 7)%7)); // start of week for dStart int earliestDayOfWeek = earliestDate.dayOfWeek(); int weeksAhead = start.daysTo(earliestDate) / 7; int notThisWeek = weeksAhead % rFreq; // zero if this week is a recurring week weeksAhead -= notThisWeek; // latest week which recurred int weekday = 0; // First check for any remaining day this week, if this week is a recurring week if (!notThisWeek) weekday = getFirstDayInWeek(earliestDayOfWeek); // Check for a day in the next scheduled week if (!weekday ) weekday = getFirstDayInWeek(rWeekStart) + rFreq*7; nextDate = start.addDays(weeksAhead*7 + weekday - 1); break; } case rMonthlyDay: case rMonthlyPos: { int startYear = dStart.year(); int startMonth = dStart.month(); // 1..12 int earliestYear = earliestDate.year(); int monthsAhead = (earliestYear - startYear)*12 + earliestDate.month() - startMonth; int notThisMonth = monthsAhead % rFreq; // zero if this month is a recurring month monthsAhead -= notThisMonth; // latest month which recurred // Check for the first later day in the current month if (!notThisMonth) nextDate = getFirstDateInMonth(earliestDate); if (!nextDate.isValid() ) { // Check for a day in the next scheduled month int months = startMonth - 1 + monthsAhead + rFreq; nextDate = getFirstDateInMonth(QDate(startYear + months/12, months%12 + 1, 1)); } break; } case rYearlyMonth: case rYearlyPos: case rYearlyDay: { int startYear = dStart.year(); int yearsAhead = earliestDate.year() - startYear; int notThisYear = yearsAhead % rFreq; // zero if this year is a recurring year yearsAhead -= notThisYear; // latest year which recurred // Check for the first later date in the current year if (!notThisYear) nextDate = getFirstDateInYear(earliestDate); // Check for a date in the next scheduled year if (!nextDate.isValid() && earliestDate.dayOfYear() > 1) nextDate = getFirstDateInYear(QDate(startYear + yearsAhead + rFreq, 1, 1)); break; } case rNone: default: return QDate(); } if (rDuration >= 0 && nextDate.isValid()) { // Check that the date found is within the range of the recurrence QDate end = endDate(); if (nextDate > end) return QDate(); if (last && nextDate == end) *last = true; } return nextDate; } /* Get the date of the last previous recurrence, before the specified date. * Reply = date of previous recurrence, or invalid date if none. */ QDate Recurrence::getPreviousDateNoTime(const QDate &afterDate, bool *last) const { if (last) *last = false; QDate dStart = mRecurStart.date(); QDate latestDate = afterDate.addDays(-1); if (latestDate < dStart) return QDate(); QDate prevDate; switch (recurs) { case rDaily: prevDate = dStart.addDays((dStart.daysTo(latestDate) / rFreq) * rFreq); break; case rWeekly: { QDate start = dStart.addDays(-((dStart.dayOfWeek() - rWeekStart + 7)%7)); // start of week for dStart int latestDayOfWeek = latestDate.dayOfWeek(); int weeksAhead = start.daysTo(latestDate) / 7; int notThisWeek = weeksAhead % rFreq; // zero if this week is a recurring week weeksAhead -= notThisWeek; // latest week which recurred int weekday = 0; // First check for any previous day this week, if this week is a recurring week if (!notThisWeek) weekday = getLastDayInWeek(latestDayOfWeek); // Check for a day in the previous scheduled week if (!weekday) { if (!notThisWeek) weeksAhead -= rFreq; int weekEnd = (rWeekStart + 5)%7 + 1; weekday = getLastDayInWeek(weekEnd); } if (weekday) prevDate = start.addDays(weeksAhead*7 + weekday - 1); break; } case rMonthlyDay: case rMonthlyPos: { int startYear = dStart.year(); int startMonth = dStart.month(); // 1..12 int latestYear = latestDate.year(); int monthsAhead = (latestYear - startYear)*12 + latestDate.month() - startMonth; int notThisMonth = monthsAhead % rFreq; // zero if this month is a recurring month monthsAhead -= notThisMonth; // latest month which recurred // Check for the last earlier day in the current month if (!notThisMonth) prevDate = getLastDateInMonth(latestDate); if (!prevDate.isValid() && latestDate.day() < latestDate.daysInMonth()) { // Check for a day in the previous scheduled month if (!notThisMonth) monthsAhead -= rFreq; int months = startMonth + monthsAhead; // get the month after the one that recurs prevDate = getLastDateInMonth(QDate(startYear + months/12, months%12 + 1, 1).addDays(-1)); } break; } case rYearlyMonth: case rYearlyPos: case rYearlyDay: { int startYear = dStart.year(); int yearsAhead = latestDate.year() - startYear; int notThisYear = yearsAhead % rFreq; // zero if this year is a recurring year yearsAhead -= notThisYear; // latest year which recurred // Check for the first later date in the current year if (!notThisYear) prevDate = getLastDateInYear(latestDate); if (!prevDate.isValid() && latestDate.dayOfYear() < latestDate.daysInYear()) { // Check for a date in the next scheduled year if (!notThisYear) yearsAhead -= rFreq; prevDate = getLastDateInYear(QDate(startYear + yearsAhead, 12, 31)); } break; } case rNone: default: return QDate(); } if (prevDate.isValid()) { // Check that the date found is within the range of the recurrence if (prevDate < dStart) return QDate(); if (rDuration >= 0) { QDate end = endDate(); if (prevDate >= end) { if (last) *last = true; return end; } } } return prevDate; } @@ -1360,2042 +1363,2042 @@ void Recurrence::setDailySub(short type, int freq, int duration) rYearNums.clear(); if (type != rDaily) mFloats = false; // sub-daily types can't be floating if (mParent) mParent->updated(); } void Recurrence::setYearly_(short type, Feb29Type feb29type, int freq, int duration) { recurs = type; if (mCompatVersion < 310 && type == rYearlyDay) { mCompatRecurs = rYearlyDay; recurs = rYearlyMonth; // convert old yearly-by-day to yearly-by-month feb29type = rMar1; // retain the same day number in the year } mFeb29YearlyType = feb29type; rFreq = freq; rDuration = duration; if (type != rYearlyPos) rMonthPositions.clear(); rMonthDays.clear(); if (mParent) mParent->updated(); } int Recurrence::recurCalc(PeriodFunc func, QDateTime &endtime) const { QDate enddate = endtime.date(); switch (func) { case END_DATE_AND_COUNT: if (rDuration < 0) { endtime = QDateTime(); return 0; // infinite recurrence } if (rDuration == 0) { endtime = rEndDateTime; func = COUNT_TO_DATE; } break; case COUNT_TO_DATE: // Count recurrences up to and including the specified date/time. if (endtime < mRecurStart) return 0; if (rDuration == 0 && endtime > rEndDateTime) enddate = rEndDateTime.date(); else if (!mFloats && mRecurStart.time() > endtime.time()) enddate = enddate.addDays(-1); break; case NEXT_AFTER_DATE: // Find next recurrence AFTER endtime if (endtime < mRecurStart) { endtime = mRecurStart; return 1; } if (rDuration == 0 && endtime >= rEndDateTime) { endtime = QDateTime(); return 0; } if (!mFloats && mRecurStart.time() > endtime.time()) enddate = enddate.addDays(-1); break; default: endtime = QDateTime(); return 0; } int count = 0; // default = error bool timed = false; switch (recurs) { case rMinutely: timed = true; count = secondlyCalc(func, endtime, rFreq*60); break; case rHourly: timed = true; count = secondlyCalc(func, endtime, rFreq*3600); break; case rDaily: count = dailyCalc(func, enddate); break; case rWeekly: count = weeklyCalc(func, enddate); break; case rMonthlyPos: case rMonthlyDay: count = monthlyCalc(func, enddate); break; case rYearlyMonth: count = yearlyMonthCalc(func, enddate); break; case rYearlyPos: count = yearlyPosCalc(func, enddate); break; case rYearlyDay: count = yearlyDayCalc(func, enddate); break; default: break; } switch (func) { case END_DATE_AND_COUNT: case NEXT_AFTER_DATE: if (count == 0) endtime = QDateTime(); else if (!timed) { endtime.setDate(enddate); endtime.setTime(mRecurStart.time()); } break; case COUNT_TO_DATE: break; } return count; } int Recurrence::recurCalc(PeriodFunc func, QDate &enddate) const { QDateTime endtime(enddate, QTime(23,59,59)); switch (func) { case END_DATE_AND_COUNT: if (rDuration < 0) { enddate = QDate(); return 0; // infinite recurrence } if (rDuration == 0) { enddate = rEndDateTime.date(); func = COUNT_TO_DATE; } break; case COUNT_TO_DATE: // Count recurrences up to and including the specified date. if (enddate < mRecurStart.date()) return 0; if (rDuration == 0 && enddate > rEndDateTime.date()) { enddate = rEndDateTime.date(); endtime.setDate(enddate); } break; case NEXT_AFTER_DATE: if (enddate < mRecurStart.date()) { enddate = mRecurStart.date(); return 1; } if (rDuration == 0 && enddate >= rEndDateTime.date()) { enddate = QDate(); return 0; } break; default: enddate = QDate(); return 0; } int count = 0; // default = error bool timed = false; switch (recurs) { case rMinutely: timed = true; count = secondlyCalc(func, endtime, rFreq*60); break; case rHourly: timed = true; count = secondlyCalc(func, endtime, rFreq*3600); break; case rDaily: count = dailyCalc(func, enddate); break; case rWeekly: count = weeklyCalc(func, enddate); break; case rMonthlyPos: case rMonthlyDay: count = monthlyCalc(func, enddate); break; case rYearlyMonth: count = yearlyMonthCalc(func, enddate); break; case rYearlyPos: count = yearlyPosCalc(func, enddate); break; case rYearlyDay: count = yearlyDayCalc(func, enddate); break; default: break; } switch (func) { case END_DATE_AND_COUNT: case NEXT_AFTER_DATE: if (count == 0) - endtime = QDate(); + endtime = QDateTime(); else if (timed) enddate = endtime.date(); break; case COUNT_TO_DATE: break; } return count; } /* Find count and, depending on 'func', the end date/time of a secondly recurrence. * Reply = total number of occurrences up to 'endtime', or 0 if error. * If 'func' = END_DATE_AND_COUNT or NEXT_AFTER_DATE, 'endtime' is updated to the * recurrence end date/time. */ int Recurrence::secondlyCalc(PeriodFunc func, QDateTime &endtime, int freq) const { switch (func) { case END_DATE_AND_COUNT: endtime = mRecurStart.addSecs((rDuration + mRecurExDatesCount - 1) * freq); return rDuration + mRecurExDatesCount; case COUNT_TO_DATE: { int n = mRecurStart.secsTo(endtime)/freq + 1; if (rDuration > 0 && n > rDuration + mRecurExDatesCount) return rDuration + mRecurExDatesCount; return n; } case NEXT_AFTER_DATE: { int count = mRecurStart.secsTo(endtime) / freq + 2; if (rDuration > 0 && count > rDuration) return 0; endtime = mRecurStart.addSecs((count - 1)*freq); return count; } } return 0; } /* Find count and, depending on 'func', the end date of a daily recurrence. * Reply = total number of occurrences up to 'enddate', or 0 if error. * If 'func' = END_DATE_AND_COUNT or NEXT_AFTER_DATE, 'enddate' is updated to the * recurrence end date. */ int Recurrence::dailyCalc(PeriodFunc func, QDate &enddate) const { QDate dStart = mRecurStart.date(); switch (func) { case END_DATE_AND_COUNT: enddate = dStart.addDays((rDuration + mRecurExDatesCount - 1) * rFreq); return rDuration + mRecurExDatesCount; case COUNT_TO_DATE: { int n = dStart.daysTo(enddate)/rFreq + 1; if (rDuration > 0 && n > rDuration + mRecurExDatesCount) return rDuration + mRecurExDatesCount; return n; } case NEXT_AFTER_DATE: { int count = dStart.daysTo(enddate) / rFreq + 2; if (rDuration > 0 && count > rDuration) return 0; enddate = dStart.addDays((count - 1)*rFreq); return count; } } return 0; } /* Find count and, depending on 'func', the end date of a weekly recurrence. * Reply = total number of occurrences up to 'enddate', or 0 if error. * If 'func' = END_DATE_AND_COUNT or NEXT_AFTER_DATE, 'enddate' is updated to the * recurrence end date. */ int Recurrence::weeklyCalc(PeriodFunc func, QDate &enddate) const { int daysPerWeek = 0; for (int i = 0; i < 7; ++i) { if (rDays.testBit((uint)i)) ++daysPerWeek; } if (!daysPerWeek) return 0; // there are no days to recur on switch (func) { case END_DATE_AND_COUNT: return weeklyCalcEndDate(enddate, daysPerWeek); case COUNT_TO_DATE: return weeklyCalcToDate(enddate, daysPerWeek); case NEXT_AFTER_DATE: return weeklyCalcNextAfter(enddate, daysPerWeek); } return 0; } int Recurrence::weeklyCalcEndDate(QDate &enddate, int daysPerWeek) const { int startDayOfWeek = mRecurStart.date().dayOfWeek(); // 1..7 int countGone = 0; int daysGone = 0; uint countTogo = rDuration + mRecurExDatesCount; if (startDayOfWeek != rWeekStart) { // Check what remains of the start week for (int i = startDayOfWeek - 1; i != rWeekStart - 1; i = (i + 1) % 7) { ++daysGone; if (rDays.testBit((uint)i)) { ++countGone; if (--countTogo == 0) break; } } daysGone += 7 * (rFreq - 1); } if (countTogo) { // Skip the remaining whole weeks // Leave at least 1 recurrence remaining, in order to get its date int wholeWeeks = (countTogo - 1) / daysPerWeek; daysGone += wholeWeeks * 7 * rFreq; countGone += wholeWeeks * daysPerWeek; countTogo -= wholeWeeks * daysPerWeek; // Check the last week in the recurrence for (int i = rWeekStart - 1; ; i = (i + 1) % 7) { ++daysGone; if (rDays.testBit((uint)i)) { ++countGone; if (--countTogo == 0) break; } } } enddate = mRecurStart.date().addDays(daysGone); return countGone; } int Recurrence::weeklyCalcToDate(const QDate &enddate, int daysPerWeek) const { QDate dStart = mRecurStart.date(); int startDayOfWeek = dStart.dayOfWeek(); // 1..7 int countGone = 0; int daysGone = 0; int totalDays = dStart.daysTo(enddate) + 1; int countMax = (rDuration > 0) ? rDuration + mRecurExDatesCount : INT_MAX; if (startDayOfWeek != rWeekStart) { // Check what remains of the start week for (int i = startDayOfWeek - 1; i != rWeekStart - 1; i = (i + 1) % 7) { if (rDays.testBit((uint)i)) { if (++countGone >= countMax) return countMax; } if (++daysGone == totalDays) return countGone; } daysGone += 7 * (rFreq - 1); if (daysGone >= totalDays) return countGone; } // Skip the remaining whole weeks int wholeWeeks = (totalDays - daysGone) / 7; countGone += (wholeWeeks / rFreq) * daysPerWeek; if (countGone >= countMax) return countMax; daysGone += wholeWeeks * 7; if (daysGone >= totalDays // have we reached the end date? || wholeWeeks % rFreq) // is end week a recurrence week? return countGone; // Check the last week in the recurrence for (int i = rWeekStart - 1; ; i = (i + 1) % 7) { if (rDays.testBit((uint)i)) { if (++countGone >= countMax) return countMax; } if (++daysGone == totalDays) return countGone; } return countGone; } int Recurrence::weeklyCalcNextAfter(QDate &enddate, int daysPerWeek) const { QDate dStart = mRecurStart.date(); int startDayOfWeek = dStart.dayOfWeek(); // 1..7 int totalDays = dStart.daysTo(enddate) + 1; uint countTogo = (rDuration > 0) ? rDuration + mRecurExDatesCount : UINT_MAX; int countGone = 0; int daysGone = 0; int recurWeeks; if (startDayOfWeek != rWeekStart) { // Check what remains of the start week for (int i = startDayOfWeek - 1; i != rWeekStart - 1; i = (i + 1) % 7) { ++daysGone; if (rDays.testBit((uint)i)) { ++countGone; if (daysGone > totalDays) goto ex; if (--countTogo == 0) return 0; } } daysGone += 7 * (rFreq - 1); } // Skip the remaining whole weeks recurWeeks = (totalDays - daysGone) / (7 * rFreq); if (recurWeeks) { int n = recurWeeks * daysPerWeek; if (static_cast<uint>(n) > countTogo) return 0; // reached end of recurrence countGone += n; countTogo -= n; daysGone += recurWeeks * 7 * rFreq; } // Check the last week or two in the recurrence for ( ; ; ) { for (int i = rWeekStart - 1; ; i = (i + 1) % 7) { ++daysGone; if (rDays.testBit((uint)i)) { ++countGone; if (daysGone > totalDays) goto ex; if (--countTogo == 0) return 0; } } daysGone += 7 * (rFreq - 1); } ex: enddate = dStart.addDays(daysGone); return countGone; } /* Find count and, depending on 'func', the end date of a monthly recurrence. * Reply = total number of occurrences up to 'enddate', or 0 if error. * If 'func' = END_DATE_AND_COUNT or NEXT_AFTER_DATE, 'enddate' is updated to the * recurrence end date. */ struct Recurrence::MonthlyData { const Recurrence *recurrence; int year; // current year int month; // current month 0..11 int day; // current day of month 1..31 bool varies; // true if recurring days vary between different months private: - QValueList<int> days28, days29, days30, days31; // recurring days in months of each length - QValueList<int> *recurDays[4]; + Q3ValueList<int> days28, days29, days30, days31; // recurring days in months of each length + Q3ValueList<int> *recurDays[4]; public: MonthlyData(const Recurrence* r, const QDate &date) : recurrence(r), year(date.year()), month(date.month()-1), day(date.day()) { recurDays[0] = &days28; recurDays[1] = &days29; recurDays[2] = &days30; recurDays[3] = &days31; varies = (recurrence->recurs == rMonthlyPos) ? true : recurrence->getMonthlyDayDays(days31, 31); } - const QValueList<int>* dayList() const { + const Q3ValueList<int>* dayList() const { if (!varies) return &days31; QDate startOfMonth(year, month + 1, 1); int daysInMonth = startOfMonth.daysInMonth(); - QValueList<int>* days = recurDays[daysInMonth - 28]; + Q3ValueList<int>* days = recurDays[daysInMonth - 28]; if (recurrence->recurs == rMonthlyPos) recurrence->getMonthlyPosDays(*days, daysInMonth, startOfMonth.dayOfWeek()); else if (days->isEmpty()) recurrence->getMonthlyDayDays(*days, daysInMonth); return days; } int yearMonth() const { return year*12 + month; } void addMonths(int diff) { month += diff; year += month / 12; month %= 12; } QDate date() const { return QDate(year, month + 1, day); } }; int Recurrence::monthlyCalc(PeriodFunc func, QDate &enddate) const { if (recurs == rMonthlyPos && rMonthPositions.isEmpty() || recurs == rMonthlyDay && rMonthDays.isEmpty()) return 0; MonthlyData data(this, mRecurStart.date()); switch (func) { case END_DATE_AND_COUNT: return monthlyCalcEndDate(enddate, data); case COUNT_TO_DATE: return monthlyCalcToDate(enddate, data); case NEXT_AFTER_DATE: return monthlyCalcNextAfter(enddate, data); } return 0; } int Recurrence::monthlyCalcEndDate(QDate &enddate, MonthlyData &data) const { uint countTogo = rDuration + mRecurExDatesCount; int countGone = 0; - QValueList<int>::ConstIterator it; - const QValueList<int>* days = data.dayList(); + Q3ValueList<int>::ConstIterator it; + const Q3ValueList<int>* days = data.dayList(); if (data.day > 1) { // Check what remains of the start month for (it = days->begin(); it != days->end(); ++it) { if (*it >= data.day) { ++countGone; if (--countTogo == 0) { data.day = *it; break; } } } if (countTogo) { data.day = 1; data.addMonths(rFreq); } } if (countTogo) { if (data.varies) { // The number of recurrence days varies from month to month, // so we need to check month by month. for ( ; ; ) { days = data.dayList(); uint n = days->count(); // number of recurrence days in this month if (n >= countTogo) break; countTogo -= n; countGone += n; data.addMonths(rFreq); } } else { // The number of recurrences is the same every month, // so skip the month-by-month check. // Skip the remaining whole months, but leave at least // 1 recurrence remaining, in order to get its date. int daysPerMonth = days->count(); int wholeMonths = (countTogo - 1) / daysPerMonth; data.addMonths(wholeMonths * rFreq); countGone += wholeMonths * daysPerMonth; countTogo -= wholeMonths * daysPerMonth; } if (countTogo) { // Check the last month in the recurrence for (it = days->begin(); it != days->end(); ++it) { ++countGone; if (--countTogo == 0) { data.day = *it; break; } } } } enddate = data.date(); return countGone; } int Recurrence::monthlyCalcToDate(const QDate &enddate, MonthlyData &data) const { int countGone = 0; int countMax = (rDuration > 0) ? rDuration + mRecurExDatesCount : INT_MAX; int endYear = enddate.year(); int endMonth = enddate.month() - 1; // zero-based int endDay = enddate.day(); int endYearMonth = endYear*12 + endMonth; - QValueList<int>::ConstIterator it; - const QValueList<int>* days = data.dayList(); + Q3ValueList<int>::ConstIterator it; + const Q3ValueList<int>* days = data.dayList(); if (data.day > 1) { // Check what remains of the start month for (it = days->begin(); it != days->end(); ++it) { if (*it >= data.day) { if (data.yearMonth() == endYearMonth && *it > endDay) return countGone; if (++countGone >= countMax) return countMax; } } data.day = 1; data.addMonths(rFreq); } if (data.varies) { // The number of recurrence days varies from month to month, // so we need to check month by month. while (data.yearMonth() < endYearMonth) { countGone += data.dayList()->count(); if (countGone >= countMax) return countMax; data.addMonths(rFreq); } days = data.dayList(); } else { // The number of recurrences is the same every month, // so skip the month-by-month check. // Skip the remaining whole months. int daysPerMonth = days->count(); int wholeMonths = endYearMonth - data.yearMonth(); countGone += (wholeMonths / rFreq) * daysPerMonth; if (countGone >= countMax) return countMax; if (wholeMonths % rFreq) return countGone; // end year isn't a recurrence year data.year = endYear; data.month = endMonth; } // Check the last month in the recurrence for (it = days->begin(); it != days->end(); ++it) { if (*it > endDay) return countGone; if (++countGone >= countMax) return countMax; } return countGone; } int Recurrence::monthlyCalcNextAfter(QDate &enddate, MonthlyData &data) const { uint countTogo = (rDuration > 0) ? rDuration + mRecurExDatesCount : UINT_MAX; int countGone = 0; int endYear = enddate.year(); int endDay = enddate.day(); int endYearMonth = endYear*12 + enddate.month() - 1; - QValueList<int>::ConstIterator it; - const QValueList<int>* days = data.dayList(); + Q3ValueList<int>::ConstIterator it; + const Q3ValueList<int>* days = data.dayList(); if (data.day > 1) { // Check what remains of the start month for (it = days->begin(); it != days->end(); ++it) { if (*it >= data.day) { ++countGone; if (data.yearMonth() == endYearMonth && *it > endDay) { data.day = *it; goto ex; } if (--countTogo == 0) return 0; } } data.day = 1; data.addMonths(rFreq); } if (data.varies) { // The number of recurrence days varies from month to month, // so we need to check month by month. while (data.yearMonth() <= endYearMonth) { days = data.dayList(); uint n = days->count(); // number of recurrence days in this month if (data.yearMonth() == endYearMonth && days->last() > endDay) break; if (n >= countTogo) return 0; countGone += n; countTogo -= n; data.addMonths(rFreq); } days = data.dayList(); } else { // The number of recurrences is the same every month, // so skip the month-by-month check. // Skip the remaining whole months to at least end year/month. int daysPerMonth = days->count(); int elapsed = endYearMonth - data.yearMonth(); int recurMonths = (elapsed + rFreq - 1) / rFreq; if (elapsed % rFreq == 0 && days->last() <= endDay) ++recurMonths; // required month is after endYearMonth if (recurMonths) { int n = recurMonths * daysPerMonth; if (static_cast<uint>(n) > countTogo) return 0; // reached end of recurrence countTogo -= n; countGone += n; data.addMonths(recurMonths * rFreq); } } // Check the last month in the recurrence for (it = days->begin(); it != days->end(); ++it) { ++countGone; if (data.yearMonth() > endYearMonth || *it > endDay) { data.day = *it; break; } if (--countTogo == 0) return 0; } ex: enddate = data.date(); return countGone; } /* Find count and, depending on 'func', the end date of an annual recurrence by date. * Reply = total number of occurrences up to 'enddate', or 0 if error. * If 'func' = END_DATE_AND_COUNT or NEXT_AFTER_DATE, 'enddate' is updated to the * recurrence end date. */ struct Recurrence::YearlyMonthData { const Recurrence *recurrence; int year; // current year int month; // current month 1..12 int day; // current day of month 1..31 bool leapyear; // true if February 29th recurs and current year is a leap year bool feb29; // true if February 29th recurs private: - QValueList<int> months; // recurring months in non-leap years 1..12 - QValueList<int> leapMonths; // recurring months in leap years 1..12 + Q3ValueList<int> months; // recurring months in non-leap years 1..12 + Q3ValueList<int> leapMonths; // recurring months in leap years 1..12 public: YearlyMonthData(const Recurrence* r, const QDate &date) : recurrence(r), year(date.year()), month(date.month()), day(date.day()) { feb29 = recurrence->getYearlyMonthMonths(day, months, leapMonths); leapyear = feb29 && QDate::leapYear(year); } - const QValueList<int>* monthList() const + const Q3ValueList<int>* monthList() const { return leapyear ? &leapMonths : &months; } - const QValueList<int>* leapMonthList() const { return &leapMonths; } + const Q3ValueList<int>* leapMonthList() const { return &leapMonths; } QDate date() const { return QDate(year, month, day); } }; int Recurrence::yearlyMonthCalc(PeriodFunc func, QDate &enddate) const { if (rYearNums.isEmpty()) return 0; YearlyMonthData data(this, mRecurStart.date()); switch (func) { case END_DATE_AND_COUNT: return yearlyMonthCalcEndDate(enddate, data); case COUNT_TO_DATE: return yearlyMonthCalcToDate(enddate, data); case NEXT_AFTER_DATE: return yearlyMonthCalcNextAfter(enddate, data); } return 0; } // Find total count and end date of an annual recurrence by date. // Reply = total number of occurrences. int Recurrence::yearlyMonthCalcEndDate(QDate &enddate, YearlyMonthData &data) const { uint countTogo = rDuration + mRecurExDatesCount; int countGone = 0; - QValueList<int>::ConstIterator it; - const QValueList<int>* mons = data.monthList(); // get recurring months for this year + Q3ValueList<int>::ConstIterator it; + const Q3ValueList<int>* mons = data.monthList(); // get recurring months for this year if (data.month > 1) { // Check what remains of the start year for (it = mons->begin(); it != mons->end(); ++it) { if (*it >= data.month) { ++countGone; if (--countTogo == 0) { data.month = *it; if (data.month == 2 && data.feb29 && !data.leapyear) { // The recurrence should end on February 29th, but it's a non-leap year switch (mFeb29YearlyType) { case rFeb28: data.day = 28; break; case rMar1: data.month = 3; data.day = 1; break; case rFeb29: break; } } break; } } } if (countTogo) { data.month = 1; data.year += rFreq; } } if (countTogo) { if (data.feb29 && mFeb29YearlyType == rFeb29) { // The number of recurrences is different on leap years, // so check year-by-year. for ( ; ; ) { mons = data.monthList(); uint n = mons->count(); if (n >= countTogo) break; countTogo -= n; countGone += n; data.year += rFreq; } } else { // The number of recurrences is the same every year, // so skip the year-by-year check. // Skip the remaining whole years, but leave at least // 1 recurrence remaining, in order to get its date. int monthsPerYear = mons->count(); int wholeYears = (countTogo - 1) / monthsPerYear; data.year += wholeYears * rFreq; countGone += wholeYears * monthsPerYear; countTogo -= wholeYears * monthsPerYear; } if (countTogo) { // Check the last year in the recurrence for (it = mons->begin(); it != mons->end(); ++it) { ++countGone; if (--countTogo == 0) { data.month = *it; if (data.month == 2 && data.feb29 && !QDate::leapYear(data.year)) { // The recurrence should end on February 29th, but it's a non-leap year switch (mFeb29YearlyType) { case rFeb28: data.day = 28; break; case rMar1: data.month = 3; data.day = 1; break; case rFeb29: break; } } break; } } } } enddate = data.date(); return countGone; } // Find count of an annual recurrence by date. // Reply = total number of occurrences up to 'enddate'. int Recurrence::yearlyMonthCalcToDate(const QDate &enddate, YearlyMonthData &data) const { int countGone = 0; int countMax = (rDuration > 0) ? rDuration + mRecurExDatesCount : INT_MAX; int endYear = enddate.year(); int endMonth = enddate.month(); int endDay = enddate.day(); if (endDay < data.day) { /* The end day of the month is earlier than the recurrence day of the month. * If Feb 29th recurs and: * 1) it recurs on Feb 28th in non-leap years, don't adjust the end month * if enddate is Feb 28th on a non-leap year. * 2) it recurs on Mar 1st in non-leap years, allow the end month to be * adjusted to February, to simplify calculations. */ if (data.feb29 && !QDate::leapYear(endYear) && mFeb29YearlyType == rFeb28 && endDay == 28 && endMonth == 2) { } else if (--endMonth == 0) { endMonth = 12; --endYear; } } - QValueList<int>::ConstIterator it; - const QValueList<int>* mons = data.monthList(); + Q3ValueList<int>::ConstIterator it; + const Q3ValueList<int>* mons = data.monthList(); if (data.month > 1) { // Check what remains of the start year for (it = mons->begin(); it != mons->end(); ++it) { if (*it >= data.month) { if (data.year == endYear && *it > endMonth) return countGone; if (++countGone >= countMax) return countMax; } } data.month = 1; data.year += rFreq; } if (data.feb29 && mFeb29YearlyType == rFeb29) { // The number of recurrences is different on leap years, // so check year-by-year. while (data.year < endYear) { countGone += data.monthList()->count(); if (countGone >= countMax) return countMax; data.year += rFreq; } mons = data.monthList(); } else { // The number of recurrences is the same every year, // so skip the year-by-year check. // Skip the remaining whole years. int monthsPerYear = mons->count(); int wholeYears = endYear - data.year; countGone += (wholeYears / rFreq) * monthsPerYear; if (countGone >= countMax) return countMax; if (wholeYears % rFreq) return countGone; // end year isn't a recurrence year data.year = endYear; } // Check the last year in the recurrence for (it = mons->begin(); it != mons->end(); ++it) { if (*it > endMonth) return countGone; if (++countGone >= countMax) return countMax; } return countGone; } // Find count and date of first recurrence after 'enddate' of an annual recurrence by date. // Reply = total number of occurrences up to 'enddate'. int Recurrence::yearlyMonthCalcNextAfter(QDate &enddate, YearlyMonthData &data) const { uint countTogo = (rDuration > 0) ? rDuration + mRecurExDatesCount : UINT_MAX; int countGone = 0; int endYear = enddate.year(); int endMonth = enddate.month(); int endDay = enddate.day(); bool mar1TooEarly = false; bool feb28ok = false; if (endDay < data.day) { if (data.feb29 && mFeb29YearlyType == rMar1 && endMonth == 3) mar1TooEarly = true; if (data.feb29 && mFeb29YearlyType == rFeb28 && endMonth == 2 && endDay == 28) feb28ok = true; else if (--endMonth == 0) { endMonth = 12; --endYear; } } - QValueList<int>::ConstIterator it; - const QValueList<int>* mons = data.monthList(); + Q3ValueList<int>::ConstIterator it; + const Q3ValueList<int>* mons = data.monthList(); if (data.month > 1) { // Check what remains of the start year for (it = mons->begin(); it != mons->end(); ++it) { if (*it >= data.month) { ++countGone; if (data.year == endYear && ( *it > endMonth && (*it > 3 || !mar1TooEarly) || *it == 2 && feb28ok && data.leapyear)) { if (*it == 2 && data.feb29 && !data.leapyear) { // The next recurrence should be on February 29th, but it's a non-leap year switch (mFeb29YearlyType) { case rFeb28: data.month = 2; data.day = 28; break; case rMar1: data.month = 3; data.day = 1; break; case rFeb29: // impossible in this context! break; } } else data.month = *it; goto ex; } if (--countTogo == 0) return 0; } } data.month = 1; data.year += rFreq; } if (data.feb29 && mFeb29YearlyType == rFeb29) { // The number of recurrences is different on leap years, // so check year-by-year. while (data.year <= endYear) { mons = data.monthList(); if (data.year == endYear && mons->last() > endMonth) break; uint n = mons->count(); if (n >= countTogo) break; countTogo -= n; countGone += n; data.year += rFreq; } mons = data.monthList(); } else { // The number of recurrences is the same every year, // so skip the year-by-year check. // Skip the remaining whole years to at least endYear. int monthsPerYear = mons->count(); int recurYears = (endYear - data.year + rFreq - 1) / rFreq; if ((endYear - data.year)%rFreq == 0 && mons->last() <= endMonth) ++recurYears; // required year is after endYear if (recurYears) { int n = recurYears * monthsPerYear; if (static_cast<uint>(n) > countTogo) return 0; // reached end of recurrence countTogo -= n; countGone += n; data.year += recurYears * rFreq; } } // Check the last year in the recurrence for (it = mons->begin(); it != mons->end(); ++it) { ++countGone; if (data.year > endYear || ( *it > endMonth && (*it > 3 || !mar1TooEarly) || *it == 2 && feb28ok && QDate::leapYear(data.year))) { if (*it == 2 && data.feb29 && !QDate::leapYear(data.year)) { // The next recurrence should be on February 29th, but it's a non-leap year switch (mFeb29YearlyType) { case rFeb28: data.month = 2; data.day = 28; break; case rMar1: data.month = 3; data.day = 1; break; case rFeb29: // impossible in this context! break; } } else data.month = *it; break; } if (--countTogo == 0) return 0; } ex: enddate = data.date(); return countGone; } /* Find count and, depending on 'func', the end date of an annual recurrence by date. * Reply = total number of occurrences up to 'enddate', or 0 if error. * If 'func' = END_DATE_AND_COUNT or NEXT_AFTER_DATE, 'enddate' is updated to the * recurrence end date. */ struct Recurrence::YearlyPosData { const Recurrence *recurrence; int year; // current year int month; // current month 1..12 int day; // current day of month 1..31 int daysPerMonth; // number of days which recur each month, or -1 if variable int count; // number of days which recur each year, or -1 if variable bool varies; // true if number of days varies from year to year private: - mutable QValueList<int> days; + mutable Q3ValueList<int> days; public: YearlyPosData(const Recurrence* r, const QDate &date) : recurrence(r), year(date.year()), month(date.month()), day(date.day()), count(-1) { if ((daysPerMonth = r->countMonthlyPosDays()) > 0) count = daysPerMonth * r->rYearNums.count(); varies = (daysPerMonth < 0); } - const QValueList<int>* dayList() const { + const Q3ValueList<int>* dayList() const { QDate startOfMonth(year, month, 1); recurrence->getMonthlyPosDays(days, startOfMonth.daysInMonth(), startOfMonth.dayOfWeek()); return &days; } int yearMonth() const { return year*12 + month - 1; } void addMonths(int diff) { month += diff - 1; year += month / 12; month = month % 12 + 1; } QDate date() const { return QDate(year, month, day); } }; int Recurrence::yearlyPosCalc(PeriodFunc func, QDate &enddate) const { if (rYearNums.isEmpty() || rMonthPositions.isEmpty()) return 0; YearlyPosData data(this, mRecurStart.date()); switch (func) { case END_DATE_AND_COUNT: return yearlyPosCalcEndDate(enddate, data); case COUNT_TO_DATE: return yearlyPosCalcToDate(enddate, data); case NEXT_AFTER_DATE: return yearlyPosCalcNextAfter(enddate, data); } return 0; } int Recurrence::yearlyPosCalcEndDate(QDate &enddate, YearlyPosData &data) const { uint countTogo = rDuration + mRecurExDatesCount; int countGone = 0; - QValueList<int>::ConstIterator id; - const QValueList<int>* days; + Q3ValueList<int>::ConstIterator id; + const Q3ValueList<int>* days; if (data.month > 1 || data.day > 1) { // Check what remains of the start year - for (QPtrListIterator<int> im(rYearNums); im.current(); ++im) { + for (Q3PtrListIterator<int> im(rYearNums); im.current(); ++im) { if (*im.current() >= data.month) { // Check what remains of the start month if (data.day > 1 || data.varies || static_cast<uint>(data.daysPerMonth) >= countTogo) { data.month = *im.current(); days = data.dayList(); for (id = days->begin(); id != days->end(); ++id) { if (*id >= data.day) { ++countGone; if (--countTogo == 0) { data.month = *im.current(); data.day = *id; goto ex; } } } data.day = 1; } else { // The number of days per month is constant, so skip // the whole month. countTogo -= data.daysPerMonth; countGone += data.daysPerMonth; } } } data.month = 1; data.year += rFreq; } if (data.varies) { // The number of recurrences varies from year to year. for ( ; ; ) { - for (QPtrListIterator<int> im(rYearNums); im.current(); ++im) { + for (Q3PtrListIterator<int> im(rYearNums); im.current(); ++im) { data.month = *im.current(); days = data.dayList(); int n = days->count(); if (static_cast<uint>(n) >= countTogo) { // Check the last month in the recurrence for (id = days->begin(); id != days->end(); ++id) { ++countGone; if (--countTogo == 0) { data.day = *id; goto ex; } } } countTogo -= n; countGone += n; } data.year += rFreq; } } else { // The number of recurrences is the same every year, // so skip the year-by-year check. // Skip the remaining whole years, but leave at least // 1 recurrence remaining, in order to get its date. int wholeYears = (countTogo - 1) / data.count; data.year += wholeYears * rFreq; countGone += wholeYears * data.count; countTogo -= wholeYears * data.count; // Check the last year in the recurrence. - for (QPtrListIterator<int> im(rYearNums); im.current(); ++im) { + for (Q3PtrListIterator<int> im(rYearNums); im.current(); ++im) { if (static_cast<uint>(data.daysPerMonth) >= countTogo) { // Check the last month in the recurrence data.month = *im.current(); days = data.dayList(); for (id = days->begin(); id != days->end(); ++id) { ++countGone; if (--countTogo == 0) { data.day = *id; goto ex; } } } countTogo -= data.daysPerMonth; countGone += data.daysPerMonth; } data.year += rFreq; } ex: enddate = data.date(); return countGone; } int Recurrence::yearlyPosCalcToDate(const QDate &enddate, YearlyPosData &data) const { int countGone = 0; int countMax = (rDuration > 0) ? rDuration + mRecurExDatesCount : INT_MAX; int endYear = enddate.year(); int endMonth = enddate.month(); int endDay = enddate.day(); if (endDay < data.day && --endMonth == 0) { endMonth = 12; --endYear; } int endYearMonth = endYear*12 + endMonth; - QValueList<int>::ConstIterator id; - const QValueList<int>* days; + Q3ValueList<int>::ConstIterator id; + const Q3ValueList<int>* days; if (data.month > 1 || data.day > 1) { // Check what remains of the start year - for (QPtrListIterator<int> im(rYearNums); im.current(); ++im) { + for (Q3PtrListIterator<int> im(rYearNums); im.current(); ++im) { if (*im.current() >= data.month) { data.month = *im.current(); if (data.yearMonth() > endYearMonth) return countGone; // Check what remains of the start month bool lastMonth = (data.yearMonth() == endYearMonth); if (lastMonth || data.day > 1 || data.varies) { days = data.dayList(); if (lastMonth || data.day > 1) { for (id = days->begin(); id != days->end(); ++id) { if (*id >= data.day) { if (lastMonth && *id > endDay) return countGone; if (++countGone >= countMax) return countMax; } } } else { countGone += days->count(); if (countGone >= countMax) return countMax; } data.day = 1; } else { // The number of days per month is constant, so skip // the whole month. countGone += data.daysPerMonth; if (countGone >= countMax) return countMax; } } } data.month = 1; data.year += rFreq; } if (data.varies) { // The number of recurrences varies from year to year. for ( ; ; ) { - for (QPtrListIterator<int> im(rYearNums); im.current(); ++im) { + for (Q3PtrListIterator<int> im(rYearNums); im.current(); ++im) { data.month = *im.current(); days = data.dayList(); if (data.yearMonth() >= endYearMonth) { if (data.yearMonth() > endYearMonth) return countGone; // Check the last month in the recurrence for (id = days->begin(); id != days->end(); ++id) { if (*id > endDay) return countGone; if (++countGone >= countMax) return countMax; } } else { countGone += days->count(); if (countGone >= countMax) return countMax; } } data.year += rFreq; } } else { // The number of recurrences is the same every year, // so skip the year-by-year check. // Skip the remaining whole years, but leave at least // 1 recurrence remaining, in order to get its date. int wholeYears = endYear - data.year; countGone += (wholeYears / rFreq) * data.count; if (countGone >= countMax) return countMax; if (wholeYears % rFreq) return countGone; // end year isn't a recurrence year data.year = endYear; // Check the last year in the recurrence. - for (QPtrListIterator<int> im(rYearNums); im.current(); ++im) { + for (Q3PtrListIterator<int> im(rYearNums); im.current(); ++im) { data.month = *im.current(); if (data.month >= endMonth) { if (data.month > endMonth) return countGone; // Check the last month in the recurrence days = data.dayList(); for (id = days->begin(); id != days->end(); ++id) { if (*id > endDay) return countGone; if (++countGone >= countMax) return countMax; } } else { countGone += data.daysPerMonth; if (countGone >= countMax) return countMax; } } } return countGone; } int Recurrence::yearlyPosCalcNextAfter(QDate &enddate, YearlyPosData &data) const { uint countTogo = (rDuration > 0) ? rDuration + mRecurExDatesCount : UINT_MAX; int countGone = 0; int endYear = enddate.year(); int endMonth = enddate.month(); int endDay = enddate.day(); if (endDay < data.day && --endMonth == 0) { endMonth = 12; --endYear; } int endYearMonth = endYear*12 + endMonth; - QValueList<int>::ConstIterator id; - const QValueList<int>* days; + Q3ValueList<int>::ConstIterator id; + const Q3ValueList<int>* days; if (data.varies) { // The number of recurrences varies from year to year. for ( ; ; ) { // Check the next year - for (QPtrListIterator<int> im(rYearNums); im.current(); ++im) { + for (Q3PtrListIterator<int> im(rYearNums); im.current(); ++im) { if (*im.current() >= data.month) { // Check the next month data.month = *im.current(); int ended = data.yearMonth() - endYearMonth; days = data.dayList(); if (ended >= 0 || data.day > 1) { // This is the start or end month, so check each day for (id = days->begin(); id != days->end(); ++id) { if (*id >= data.day) { ++countGone; if (ended > 0 || (ended == 0 && *id > endDay)) { data.day = *id; goto ex; } if (--countTogo == 0) return 0; } } } else { // Skip the whole month uint n = days->count(); if (n >= countTogo) return 0; countGone += n; } data.day = 1; // we've checked the start month now } } data.month = 1; // we've checked the start year now data.year += rFreq; } } else { // The number of recurrences is the same every year. if (data.month > 1 || data.day > 1) { // Check what remains of the start year - for (QPtrListIterator<int> im(rYearNums); im.current(); ++im) { + for (Q3PtrListIterator<int> im(rYearNums); im.current(); ++im) { if (*im.current() >= data.month) { // Check what remains of the start month data.month = *im.current(); int ended = data.yearMonth() - endYearMonth; if (ended >= 0 || data.day > 1) { // This is the start or end month, so check each day days = data.dayList(); for (id = days->begin(); id != days->end(); ++id) { if (*id >= data.day) { ++countGone; if (ended > 0 || (ended == 0 && *id > endDay)) { data.day = *id; goto ex; } if (--countTogo == 0) return 0; } } data.day = 1; // we've checked the start month now } else { // Skip the whole month. if (static_cast<uint>(data.daysPerMonth) >= countTogo) return 0; countGone += data.daysPerMonth; } } } data.year += rFreq; } // Skip the remaining whole years to at least endYear. int recurYears = (endYear - data.year + rFreq - 1) / rFreq; if ((endYear - data.year)%rFreq == 0 && *rYearNums.getLast() <= endMonth) ++recurYears; // required year is after endYear if (recurYears) { int n = recurYears * data.count; if (static_cast<uint>(n) > countTogo) return 0; // reached end of recurrence countTogo -= n; countGone += n; data.year += recurYears * rFreq; } // Check the last year in the recurrence - for (QPtrListIterator<int> im(rYearNums); im.current(); ++im) { + for (Q3PtrListIterator<int> im(rYearNums); im.current(); ++im) { data.month = *im.current(); int ended = data.yearMonth() - endYearMonth; if (ended >= 0) { // This is the end month, so check each day days = data.dayList(); for (id = days->begin(); id != days->end(); ++id) { ++countGone; if (ended > 0 || (ended == 0 && *id > endDay)) { data.day = *id; goto ex; } if (--countTogo == 0) return 0; } } else { // Skip the whole month. if (static_cast<uint>(data.daysPerMonth) >= countTogo) return 0; countGone += data.daysPerMonth; } } } ex: enddate = data.date(); return countGone; } /* Find count and, depending on 'func', the end date of an annual recurrence by day. * Reply = total number of occurrences up to 'enddate', or 0 if error. * If 'func' = END_DATE_AND_COUNT or NEXT_AFTER_DATE, 'enddate' is updated to the * recurrence end date. */ struct Recurrence::YearlyDayData { int year; // current year int day; // current day of year 1..366 bool varies; // true if day 366 recurs private: int daycount; public: YearlyDayData(const Recurrence* r, const QDate &date) : year(date.year()), day(date.dayOfYear()), varies(*r->rYearNums.getLast() == 366), daycount(r->rYearNums.count()) { } bool leapYear() const { return QDate::leapYear(year); } int dayCount() const { return daycount - (varies && !QDate::leapYear(year) ? 1 : 0); } bool isMaxDayCount() const { return !varies || QDate::leapYear(year); } QDate date() const { return QDate(year, 1, 1).addDays(day - 1); } }; int Recurrence::yearlyDayCalc(PeriodFunc func, QDate &enddate) const { if (rYearNums.isEmpty()) return 0; YearlyDayData data(this, mRecurStart.date()); switch (func) { case END_DATE_AND_COUNT: return yearlyDayCalcEndDate(enddate, data); case COUNT_TO_DATE: return yearlyDayCalcToDate(enddate, data); case NEXT_AFTER_DATE: return yearlyDayCalcNextAfter(enddate, data); } return 0; } int Recurrence::yearlyDayCalcEndDate(QDate &enddate, YearlyDayData &data) const { uint countTogo = rDuration + mRecurExDatesCount; int countGone = 0; if (data.day > 1) { // Check what remains of the start year bool leapOK = data.isMaxDayCount(); - for (QPtrListIterator<int> it(rYearNums); it.current(); ++it) { + for (Q3PtrListIterator<int> it(rYearNums); it.current(); ++it) { int d = *it.current(); if (d >= data.day && (leapOK || d < 366)) { ++countGone; if (--countTogo == 0) { data.day = d; goto ex; } } } data.day = 1; data.year += rFreq; } if (data.varies) { // The number of recurrences is different in leap years, // so check year-by-year. for ( ; ; ) { uint n = data.dayCount(); if (n >= countTogo) break; countTogo -= n; countGone += n; data.year += rFreq; } } else { // The number of recurrences is the same every year, // so skip the year-by-year check. // Skip the remaining whole years, but leave at least // 1 recurrence remaining, in order to get its date. int daysPerYear = rYearNums.count(); int wholeYears = (countTogo - 1) / daysPerYear; data.year += wholeYears * rFreq; countGone += wholeYears * daysPerYear; countTogo -= wholeYears * daysPerYear; } if (countTogo) { // Check the last year in the recurrence - for (QPtrListIterator<int> it(rYearNums); it.current(); ++it) { + for (Q3PtrListIterator<int> it(rYearNums); it.current(); ++it) { ++countGone; if (--countTogo == 0) { data.day = *it.current(); break; } } } ex: enddate = data.date(); return countGone; } int Recurrence::yearlyDayCalcToDate(const QDate &enddate, YearlyDayData &data) const { int countGone = 0; int countMax = (rDuration > 0) ? rDuration + mRecurExDatesCount : INT_MAX; int endYear = enddate.year(); int endDay = enddate.dayOfYear(); if (data.day > 1) { // Check what remains of the start year bool leapOK = data.isMaxDayCount(); - for (QPtrListIterator<int> it(rYearNums); it.current(); ++it) { + for (Q3PtrListIterator<int> it(rYearNums); it.current(); ++it) { int d = *it.current(); if (d >= data.day && (leapOK || d < 366)) { if (data.year == endYear && d > endDay) return countGone; if (++countGone >= countMax) return countMax; } } data.day = 1; data.year += rFreq; } if (data.varies) { // The number of recurrences is different in leap years, // so check year-by-year. while (data.year < endYear) { uint n = data.dayCount(); countGone += n; if (countGone >= countMax) return countMax; data.year += rFreq; } if (data.year > endYear) return countGone; } else { // The number of recurrences is the same every year. // Skip the remaining whole years. int wholeYears = endYear - data.year; countGone += (wholeYears / rFreq) * rYearNums.count(); if (countGone >= countMax) return countMax; if (wholeYears % rFreq) return countGone; // end year isn't a recurrence year data.year = endYear; } if (data.year <= endYear) { // Check the last year in the recurrence - for (QPtrListIterator<int> it(rYearNums); it.current(); ++it) { + for (Q3PtrListIterator<int> it(rYearNums); it.current(); ++it) { if (*it.current() > endDay) return countGone; if (++countGone >= countMax) return countMax; } } return countGone; } int Recurrence::yearlyDayCalcNextAfter(QDate &enddate, YearlyDayData &data) const { uint countTogo = (rDuration > 0) ? rDuration + mRecurExDatesCount : UINT_MAX; int countGone = 0; int endYear = enddate.year(); int endDay = enddate.dayOfYear(); if (data.day > 1) { // Check what remains of the start year bool leapOK = data.isMaxDayCount(); - for (QPtrListIterator<int> it(rYearNums); it.current(); ++it) { + for (Q3PtrListIterator<int> it(rYearNums); it.current(); ++it) { int d = *it.current(); if (d >= data.day && (leapOK || d < 366)) { ++countGone; if (data.year == endYear && d > endDay) { data.day = d; goto ex; } if (--countTogo == 0) return 0; } } data.day = 1; data.year += rFreq; } if (data.varies) { // The number of recurrences is different in leap years, // so check year-by-year. while (data.year <= endYear) { uint n = data.dayCount(); if (data.year == endYear && *rYearNums.getLast() > endDay) break; if (n >= countTogo) break; countTogo -= n; countGone += n; data.year += rFreq; } } else { // The number of recurrences is the same every year, // so skip the year-by-year check. // Skip the remaining whole years to at least endYear. int daysPerYear = rYearNums.count(); int recurYears = (endYear - data.year + rFreq - 1) / rFreq; if ((endYear - data.year)%rFreq == 0 && *rYearNums.getLast() <= endDay) ++recurYears; // required year is after endYear if (recurYears) { int n = recurYears * daysPerYear; if (static_cast<uint>(n) > countTogo) return 0; // reached end of recurrence countTogo -= n; countGone += n; data.year += recurYears * rFreq; } } // Check the last year in the recurrence - for (QPtrListIterator<int> it(rYearNums); it.current(); ++it) { + for (Q3PtrListIterator<int> it(rYearNums); it.current(); ++it) { ++countGone; int d = *it.current(); if (data.year > endYear || d > endDay) { data.day = d; break; } if (--countTogo == 0) return 0; } ex: enddate = data.date(); return countGone; } // Get the days in this month which recur, in numerical order. // Parameters: daysInMonth = number of days in this month // startDayOfWeek = day of week for first day of month. -void Recurrence::getMonthlyPosDays(QValueList<int> &list, int daysInMonth, int startDayOfWeek) const +void Recurrence::getMonthlyPosDays(Q3ValueList<int> &list, int daysInMonth, int startDayOfWeek) const { list.clear(); int endDayOfWeek = (startDayOfWeek + daysInMonth - 2) % 7 + 1; // Go through the list, compiling a bit list of actual day numbers Q_UINT32 days = 0; - for (QPtrListIterator<rMonthPos> pos(rMonthPositions); pos.current(); ++pos) { + for (Q3PtrListIterator<rMonthPos> pos(rMonthPositions); pos.current(); ++pos) { int weeknum = pos.current()->rPos - 1; // get 0-based week number QBitArray &rdays = pos.current()->rDays; if (pos.current()->negative) { // nth days before the end of the month for (uint i = 1; i <= 7; ++i) { if (rdays.testBit(i - 1)) { int day = daysInMonth - weeknum*7 - (endDayOfWeek - i + 7) % 7; if (day > 0) days |= 1 << (day - 1); } } } else { // nth days after the start of the month for (uint i = 1; i <= 7; ++i) { if (rdays.testBit(i - 1)) { int day = 1 + weeknum*7 + (i - startDayOfWeek + 7) % 7; if (day <= daysInMonth) days |= 1 << (day - 1); } } } } // Compile the ordered list Q_UINT32 mask = 1; for (int i = 0; i < daysInMonth; mask <<= 1, ++i) { if (days & mask) list.append(i + 1); } } // Get the number of days in the month which recur. // Reply = -1 if the number varies from month to month. int Recurrence::countMonthlyPosDays() const { int count = 0; Q_UINT8 positive[5] = { 0, 0, 0, 0, 0 }; Q_UINT8 negative[4] = { 0, 0, 0, 0 }; - for (QPtrListIterator<rMonthPos> pos(rMonthPositions); pos.current(); ++pos) { + for (Q3PtrListIterator<rMonthPos> pos(rMonthPositions); pos.current(); ++pos) { int weeknum = pos.current()->rPos; Q_UINT8* wk; if (pos.current()->negative) { // nth days before the end of the month if (weeknum > 4) return -1; // days in 5th week are often missing wk = &negative[4 - weeknum]; } else { // nth days after the start of the month if (weeknum > 4) return -1; // days in 5th week are often missing wk = &positive[weeknum - 1]; } QBitArray &rdays = pos.current()->rDays; for (uint i = 0; i < 7; ++i) { if (rdays.testBit(i)) { ++count; *wk |= (1 << i); } } } // Check for any possible days which could be duplicated by // a positive and a negative position. for (int i = 0; i < 4; ++i) { if (negative[i] & (positive[i] | positive[i+1])) return -1; } return count; } // Get the days in this month which recur, in numerical order. // Reply = true if day numbers varies from month to month. -bool Recurrence::getMonthlyDayDays(QValueList<int> &list, int daysInMonth) const +bool Recurrence::getMonthlyDayDays(Q3ValueList<int> &list, int daysInMonth) const { list.clear(); bool variable = false; Q_UINT32 days = 0; - for (QPtrListIterator<int> it(rMonthDays); it.current(); ++it) { + for (Q3PtrListIterator<int> it(rMonthDays); it.current(); ++it) { int day = *it.current(); if (day > 0) { // date in the month if (day <= daysInMonth) days |= 1 << (day - 1); if (day > 28 && day <= 31) variable = true; // this date does not appear in some months } else if (day < 0) { // days before the end of the month variable = true; // this date varies depending on the month length day = daysInMonth + day; // zero-based day of month if (day >= 0) days |= 1 << day; } } // Compile the ordered list Q_UINT32 mask = 1; for (int i = 0; i < daysInMonth; mask <<= 1, ++i) { if (days & mask) list.append(i + 1); } return variable; } // Get the months which recur, in numerical order, for both leap years and non-leap years. // N.B. If February 29th recurs on March 1st in non-leap years, February (not March) is // included in the non-leap year month list. // Reply = true if February 29th also recurs. -bool Recurrence::getYearlyMonthMonths(int day, QValueList<int> &list, QValueList<int> &leaplist) const +bool Recurrence::getYearlyMonthMonths(int day, Q3ValueList<int> &list, Q3ValueList<int> &leaplist) const { list.clear(); leaplist.clear(); bool feb29 = false; - for (QPtrListIterator<int> it(rYearNums); it.current(); ++it) { + for (Q3PtrListIterator<int> it(rYearNums); it.current(); ++it) { int month = *it.current(); if (month == 2) { if (day <= 28) { list.append(month); // date appears in February leaplist.append(month); } else if (day == 29) { // February 29th leaplist.append(month); switch (mFeb29YearlyType) { case rFeb28: case rMar1: list.append(2); break; case rFeb29: break; } feb29 = true; } } else if (day <= 30 || QDate(2000, month, 1).daysInMonth() == 31) { list.append(month); // date appears in every month leaplist.append(month); } } return feb29; } /* From the recurrence day of the week list, get the earliest day in the * specified week which is >= the startDay. * Parameters: startDay = 1..7 (Monday..Sunday) * useWeekStart = true to end search at day before next rWeekStart * = false to search for a full 7 days * Reply = day of the week (1..7), or 0 if none found. */ int Recurrence::getFirstDayInWeek(int startDay, bool useWeekStart) const { int last = ((useWeekStart ? rWeekStart : startDay) + 5)%7; for (int i = startDay - 1; ; i = (i + 1)%7) { if (rDays.testBit(i)) return i + 1; if (i == last) return 0; } } /* From the recurrence day of the week list, get the latest day in the * specified week which is <= the endDay. * Parameters: endDay = 1..7 (Monday..Sunday) * useWeekStart = true to end search at rWeekStart * = false to search for a full 7 days * Reply = day of the week (1..7), or 0 if none found. */ int Recurrence::getLastDayInWeek(int endDay, bool useWeekStart) const { int last = useWeekStart ? rWeekStart - 1 : endDay%7; for (int i = endDay - 1; ; i = (i + 6)%7) { if (rDays.testBit(i)) return i + 1; if (i == last) return 0; } } /* From the recurrence monthly day number list or monthly day of week/week of * month list, get the earliest day in the specified month which is >= the * earliestDate. */ QDate Recurrence::getFirstDateInMonth(const QDate &earliestDate) const { int earliestDay = earliestDate.day(); int daysInMonth = earliestDate.daysInMonth(); switch (recurs) { case rMonthlyDay: { int minday = daysInMonth + 1; - for (QPtrListIterator<int> it(rMonthDays); it.current(); ++it) { + for (Q3PtrListIterator<int> it(rMonthDays); it.current(); ++it) { int day = *it.current(); if (day < 0) day = daysInMonth + day + 1; if (day >= earliestDay && day < minday) minday = day; } if (minday <= daysInMonth) return earliestDate.addDays(minday - earliestDay); break; } case rMonthlyPos: case rYearlyPos: { QDate monthBegin(earliestDate.addDays(1 - earliestDay)); - QValueList<int> dayList; + Q3ValueList<int> dayList; getMonthlyPosDays(dayList, daysInMonth, monthBegin.dayOfWeek()); - for (QValueList<int>::ConstIterator id = dayList.begin(); id != dayList.end(); ++id) { + for (Q3ValueList<int>::ConstIterator id = dayList.begin(); id != dayList.end(); ++id) { if (*id >= earliestDay) return monthBegin.addDays(*id - 1); } break; } } return QDate(); } /* From the recurrence monthly day number list or monthly day of week/week of * month list, get the latest day in the specified month which is <= the * latestDate. */ QDate Recurrence::getLastDateInMonth(const QDate &latestDate) const { int latestDay = latestDate.day(); int daysInMonth = latestDate.daysInMonth(); switch (recurs) { case rMonthlyDay: { int maxday = -1; - for (QPtrListIterator<int> it(rMonthDays); it.current(); ++it) { + for (Q3PtrListIterator<int> it(rMonthDays); it.current(); ++it) { int day = *it.current(); if (day < 0) day = daysInMonth + day + 1; if (day <= latestDay && day > maxday) maxday = day; } if (maxday > 0) return QDate(latestDate.year(), latestDate.month(), maxday); break; } case rMonthlyPos: case rYearlyPos: { QDate monthBegin(latestDate.addDays(1 - latestDay)); - QValueList<int> dayList; + Q3ValueList<int> dayList; getMonthlyPosDays(dayList, daysInMonth, monthBegin.dayOfWeek()); - for (QValueList<int>::ConstIterator id = dayList.fromLast(); id != dayList.end(); --id) { + for (Q3ValueList<int>::ConstIterator id = dayList.fromLast(); id != dayList.end(); --id) { if (*id <= latestDay) return monthBegin.addDays(*id - 1); } break; } } return QDate(); } /* From the recurrence yearly month list or yearly day list, get the earliest * month or day in the specified year which is >= the earliestDate. * Note that rYearNums is sorted in numerical order. */ QDate Recurrence::getFirstDateInYear(const QDate &earliestDate) const { - QPtrListIterator<int> it(rYearNums); + Q3PtrListIterator<int> it(rYearNums); switch (recurs) { case rYearlyMonth: { int day = recurStart().date().day(); int earliestYear = earliestDate.year(); int earliestMonth = earliestDate.month(); int earliestDay = earliestDate.day(); if (earliestDay > day) { // The earliest date is later in the month than the recurrence date, // so skip to the next month before starting to check if (++earliestMonth > 12) return QDate(); } for ( ; it.current(); ++it) { int month = *it.current(); if (month >= earliestMonth) { if (day <= 28 || QDate::isValid(earliestYear, month, day)) return QDate(earliestYear, month, day); if (day == 29 && month == 2) { // It's a recurrence on February 29th, in a non-leap year switch (mFeb29YearlyType) { case rMar1: return QDate(earliestYear, 3, 1); case rFeb28: if (earliestDay <= 28) return QDate(earliestYear, 2, 28); break; case rFeb29: break; } } } } break; } case rYearlyPos: { - QValueList<int> dayList; + Q3ValueList<int> dayList; int earliestYear = earliestDate.year(); int earliestMonth = earliestDate.month(); int earliestDay = earliestDate.day(); for ( ; it.current(); ++it) { int month = *it.current(); if (month >= earliestMonth) { QDate monthBegin(earliestYear, month, 1); getMonthlyPosDays(dayList, monthBegin.daysInMonth(), monthBegin.dayOfWeek()); - for (QValueList<int>::ConstIterator id = dayList.begin(); id != dayList.end(); ++id) { + for (Q3ValueList<int>::ConstIterator id = dayList.begin(); id != dayList.end(); ++id) { if (*id >= earliestDay) return monthBegin.addDays(*id - 1); } earliestDay = 1; } } break; } case rYearlyDay: { int earliestDay = earliestDate.dayOfYear(); for ( ; it.current(); ++it) { int day = *it.current(); if (day >= earliestDay && (day <= 365 || day <= earliestDate.daysInYear())) return earliestDate.addDays(day - earliestDay); } break; } } return QDate(); } /* From the recurrence yearly month list or yearly day list, get the latest * month or day in the specified year which is <= the latestDate. * Note that rYearNums is sorted in numerical order. */ QDate Recurrence::getLastDateInYear(const QDate &latestDate) const { - QPtrListIterator<int> it(rYearNums); + Q3PtrListIterator<int> it(rYearNums); switch (recurs) { case rYearlyMonth: { int day = recurStart().date().day(); int latestYear = latestDate.year(); int latestMonth = latestDate.month(); if (latestDate.day() > day) { // The latest date is earlier in the month than the recurrence date, // so skip to the previous month before starting to check if (--latestMonth <= 0) return QDate(); } for (it.toLast(); it.current(); --it) { int month = *it.current(); if (month <= latestMonth) { if (day <= 28 || QDate::isValid(latestYear, month, day)) return QDate(latestYear, month, day); if (day == 29 && month == 2) { // It's a recurrence on February 29th, in a non-leap year switch (mFeb29YearlyType) { case rMar1: if (latestMonth >= 3) return QDate(latestYear, 3, 1); break; case rFeb28: return QDate(latestYear, 2, 28); case rFeb29: break; } } } } break; } case rYearlyPos: { - QValueList<int> dayList; + Q3ValueList<int> dayList; int latestYear = latestDate.year(); int latestMonth = latestDate.month(); int latestDay = latestDate.day(); for (it.toLast(); it.current(); --it) { int month = *it.current(); if (month <= latestMonth) { QDate monthBegin(latestYear, month, 1); getMonthlyPosDays(dayList, monthBegin.daysInMonth(), monthBegin.dayOfWeek()); - for (QValueList<int>::ConstIterator id = dayList.fromLast(); id != dayList.end(); --id) { + for (Q3ValueList<int>::ConstIterator id = dayList.fromLast(); id != dayList.end(); --id) { if (*id <= latestDay) return monthBegin.addDays(*id - 1); } latestDay = 31; } } break; } case rYearlyDay: { int latestDay = latestDate.dayOfYear(); for (it.toLast(); it.current(); --it) { int day = *it.current(); if (day <= latestDay) return latestDate.addDays(day - latestDay); } break; } } return QDate(); } void Recurrence::dump() const { ; } diff --git a/libkcal/recurrence.h b/libkcal/recurrence.h index b13d14f..5b5aab1 100644 --- a/libkcal/recurrence.h +++ b/libkcal/recurrence.h @@ -1,401 +1,403 @@ /* This file is part of libkcal. Copyright (c) 1998 Preston Brown Copyright (c) 2001 Cornelius Schumacher <schumacher@kde.org> Copyright (c) 2002 David Jarvie <software@astrojar.org.uk> 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #ifndef KCAL_RECURRENCE_H #define KCAL_RECURRENCE_H #include <qstring.h> #include <qbitarray.h> -#include <qptrlist.h> +#include <q3ptrlist.h> +//Added by qt3to4: +#include <Q3ValueList> namespace KCal { class Incidence; /** This class represents a recurrence rule for a calendar incidence. */ class Recurrence { public: /** enumeration for describing how an event recurs, if at all. */ enum { rNone = 0, rMinutely = 0x001, rHourly = 0x0002, rDaily = 0x0003, rWeekly = 0x0004, rMonthlyPos = 0x0005, rMonthlyDay = 0x0006, rYearlyMonth = 0x0007, rYearlyDay = 0x0008, rYearlyPos = 0x0009 }; /** Enumeration for specifying what date yearly recurrences of February 29th occur * in non-leap years. */ enum Feb29Type { rMar1, // recur on March 1st (default) rFeb28, // recur on February 28th rFeb29 // only recur on February 29th, i.e. don't recur in non-leap years }; /** structure for Recurs rMonthlyPos */ struct rMonthPos { QBitArray rDays; short rPos; bool negative; }; Recurrence(Incidence *parent, int compatVersion = 0); Recurrence(const Recurrence&, Incidence *parent); ~Recurrence(); bool operator==( const Recurrence& ) const; bool operator!=( const Recurrence& r ) const { return !operator==(r); } Incidence *parent() { return mParent; } /** Return the start of the recurrence */ QDateTime recurStart() const { return mRecurStart; } /** Returns the number of exception dates for the recurrence */ int recurExDatesCount() const { return mRecurExDatesCount; } /** Set start of recurrence, as a date and time. */ void setRecurStart(const QDateTime &start); /** Set start of recurrence, as a date with no time. * Recurrence types which are sub-daily (e.g. rHourly) always have a time; * the time is set to 00:00:00 in these cases. */ void setRecurStart(const QDate &start); /** Set whether the recurrence has no time, just a date. * Recurrence types which are sub-daily (e.g. rHourly) always have a time * and cannot be set to float. * N.B. This property is derived by default from the parent incidence, * or according to whether a time is specified in setRecurStart(). */ void setFloats(bool f); /** Returns whether the recurrence has no time, just a date. */ bool doesFloat() const { return mFloats; } /** Set if recurrence is read-only or can be changed. */ void setRecurReadOnly(bool readOnly) { mRecurReadOnly = readOnly; } bool recurReadOnly() const { return mRecurReadOnly; } /** Set number of exception dates. */ void setRecurExDatesCount(int count) { if (count >= 0) mRecurExDatesCount = count; } /** Set the calendar file version for backwards compatibility. * @var version is the KOrganizer/libkcal version, e.g. 220 for KDE 2.2.0. * Specify version = 0 to cancel compatibility mode. */ void setCompatVersion(int version = 0); /** Returns the event's recurrence status. See the enumeration at the top * of this file for possible values. */ ushort doesRecur() const; /** Returns true if the date specified is one on which the event will * recur. */ bool recursOnPure(const QDate &qd) const; /** Returns true if the date/time specified is one at which the event will * recur. Times are rounded down to the nearest minute to determine the result. */ bool recursAtPure(const QDateTime &) const; /** Turns off recurrence for the event. */ void unsetRecurs(); /** Returns the date of the next recurrence, after the specified date. * @var preDate the date after which to find the recurrence. * @var last if non-null, *last is set to true if the next recurrence is the * last recurrence, else false. * Reply = date of next recurrence, or invalid date if none. */ QDate getNextDate(const QDate& preDate, bool* last = 0) const; /** Returns the date and time of the next recurrence, after the specified date/time. * If the recurrence has no time, the next date after the specified date is returned. * @var preDate the date/time after which to find the recurrence. * @var last if non-null, *last is set to true if the next recurrence is the * last recurrence, else false. * Reply = date/time of next recurrence, or invalid date if none. */ QDateTime getNextDateTime(const QDateTime& preDateTime, bool* last = 0) const; /** Returns the date of the last previous recurrence, before the specified date. * @var afterDate the date before which to find the recurrence. * @var last if non-null, *last is set to true if the previous recurrence is the * last recurrence, else false. * Reply = date of previous recurrence, or invalid date if none. */ QDate getPreviousDate(const QDate& afterDate, bool* last = 0) const; /** Returns the date and time of the last previous recurrence, before the specified date/time. * If a time later than 00:00:00 is specified and the recurrence has no time, 00:00:00 on * the specified date is returned if that date recurs. * @var afterDate the date/time before which to find the recurrence. * @var last if non-null, *last is set to true if the previous recurrence is the * last recurrence, else false. * Reply = date/time of previous recurrence, or invalid date if none. */ QDateTime getPreviousDateTime(const QDateTime& afterDateTime, bool* last = 0) const; /** Returns frequency of recurrence, in terms of the recurrence time period type. */ int frequency() const; /** Returns the total number of recurrences, including the initial occurrence. */ int duration() const; /** Sets the total number of times the event is to occur, including both the * first and last. */ void setDuration(int duration); /** Returns the number of recurrences up to and including the date specified. */ int durationTo(const QDate &) const; /** Returns the number of recurrences up to and including the date/time specified. */ int durationTo(const QDateTime &) const; /** Returns the date of the last recurrence. * An invalid date is returned if the recurrence has no end. * Note: for some recurrence types, endDate() can involve significant calculation. */ QDate endDate() const; /** Returns the date and time of the last recurrence. * An invalid date is returned if the recurrence has no end. * Note: for some recurrence types, endDateTime() can involve significant calculation. */ QDateTime endDateTime() const; /** Returns a string representing the recurrence end date in the format according to the user's locale settings. */ QString endDateStr(bool shortfmt=true) const; /** Sets an event to recur minutely. * @var _rFreq the frequency to recur, e.g. 2 is every other minute * @var duration the number of times the event is to occur, or -1 to recur indefinitely. */ void setMinutely(int _rFreq, int duration); /** Sets an event to recur minutely. * @var _rFreq the frequency to recur, e.g. 2 is every other minute * @var endDateTime the ending date/time after which to stop recurring */ void setMinutely(int _rFreq, const QDateTime &endDateTime); /** Sets an event to recur hourly. * @var _rFreq the frequency to recur, e.g. 2 is every other hour * @var duration the number of times the event is to occur, or -1 to recur indefinitely. */ void setHourly(int _rFreq, int duration); /** Sets an event to recur hourly. * @var _rFreq the frequency to recur, e.g. 2 is every other hour * @var endDateTime the ending date/time after which to stop recurring */ void setHourly(int _rFreq, const QDateTime &endDateTime); /** Sets an event to recur daily. * @var _rFreq the frequency to recur, e.g. 2 is every other day * @var duration the number of times the event is to occur, or -1 to recur indefinitely. */ void setDaily(int _rFreq, int duration); /** Sets an event to recur daily. * @var _rFreq the frequency to recur, e.g. 2 is every other day * @var endDate the ending date after which to stop recurring */ void setDaily(int _rFreq, const QDate &endDate); /** Sets an event to recur weekly. * @var _rFreq the frequency to recur, e.g. every other week etc. * @var _rDays a 7 bit array indicating which days on which to recur (bit 0 = Monday). * @var duration the number of times the event is to occur, or -1 to recur indefinitely. * @var weekStart the first day of the week (Monday=1 .. Sunday=7, default is Monday). */ void setWeekly(int _rFreq, const QBitArray &_rDays, int duration, int weekStart = 1); /** Sets an event to recur weekly. * @var _rFreq the frequency to recur, e.g. every other week etc. * @var _rDays a 7 bit array indicating which days on which to recur (bit 0 = Monday). * @var endDate the date on which to stop recurring. * @var weekStart the first day of the week (Monday=1 .. Sunday=7, default is Monday). */ void setWeekly(int _rFreq, const QBitArray &_rDays, const QDate &endDate, int weekStart = 1); /** Returns the first day of the week. Monday=1 .. Sunday=7. */ int weekStart() const { return rWeekStart; } /** Returns week day mask (bit 0 = Monday). */ const QBitArray &days() const; /** Sets an event to recur monthly. * @var type rMonthlyPos or rMonthlyDay * @var _rFreq the frequency to recur, e.g. 3 for every third month. * @var duration the number of times the event is to occur, or -1 to recur indefinitely. */ void setMonthly(short type, int _rFreq, int duration); /** same as above, but with ending date not number of recurrences */ void setMonthly(short type, int _rFreq, const QDate &endDate); /** Adds a position to the recursMonthlyPos recurrence rule, if it is * set. * @var _rPos the position in the month for the recurrence, with valid * values being 1-5 (5 weeks max in a month). * @var _rDays the days for the position to recur on (bit 0 = Monday). * Example: _rPos = 2, and bits 0 and 2 are set in _rDays: * the rule is to repeat every 2nd Monday and Wednesday in the month. */ void addMonthlyPos(short _rPos, const QBitArray &_rDays); /** Adds a position the the recursMonthlyDay list. * @var _rDay the date in the month to recur. */ void addMonthlyDay(short _rDay); /** Returns list of day positions in months. */ - const QPtrList<rMonthPos> &monthPositions() const; + const Q3PtrList<rMonthPos> &monthPositions() const; /** Returns list of day numbers of a month. */ - const QPtrList<int> &monthDays() const; + const Q3PtrList<int> &monthDays() const; /** Sets an event to recur yearly. * @var type rYearlyMonth, rYearlyPos or rYearlyDay * @var freq the frequency to recur, e.g. 3 for every third year. * @var duration the number of times the event is to occur, or -1 to recur indefinitely. */ void setYearly(int type, int freq, int duration); /** Sets an event to recur yearly ending at \a endDate. */ void setYearly(int type, int freq, const QDate &endDate); /** Sets an event to recur yearly on specified dates. * The dates must be specified by calling addYearlyNum(). * @var type the way recurrences of February 29th are to be handled in non-leap years. * @var freq the frequency to recur, e.g. 3 for every third year. * @var duration the number of times the event is to occur, or -1 to recur indefinitely. */ void setYearlyByDate(Feb29Type type, int freq, int duration); /** Sets an event to recur yearly ending at \a endDate. */ void setYearlyByDate(Feb29Type type, int freq, const QDate &endDate); /** Adds position of day or month in year. * N.B. for recursYearlyPos, addYearlyMonthPos() must also be called * to add positions within the month. */ void addYearlyNum(short _rNum); /** Adds a position to the recursYearlyPos recurrence rule, if it is set. * N.B. addYearlyNum() must also be called to add recurrence months. * Parameters are the same as for addMonthlyPos(). */ void addYearlyMonthPos(short _rPos, const QBitArray &_rDays); /** Returns positions of days or months in year. */ - const QPtrList<int> &yearNums() const; + const Q3PtrList<int> &yearNums() const; /** Returns list of day positions in months, for a recursYearlyPos recurrence rule. */ - const QPtrList<rMonthPos> &yearMonthPositions() const; + const Q3PtrList<rMonthPos> &yearMonthPositions() const; /** Returns how yearly recurrences of February 29th are handled. */ Feb29Type feb29YearlyType() const { return mFeb29YearlyType; } /** Sets the default method for handling yearly recurrences of February 29th. */ static void setFeb29YearlyTypeDefault(Feb29Type t) { mFeb29YearlyDefaultType = t; } /** Returns the default method for handling yearly recurrences of February 29th. */ static Feb29Type setFeb29YearlyTypeDefault() { return mFeb29YearlyDefaultType; } void addYearlyMonth(short _rPos ); // added LR /** Debug output. */ void dump() const; QString recurrenceText() const; - bool getYearlyMonthMonths(int day, QValueList<int>&, - QValueList<int> &leaplist) const; + bool getYearlyMonthMonths(int day, Q3ValueList<int>&, + Q3ValueList<int> &leaplist) const; protected: enum PeriodFunc { END_DATE_AND_COUNT, COUNT_TO_DATE, NEXT_AFTER_DATE }; struct MonthlyData; friend struct MonthlyData; struct YearlyMonthData; friend struct YearlyMonthData; struct YearlyPosData; friend struct YearlyPosData; struct YearlyDayData; friend struct YearlyDayData; bool recursSecondly(const QDate &, int secondFreq) const; bool recursMinutelyAt(const QDateTime &dt, int minuteFreq) const; bool recursDaily(const QDate &) const; bool recursWeekly(const QDate &) const; bool recursMonthly(const QDate &) const; bool recursYearlyByMonth(const QDate &) const; bool recursYearlyByPos(const QDate &) const; bool recursYearlyByDay(const QDate &) const; QDate getNextDateNoTime(const QDate& preDate, bool* last) const; QDate getPreviousDateNoTime(const QDate& afterDate, bool* last) const; void addMonthlyPos_(short _rPos, const QBitArray &_rDays); void setDailySub(short type, int freq, int duration); void setYearly_(short type, Feb29Type, int freq, int duration); int recurCalc(PeriodFunc, QDate &enddate) const; int recurCalc(PeriodFunc, QDateTime &endtime) const; int secondlyCalc(PeriodFunc, QDateTime& endtime, int freq) const; int dailyCalc(PeriodFunc, QDate &enddate) const; int weeklyCalc(PeriodFunc, QDate &enddate) const; int weeklyCalcEndDate(QDate& enddate, int daysPerWeek) const; int weeklyCalcToDate(const QDate& enddate, int daysPerWeek) const; int weeklyCalcNextAfter(QDate& enddate, int daysPerWeek) const; int monthlyCalc(PeriodFunc, QDate &enddate) const; int monthlyCalcEndDate(QDate& enddate, MonthlyData&) const; int monthlyCalcToDate(const QDate& enddate, MonthlyData&) const; int monthlyCalcNextAfter(QDate& enddate, MonthlyData&) const; int yearlyMonthCalc(PeriodFunc, QDate &enddate) const; int yearlyMonthCalcEndDate(QDate& enddate, YearlyMonthData&) const; int yearlyMonthCalcToDate(const QDate& enddate, YearlyMonthData&) const; int yearlyMonthCalcNextAfter(QDate& enddate, YearlyMonthData&) const; int yearlyPosCalc(PeriodFunc, QDate &enddate) const; int yearlyPosCalcEndDate(QDate& enddate, YearlyPosData&) const; int yearlyPosCalcToDate(const QDate& enddate, YearlyPosData&) const; int yearlyPosCalcNextAfter(QDate& enddate, YearlyPosData&) const; int yearlyDayCalc(PeriodFunc, QDate &enddate) const; int yearlyDayCalcEndDate(QDate& enddate, YearlyDayData&) const; int yearlyDayCalcToDate(const QDate& enddate, YearlyDayData&) const; int yearlyDayCalcNextAfter(QDate& enddate, YearlyDayData&) const; int countMonthlyPosDays() const; - void getMonthlyPosDays(QValueList<int>&, int daysInMonth, + void getMonthlyPosDays(Q3ValueList<int>&, int daysInMonth, int startDayOfWeek) const; - bool getMonthlyDayDays(QValueList<int>&, int daysInMonth) const; + bool getMonthlyDayDays(Q3ValueList<int>&, int daysInMonth) const; int getFirstDayInWeek(int startDay, bool useWeekStart = true) const; int getLastDayInWeek(int endDay, bool useWeekStart = true) const; QDate getFirstDateInMonth(const QDate& earliestDate) const; QDate getLastDateInMonth(const QDate& latestDate) const; QDate getFirstDateInYear(const QDate& earliestDate) const; QDate getLastDateInYear(const QDate& latestDate) const; private: // Prohibit copying Recurrence(const Recurrence&); Recurrence &operator=(const Recurrence&); short recurs; // should be one of the enums. int rWeekStart; // day which starts the week, Monday=1 .. Sunday=7 QBitArray rDays; // array of days during week it recurs - QPtrList<rMonthPos> rMonthPositions; // list of positions during a month + Q3PtrList<rMonthPos> rMonthPositions; // list of positions during a month // on which an event recurs - QPtrList<int> rMonthDays; // list of days during a month on + Q3PtrList<int> rMonthDays; // list of days during a month on // which the event recurs - QPtrList<int> rYearNums; // either months/days to recur on for rYearly, + Q3PtrList<int> rYearNums; // either months/days to recur on for rYearly, // sorted in numerical order int rFreq; // frequency of period // one of the following must be specified int rDuration; // num times to recur (inc. first occurrence), -1 = infinite QDateTime rEndDateTime; // date/time at which to end recurrence QDateTime mRecurStart; // date/time of first recurrence bool mFloats; // the recurrence has no time, just a date bool mRecurReadOnly; int mRecurExDatesCount; // number of recurrences (in addition to rDuration) which are excluded Feb29Type mFeb29YearlyType; // how to handle yearly recurrences of February 29th static Feb29Type mFeb29YearlyDefaultType; // default value for mFeb29YearlyType // Backwards compatibility for KDE < 3.1. int mCompatVersion; // calendar file version for backwards compatibility short mCompatRecurs; // original 'recurs' in old calendar format, or rNone int mCompatDuration; // original 'rDuration' in old calendar format, or 0 Incidence *mParent; }; } #endif diff --git a/libkcal/scheduler.cpp b/libkcal/scheduler.cpp index 253d8b7..234cfcf 100644 --- a/libkcal/scheduler.cpp +++ b/libkcal/scheduler.cpp @@ -1,355 +1,357 @@ /* This file is part of libkcal. Copyright (c) 2001 Cornelius Schumacher <schumacher@kde.org> 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #include <qdir.h> #include <qfile.h> -#include <qtextstream.h> +#include <q3textstream.h> +//Added by qt3to4: +#include <Q3PtrList> #include <klocale.h> #include <kdebug.h> #include <kstandarddirs.h> #include "event.h" #include "todo.h" #include "freebusy.h" #include "icalformat.h" #include "calendar.h" #include "scheduler.h" using namespace KCal; ScheduleMessage::ScheduleMessage(IncidenceBase *incidence,int method,ScheduleMessage::Status status) { mIncidence = incidence; mMethod = method; mStatus = status; } QString ScheduleMessage::statusName(ScheduleMessage::Status status) { switch (status) { case PublishNew: return i18n("Publish"); case Obsolete: return i18n("Obsolete"); case RequestNew: return i18n("New Request"); case RequestUpdate: return i18n("Updated Request"); default: return i18n("Unknown Status: %1").arg(QString::number(status)); } } Scheduler::Scheduler(Calendar *calendar) { mCalendar = calendar; mFormat = new ICalFormat(); } Scheduler::~Scheduler() { delete mFormat; } bool Scheduler::acceptTransaction(IncidenceBase *incidence,Method method,ScheduleMessage::Status status) { kdDebug() << "Scheduler::acceptTransaction " << endl; switch (method) { case Publish: return acceptPublish(incidence, status, method); case Request: return acceptRequest(incidence, status); case Add: return acceptAdd(incidence, status); case Cancel: return acceptCancel(incidence, status); case Declinecounter: return acceptDeclineCounter(incidence, status); case Reply: return acceptReply(incidence, status, method); case Refresh: return acceptRefresh(incidence, status); case Counter: return acceptCounter(incidence, status); default: deleteTransaction(incidence); return false; } deleteTransaction(incidence); return false; } QString Scheduler::methodName(Method method) { switch (method) { case Publish: return QString::fromLatin1("Publish"); case Request: return QString::fromLatin1("Request"); case Refresh: return QString::fromLatin1("Refresh"); case Cancel: return QString::fromLatin1("Cancel"); case Add: return QString::fromLatin1("Add"); case Reply: return QString::fromLatin1("Reply"); case Counter: return QString::fromLatin1("Counter"); case Declinecounter: return QString::fromLatin1("Decline Counter"); default: return QString::fromLatin1("Unknown"); } } QString Scheduler::translatedMethodName(Method method) { switch (method) { case Publish: return i18n("Publish"); case Request: return i18n("Request"); case Refresh: return i18n("Refresh"); case Cancel: return i18n("Cancel"); case Add: return i18n("Add"); case Reply: return i18n("Reply"); case Counter: return i18n("counter proposal","Counter"); case Declinecounter: return i18n("decline counter proposal","Decline Counter"); default: return i18n("Unknown"); } } bool Scheduler::deleteTransaction(IncidenceBase *) { return true; } bool Scheduler::acceptPublish(IncidenceBase *incidence,ScheduleMessage::Status status, Method method) { if(incidence->type()=="FreeBusy") { return acceptFreeBusy(incidence, method); } switch (status) { case ScheduleMessage::Unknown: case ScheduleMessage::PublishNew: if (!mCalendar->event(incidence->uid())) { Incidence *inc = static_cast<Incidence *>(incidence); mCalendar->addIncidence(inc); deleteTransaction(incidence); } return true; case ScheduleMessage::Obsolete: return true; default: deleteTransaction(incidence); return false; } deleteTransaction(incidence); return false; } bool Scheduler::acceptRequest(IncidenceBase *incidence,ScheduleMessage::Status status) { Incidence *inc = static_cast<Incidence *>(incidence); if (inc->type()=="FreeBusy") { // reply to this request is handled in korganizer's incomingdialog return true; } else { Event *even = mCalendar->event(incidence->uid()); if (even) { if ( even->revision()<=inc->revision() ) { if ( even->revision()==inc->revision() && even->lastModified()>inc->lastModified()) { deleteTransaction(incidence); return false; } mCalendar->deleteEvent(even); } else { deleteTransaction(incidence); return false; } } else { Todo *todo = mCalendar->todo(incidence->uid()); if (todo) { if ( todo->revision()<=inc->revision() ) { if ( todo->revision()==inc->revision() && todo->lastModified()>inc->lastModified()) { deleteTransaction(incidence); return false; } mCalendar->deleteTodo(todo); } else { deleteTransaction(incidence); return false; } } } } mCalendar->addIncidence(inc); deleteTransaction(incidence); return true; } bool Scheduler::acceptAdd(IncidenceBase *incidence,ScheduleMessage::Status status) { deleteTransaction(incidence); return false; } bool Scheduler::acceptCancel(IncidenceBase *incidence,ScheduleMessage::Status status) { bool ret = false; Event *even = mCalendar->event(incidence->uid()); if (even) { mCalendar->deleteEvent(even); ret = true; } else { Todo *todo = mCalendar->todo(incidence->uid()); if (todo) { mCalendar->deleteTodo(todo); ret = true; } } deleteTransaction(incidence); return ret; } bool Scheduler::acceptDeclineCounter(IncidenceBase *incidence,ScheduleMessage::Status status) { deleteTransaction(incidence); return false; } //bool Scheduler::acceptFreeBusy(Incidence *incidence,ScheduleMessage::Status status) //{ // deleteTransaction(incidence); // return false; //} bool Scheduler::acceptReply(IncidenceBase *incidence,ScheduleMessage::Status status, Method method) { if(incidence->type()=="FreeBusy") { return acceptFreeBusy(incidence, method); } bool ret = false; Event *ev = mCalendar->event(incidence->uid()); Todo *to = mCalendar->todo(incidence->uid()); if (ev || to) { //get matching attendee in calendar kdDebug(5800) << "Scheduler::acceptTransaction match found!" << endl; - QPtrList<Attendee> attendeesIn = incidence->attendees(); - QPtrList<Attendee> attendeesEv; + Q3PtrList<Attendee> attendeesIn = incidence->attendees(); + Q3PtrList<Attendee> attendeesEv; if (ev) attendeesEv = ev->attendees(); if (to) attendeesEv = to->attendees(); Attendee *attIn; Attendee *attEv; for ( attIn = attendeesIn.first(); attIn; attIn = attendeesIn.next() ) { for ( attEv = attendeesEv.first(); attEv; attEv = attendeesEv.next() ) { if (attIn->email()==attEv->email()) { //update attendee-info kdDebug(5800) << "Scheduler::acceptTransaction update attendee" << endl; attEv->setStatus(attIn->status()); attEv->setRSVP(false); // better to not update the sequence number with replys //if (ev) ev->setRevision(ev->revision()+1); //if (to) to->setRevision(to->revision()+1); ret = true; } } } } if (ret) deleteTransaction(incidence); return ret; } bool Scheduler::acceptRefresh(IncidenceBase *incidence,ScheduleMessage::Status status) { // handled in korganizer's IncomingDialog deleteTransaction(incidence); return false; } bool Scheduler::acceptCounter(IncidenceBase *incidence,ScheduleMessage::Status status) { deleteTransaction(incidence); return false; } bool Scheduler::acceptFreeBusy(IncidenceBase *incidence, Method method) { FreeBusy *freebusy = static_cast<FreeBusy *>(incidence); QString freeBusyDirName = locateLocal("appdata","freebusy"); kdDebug() << "acceptFreeBusy:: freeBusyDirName: " << freeBusyDirName << endl; QString from; if(method == Scheduler::Publish) { from = freebusy->organizer(); } if((method == Scheduler::Reply) && (freebusy->attendeeCount() == 1)) { Attendee *attendee = freebusy->attendees().first(); from = attendee->email(); } QDir freeBusyDir(freeBusyDirName); if (!freeBusyDir.exists()) { kdDebug() << "Directory " << freeBusyDirName << " does not exist!" << endl; kdDebug() << "Creating directory: " << freeBusyDirName << endl; if(!freeBusyDir.mkdir(freeBusyDirName, TRUE)) { kdDebug() << "Could not create directory: " << freeBusyDirName << endl; return false; } } QString filename(freeBusyDirName); filename += "/"; filename += from; filename += ".ifb"; QFile f(filename); kdDebug() << "acceptFreeBusy: filename" << filename << endl; freebusy->clearAttendees(); freebusy->setOrganizer(from); QString messageText = mFormat->createScheduleMessage(freebusy, Publish); - if (!f.open(IO_ReadWrite)) { + if (!f.open(QIODevice::ReadWrite)) { kdDebug() << "acceptFreeBusy: Can't open:" << filename << " for writing" << endl; return false; } - QTextStream t(&f); + Q3TextStream t(&f); t << messageText; f.close(); deleteTransaction(incidence); return true; } diff --git a/libkcal/scheduler.h b/libkcal/scheduler.h index a9f43b9..357e98e 100644 --- a/libkcal/scheduler.h +++ b/libkcal/scheduler.h @@ -1,133 +1,133 @@ /* This file is part of libkcal. Copyright (c) 2001 Cornelius Schumacher <schumacher@kde.org> 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #ifndef SCHEDULER_H #define SCHEDULER_H // iTIP transactions base class #include <qstring.h> -#include <qptrlist.h> +#include <q3ptrlist.h> namespace KCal { class IncidenceBase; class Event; class Calendar; class ICalFormat; /** This class provides an encapsulation of a scheduling message. It associates an incidence with a method and status information. This class is used by the Scheduler class. @short A Scheduling message */ class ScheduleMessage { public: /** Message status. */ enum Status { PublishNew, Obsolete, RequestNew, RequestUpdate, Unknown }; /** Create a scheduling message with method as defined in Scheduler::Method and a status. */ ScheduleMessage(IncidenceBase *,int method,Status status); ~ScheduleMessage() {}; /** Return event associated with this message. */ IncidenceBase *event() { return mIncidence; } /** Return iTIP method associated with this message. */ int method() { return mMethod; } /** Return status of this message. */ Status status() { return mStatus; } /** Return error message if there is any. */ QString error() { return mError; } /** Return a human-readable name for an ical message status. */ static QString statusName(Status status); private: IncidenceBase *mIncidence; int mMethod; Status mStatus; QString mError; }; /** This class provides an encapsulation of iTIP transactions. It is an abstract base class for inheritance by implementations of the iTIP scheme like iMIP or iRIP. */ class Scheduler { public: /** iTIP methods. */ enum Method { Publish,Request,Refresh,Cancel,Add,Reply,Counter, Declinecounter,NoMethod }; /** Create scheduler for calendar specified as argument. */ Scheduler(Calendar *calendar); virtual ~Scheduler(); /** iTIP publish action */ virtual bool publish (IncidenceBase *incidence,const QString &recipients) = 0; /** Perform iTIP transaction on incidence. The method is specified as the method argumanet and can be any valid iTIP method. */ virtual bool performTransaction(IncidenceBase *incidence,Method method) = 0; /** Perform iTIP transaction on incidence to specified recipient(s). The method is specified as the method argumanet and can be any valid iTIP method. */ virtual bool performTransaction(IncidenceBase *incidence,Method method,const QString &recipients) = 0; /** Retrieve incoming iTIP transactions */ - virtual QPtrList<ScheduleMessage> retrieveTransactions() = 0; + virtual Q3PtrList<ScheduleMessage> retrieveTransactions() = 0; /** Accept transaction. The incidence argument specifies the iCal compoennt on which the transaction acts. The status is the result of processing a iTIP message with the current calendar and specifies the action to be taken for this incidence. */ bool acceptTransaction(IncidenceBase *,Method method,ScheduleMessage::Status status); /** Return a machine-readable name for a iTIP method. */ static QString methodName(Method); /** Return a translated and human-readable name for a iTIP method. */ static QString translatedMethodName(Method); virtual bool deleteTransaction(IncidenceBase *incidence); protected: bool acceptPublish(IncidenceBase *,ScheduleMessage::Status status, Method method); bool acceptRequest(IncidenceBase *,ScheduleMessage::Status status); bool acceptAdd(IncidenceBase *,ScheduleMessage::Status status); bool acceptCancel(IncidenceBase *,ScheduleMessage::Status status); bool acceptDeclineCounter(IncidenceBase *,ScheduleMessage::Status status); bool acceptReply(IncidenceBase *,ScheduleMessage::Status status, Method method); bool acceptRefresh(IncidenceBase *,ScheduleMessage::Status status); bool acceptCounter(IncidenceBase *,ScheduleMessage::Status status); bool acceptFreeBusy(IncidenceBase *,Method method); Calendar *mCalendar; ICalFormat *mFormat; }; } #endif // SCHEDULER_H diff --git a/libkcal/sharpformat.cpp b/libkcal/sharpformat.cpp index 9b757f7..b8c2aa7 100644 --- a/libkcal/sharpformat.cpp +++ b/libkcal/sharpformat.cpp @@ -1,978 +1,978 @@ /* This file is part of libkcal. Copyright (c) 2003 Cornelius Schumacher <schumacher@kde.org> 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #include <qdatetime.h> #include <qstring.h> #include <qapplication.h> -#include <qptrlist.h> +#include <q3ptrlist.h> #include <qregexp.h> #include <qmessagebox.h> #include <qclipboard.h> #include <qfile.h> -#include <qtextstream.h> +#include <q3textstream.h> #include <qtextcodec.h> #include <qxml.h> #include <qlabel.h> #include <kdebug.h> #include <klocale.h> #include <kglobal.h> #include "calendar.h" #include "alarm.h" #include "recurrence.h" #include "calendarlocal.h" #include "sharpformat.h" #include "syncdefines.h" using namespace KCal; //CARDID,CATEGORY,DSRP,PLCE,MEM1,TIM1,TIM2,ADAY,ARON,ARMN,ARSD,RTYP,RFRQ,RPOS,RDYS,REND,REDT,ALSD,ALED,MDAY // 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 //ARSD silentalarm = 0 // 11 RTYP 225 no /0 dialy/ 1 weekly/ 3 month by date/ 2 month by day(pos)/ yearly // 12 RFRQ // 13 RPOS pos = 4. monday in month // 14 RDYS days: 1 mon/ 2 tue .. 64 sun // 15 REND 0 = no end/ 1 = end // 16 REDT rec end dt //ALSD //ALED //MDAY class SharpParser : public QObject { public: SharpParser( Calendar *calendar ) : mCalendar( calendar ) { } bool startElement( Calendar *existingCalendar, const QStringList & attList, QString qName ) { int i = 1; bool skip = true; int max = attList.count() -2; while ( i < max ) { if ( !attList[i].isEmpty() ) { skip = false; break; } ++i ; } if ( skip ) return false; ulong cSum = SharpFormat::getCsum(attList ); if ( qName == "Event" ) { Event *event; event = existingCalendar->event( "Sharp_DTM",attList[0] ); if ( event ) event = (Event*)event->clone(); else event = new Event; event->setID("Sharp_DTM", attList[0] ); event->setCsum( "Sharp_DTM", QString::number( cSum )); event->setTempSyncStat(SYNC_TEMPSTATE_NEW_EXTERNAL ); event->setSummary( attList[2] ); event->setLocation( attList[3] ); event->setDescription( attList[4] ); if ( attList[7] == "1" ) { event->setDtStart( QDateTime(fromString( attList[17]+"T000000", false ).date(),QTime(0,0,0 ) )); event->setDtEnd( QDateTime(fromString( attList[18]+"T000000", false ).date(),QTime(0,0,0 ))); event->setFloats( true ); } else { event->setFloats( false ); event->setDtStart( fromString( attList[5] ) ); event->setDtEnd( fromString( attList[6] )); } QString rtype = attList[11]; if ( rtype != "255" ) { // qDebug("recurs "); QDate startDate = event->dtStart().date(); QString freqStr = attList[12]; int freq = freqStr.toInt(); QString hasEndDateStr = attList[15] ; bool hasEndDate = hasEndDateStr == "1"; QString endDateStr = attList[16]; QDate endDate = fromString( endDateStr ).date(); QString weekDaysStr = attList[14]; uint weekDaysNum = weekDaysStr.toInt(); QBitArray weekDays( 7 ); int i; int bb = 1; for( i = 1; i <= 7; ++i ) { weekDays.setBit( i - 1, ( bb & weekDaysNum )); bb = 2 << (i-1); //qDebug(" %d bit %d ",i-1,weekDays.at(i-1) ); } // qDebug("next "); QString posStr = attList[13]; int pos = posStr.toInt(); Recurrence *r = event->recurrence(); if ( rtype == "0" ) { if ( hasEndDate ) r->setDaily( freq, endDate ); else r->setDaily( freq, -1 ); } else if ( rtype == "1" ) { if ( hasEndDate ) r->setWeekly( freq, weekDays, endDate ); else r->setWeekly( freq, weekDays, -1 ); } else if ( rtype == "3" ) { if ( hasEndDate ) r->setMonthly( Recurrence::rMonthlyDay, freq, endDate ); else r->setMonthly( Recurrence::rMonthlyDay, freq, -1 ); r->addMonthlyDay( startDate.day() ); } else if ( rtype == "2" ) { if ( hasEndDate ) r->setMonthly( Recurrence::rMonthlyPos, freq, endDate ); else r->setMonthly( Recurrence::rMonthlyPos, freq, -1 ); QBitArray days( 7 ); days.fill( false ); days.setBit( startDate.dayOfWeek() - 1 ); r->addMonthlyPos( pos, days ); } else if ( rtype == "4" ) { if ( hasEndDate ) r->setYearly( Recurrence::rYearlyMonth, freq, endDate ); else r->setYearly( Recurrence::rYearlyMonth, freq, -1 ); r->addYearlyNum( startDate.month() ); } } else { event->recurrence()->unsetRecurs(); } QString categoryList = attList[1] ; event->setCategories( categoryList ); // strange 0 semms to mean: alarm enabled if ( attList[8] == "0" ) { Alarm *alarm; if ( event->alarms().count() > 0 ) alarm = event->alarms().first(); else { alarm = new Alarm( event ); event->addAlarm( alarm ); alarm->setType( Alarm::Audio ); } //alarm->setType( Alarm::Audio ); alarm->setEnabled( true ); int alarmOffset = attList[9].toInt(); alarm->setStartOffset( alarmOffset * -60 ); } else { Alarm *alarm; if ( event->alarms().count() > 0 ) { alarm = event->alarms().first(); alarm->setType( Alarm::Audio ); alarm->setStartOffset( -60*15 ); alarm->setEnabled( false ); } } mCalendar->addEvent( event); } else if ( qName == "Todo" ) { Todo *todo; todo = existingCalendar->todo( "Sharp_DTM", attList[0] ); if (todo ) todo = (Todo*)todo->clone(); else todo = new Todo; //CARDID,CATEGORY,ETDY,LTDY,FNDY,MARK,PRTY,TITL,MEM1 // 0 1 2 3 4 5 6 7 8 //1,,,,,1,4,Loch zumachen,"" //3,Privat,20040317T000000,20040318T000000,20040319T000000,0,5,Call bbb,"notes123 bbb gggg ""bb "" " //2,"Familie,Freunde,Holiday",20040318T000000,20040324T000000,20040317T000000,1,2,tod2,notes todo->setID( "Sharp_DTM", attList[0]); todo->setCsum( "Sharp_DTM", QString::number( cSum )); todo->setTempSyncStat( SYNC_TEMPSTATE_NEW_EXTERNAL ); todo->setSummary( attList[7] ); todo->setDescription( attList[8]); int priority = attList[6].toInt(); if ( priority == 0 ) priority = 3; todo->setPriority( priority ); QString categoryList = attList[1]; todo->setCategories( categoryList ); QString hasDateStr = attList[3]; // due if ( !hasDateStr.isEmpty() ) { if ( hasDateStr.right(6) == "000000" ) { todo->setDtDue( QDateTime(fromString( hasDateStr, false ).date(), QTime(0,0,0 )) ); todo->setFloats( true ); } else { todo->setDtDue( fromString( hasDateStr ) ); todo->setFloats( false ); } todo->setHasDueDate( true ); } hasDateStr = attList[2];//start if ( !hasDateStr.isEmpty() ) { todo->setDtStart( fromString( hasDateStr ) ); todo->setHasStartDate( true); } else todo->setHasStartDate( false ); hasDateStr = attList[4];//completed if ( !hasDateStr.isEmpty() ) { todo->setCompleted(fromString( hasDateStr ) ); } QString completedStr = attList[5]; if ( completedStr == "0" ) todo->setCompleted( true ); else { // do not change percent complete if ( todo->isCompleted() ) todo->setCompleted( false ); } mCalendar->addTodo( todo ); } else if ( qName == "Category" ) { /* QString id = attributes.value( "id" ); QString name = attributes.value( "name" ); setCategory( id, name ); */ } //qDebug("end "); return true; } QDateTime fromString ( QString s, bool useTz = true ) { QDateTime dt; int y,m,t,h,min,sec; y = s.mid(0,4).toInt(); m = s.mid(4,2).toInt(); t = s.mid(6,2).toInt(); h = s.mid(9,2).toInt(); min = s.mid(11,2).toInt(); sec = s.mid(13,2).toInt(); dt = QDateTime(QDate(y,m,t), QTime(h,min,sec)); int offset = KGlobal::locale()->localTimeOffset( dt ); if ( useTz ) dt = dt.addSecs ( offset*60); return dt; } protected: QDateTime toDateTime( const QString &value ) { QDateTime dt; dt.setTime_t( value.toUInt() ); return dt; } private: Calendar *mCalendar; }; SharpFormat::SharpFormat() { } SharpFormat::~SharpFormat() { } ulong SharpFormat::getCsum( const QStringList & attList) { int max = attList.count() -1; ulong cSum = 0; int j,k,i; int add; for ( i = 1; i < max ; ++i ) { QString s = attList[i]; if ( ! s.isEmpty() ){ j = s.length(); for ( k = 0; k < j; ++k ) { int mul = k +1; add = s[k].unicode (); if ( k < 16 ) mul = mul * mul; add = add * mul *i*i*i; cSum += add; } } } return cSum; } #include <stdlib.h> #define DEBUGMODE false //#define DEBUGMODE true bool SharpFormat::load( Calendar *calendar, Calendar *existngCal ) { bool debug = DEBUGMODE; QString text; QString codec = "utf8"; QLabel status ( i18n("Reading events ..."), 0 ); int w = status.sizeHint().width()+20 ; if ( w < 200 ) w = 200; int h = status.sizeHint().height()+20 ; int dw = QApplication::desktop()->width(); int dh = QApplication::desktop()->height(); status.setCaption(i18n("Reading DTM Data") ); status.setGeometry( (dw-w)/2, (dh - h )/2 ,w,h ); status.show(); status.raise(); qApp->processEvents(); QString fileName; if ( ! debug ) { fileName = "/tmp/kopitempout"; QString command ="db2file datebook -r -c "+ codec + " > " + fileName; system ( command.latin1() ); } else { fileName = "/tmp/events.txt"; } QFile file( fileName ); - if (!file.open( IO_ReadOnly ) ) { + if (!file.open( QIODevice::ReadOnly ) ) { return false; } - QTextStream ts( &file ); + Q3TextStream ts( &file ); ts.setCodec( QTextCodec::codecForName("utf8") ); text = ts.read(); file.close(); status.setText( i18n("Processing events ...") ); status.raise(); qApp->processEvents(); fromString2Cal( calendar, existngCal, text, "Event" ); status.setText( i18n("Reading todos ...") ); qApp->processEvents(); if ( ! debug ) { fileName = "/tmp/kopitempout"; QString command = "db2file todo -r -c " + codec+ " > " + fileName; system ( command.latin1() ); } else { fileName = "/tmp/todo.txt"; } file.setName( fileName ); - if (!file.open( IO_ReadOnly ) ) { + if (!file.open( QIODevice::ReadOnly ) ) { return false; } ts.setDevice( &file ); text = ts.read(); file.close(); status.setText( i18n("Processing todos ...") ); status.raise(); qApp->processEvents(); fromString2Cal( calendar, existngCal, text, "Todo" ); return true; } int SharpFormat::getNumFromRecord( QString answer, Incidence* inc ) { int retval = -1; QStringList templist; QString tempString; int start = 0; int len = answer.length(); int end = answer.find ("\n",start)+1; bool ok = true; start = end; int ccc = 0; while ( start > 0 ) { templist.clear(); ok = true; int loopCount = 0; while ( ok ) { ++loopCount; if ( loopCount > 25 ) { qDebug("KO: Error in while loop"); ok = false; start = 0; break; } if ( ok ) tempString = getPart( answer, ok, start ); if ( start >= len || start == 0 ) { start = 0; ok = false; } if ( tempString.right(1) =="\n" ) tempString = tempString.left( tempString.length()-1); templist.append( tempString ); } ++ccc; if ( ccc == 2 && loopCount < 25 ) { start = 0; bool ok; int newnum = templist[0].toInt( &ok ); if ( ok && newnum > 0) { retval = newnum; inc->setID( "Sharp_DTM",templist[0] ); inc->setCsum( "Sharp_DTM", QString::number( getCsum( templist ) )); inc->setTempSyncStat( SYNC_TEMPSTATE_NEW_ID ); } if ( ok && newnum == -1 ) { qDebug("Error writing back %s ", inc->summary().latin1()); } } } //qDebug("getNumFromRecord returning : %d ", retval); return retval; } bool SharpFormat::save( Calendar *calendar) { QLabel status ( i18n("Processing/adding events ..."), 0 ); int w = status.sizeHint().width()+20 ; if ( w < 200 ) w = 200; int h = status.sizeHint().height()+20 ; int dw = QApplication::desktop()->width(); int dh = QApplication::desktop()->height(); status.setCaption(i18n("Writing DTM Data") ); status.setGeometry( (dw-w)/2, (dh - h )/2 ,w,h ); status.show(); status.raise(); qApp->processEvents(); bool debug = DEBUGMODE; QString codec = "utf8"; QString answer; QString ePrefix = "CARDID,CATEGORY,DSRP,PLCE,MEM1,TIM1,TIM2,ADAY,ARON,ARMN,ARSD,RTYP,RFRQ,RPOS,RDYS,REND,REDT,ALSD,ALED,MDAY\n"; QString tPrefix = "CARDID,CATEGORY,ETDY,LTDY,FNDY,MARK,PRTY,TITL,MEM1\n"; QString command; - QPtrList<Event> er = calendar->rawEvents(); + Q3PtrList<Event> er = calendar->rawEvents(); Event* ev = er.first(); QString fileName = "/tmp/kopitempout"; int i = 0; QString changeString = ePrefix; QString deleteString = ePrefix; bool deleteEnt = false; bool changeEnt = false; QString message = i18n("Processing event # "); int procCount = 0; while ( ev ) { //qDebug("i %d ", ++i); if ( ev->tempSyncStat() != SYNC_TEMPSTATE_NEW_EXTERNAL ) { status.setText ( message + QString::number ( ++procCount ) ); qApp->processEvents(); QString eString = getEventString( ev ); if ( ev->tempSyncStat() == SYNC_TEMPSTATE_DELETE ) { // delete // deleting empty strings does not work. // we write first and x and then delete the record with the x eString = eString.replace( QRegExp(",\"\""),",\"x\"" ); changeString += eString + "\n"; deleteString += eString + "\n"; deleteEnt = true; changeEnt = true; } else if ( ev->getID("Sharp_DTM").isEmpty() ) { // add new QString fileNameIn = "/tmp/kopitempin"; QFile fileIn( fileNameIn ); - if (!fileIn.open( IO_WriteOnly ) ) { + if (!fileIn.open( QIODevice::WriteOnly ) ) { return false; } - QTextStream tsIn( &fileIn ); + Q3TextStream tsIn( &fileIn ); tsIn.setCodec( QTextCodec::codecForName("utf8") ); tsIn << ePrefix << eString ; fileIn.close(); //command = "(echo \"" + ePrefix + eString + "\" ) | db2file datebook -w -g -c " + codec+ " > "+ fileName; command = "(cat /tmp/kopitempin | db2file datebook -w -g -c " + codec+ ") > "+ fileName; //qDebug("command ++++++++ "); //qDebug("%s ",command.latin1()); //qDebug("command -------- "); system ( command.utf8() ); QFile file( fileName ); - if (!file.open( IO_ReadOnly ) ) { + if (!file.open( QIODevice::ReadOnly ) ) { return false; } - QTextStream ts( &file ); + Q3TextStream ts( &file ); ts.setCodec( QTextCodec::codecForName("utf8") ); answer = ts.read(); file.close(); //qDebug("answer \n%s ", answer.latin1()); getNumFromRecord( answer, ev ) ; } else { // change existing //qDebug("canging %d %d",ev->zaurusStat() ,ev->zaurusId() ); //command = "(echo \"" + ePrefix + eString + "\" ) | db2file datebook -w -g -c " + codec+ " > "+ fileName; changeString += eString + "\n"; changeEnt = true; } } ev = er.next(); } status.setText ( i18n("Changing events ...") ); qApp->processEvents(); //qDebug("changing... "); if ( changeEnt ) { QFile file( fileName ); - if (!file.open( IO_WriteOnly ) ) { + if (!file.open( QIODevice::WriteOnly ) ) { return false; } - QTextStream ts( &file ); + Q3TextStream ts( &file ); ts.setCodec( QTextCodec::codecForName("utf8") ); ts << changeString ; file.close(); command = "db2file datebook -w -g -c " + codec+ " < "+ fileName; system ( command.latin1() ); //qDebug("command %s file :\n%s ", command.latin1(), changeString.latin1()); } status.setText ( i18n("Deleting events ...") ); qApp->processEvents(); //qDebug("deleting... "); if ( deleteEnt ) { QFile file( fileName ); - if (!file.open( IO_WriteOnly ) ) { + if (!file.open( QIODevice::WriteOnly ) ) { return false; } - QTextStream ts( &file ); + Q3TextStream ts( &file ); ts.setCodec( QTextCodec::codecForName("utf8") ); ts << deleteString; file.close(); command = "db2file datebook -d -c " + codec+ " < "+ fileName; system ( command.latin1() ); // qDebug("command %s file :\n%s ", command.latin1(), deleteString.latin1()); } changeString = tPrefix; deleteString = tPrefix; status.setText ( i18n("Processing todos ...") ); qApp->processEvents(); - QPtrList<Todo> tl = calendar->rawTodos(); + Q3PtrList<Todo> tl = calendar->rawTodos(); Todo* to = tl.first(); i = 0; message = i18n("Processing todo # "); procCount = 0; while ( to ) { if ( to->tempSyncStat() != SYNC_TEMPSTATE_NEW_EXTERNAL ) { status.setText ( message + QString::number ( ++procCount ) ); qApp->processEvents(); QString eString = getTodoString( to ); if ( to->tempSyncStat() == SYNC_TEMPSTATE_DELETE ) { // delete // deleting empty strings does not work. // we write first and x and then delete the record with the x eString = eString.replace( QRegExp(",\"\""),",\"x\"" ); changeString += eString + "\n"; deleteString += eString + "\n"; deleteEnt = true; changeEnt = true; } else if ( to->getID("Sharp_DTM").isEmpty() ) { // add new QString fileNameIn = "/tmp/kopitempin"; QFile fileIn( fileNameIn ); - if (!fileIn.open( IO_WriteOnly ) ) { + if (!fileIn.open( QIODevice::WriteOnly ) ) { return false; } - QTextStream tsIn( &fileIn ); + Q3TextStream tsIn( &fileIn ); tsIn.setCodec( QTextCodec::codecForName("utf8") ); tsIn << tPrefix << eString ; fileIn.close(); command = "(cat /tmp/kopitempin | db2file todo -w -g -c " + codec+ ") > "+ fileName; system ( command.utf8() ); QFile file( fileName ); - if (!file.open( IO_ReadOnly ) ) { + if (!file.open( QIODevice::ReadOnly ) ) { return false; } - QTextStream ts( &file ); + Q3TextStream ts( &file ); ts.setCodec( QTextCodec::codecForName("utf8") ); answer = ts.read(); file.close(); //qDebug("answer \n%s ", answer.latin1()); getNumFromRecord( answer, to ) ; } else { // change existing //qDebug("canging %d %d",to->zaurusStat() ,to->zaurusId() ); //command = "(echo \"" + ePrefix + eString + "\" ) | db2file datebook -w -g -c " + codec+ " > "+ fileName; changeString += eString + "\n"; changeEnt = true; } } to = tl.next(); } status.setText ( i18n("Changing todos ...") ); qApp->processEvents(); //qDebug("changing... "); if ( changeEnt ) { QFile file( fileName ); - if (!file.open( IO_WriteOnly ) ) { + if (!file.open( QIODevice::WriteOnly ) ) { return false; } - QTextStream ts( &file ); + Q3TextStream ts( &file ); ts.setCodec( QTextCodec::codecForName("utf8") ); ts << changeString ; file.close(); command = "db2file todo -w -g -c " + codec+ " < "+ fileName; system ( command.latin1() ); //qDebug("command %s file :\n%s ", command.latin1(), changeString.latin1()); } status.setText ( i18n("Deleting todos ...") ); qApp->processEvents(); //qDebug("deleting... "); if ( deleteEnt ) { QFile file( fileName ); - if (!file.open( IO_WriteOnly ) ) { + if (!file.open( QIODevice::WriteOnly ) ) { return false; } - QTextStream ts( &file ); + Q3TextStream ts( &file ); ts.setCodec( QTextCodec::codecForName("utf8") ); ts << deleteString; file.close(); command = "db2file todo -d -c " + codec+ " < "+ fileName; system ( command.latin1() ); // qDebug("command %s file :\n%s ", command.latin1(), deleteString.latin1()); } return true; } QString SharpFormat::dtToString( const QDateTime& dti, bool useTZ ) { QString datestr; QString timestr; int offset = KGlobal::locale()->localTimeOffset( dti ); QDateTime dt; if (useTZ) dt = dti.addSecs ( -(offset*60)); else dt = dti; if(dt.date().isValid()){ const QDate& date = dt.date(); datestr.sprintf("%04d%02d%02d", date.year(), date.month(), date.day()); } if(dt.time().isValid()){ const QTime& time = dt.time(); timestr.sprintf("T%02d%02d%02d", time.hour(), time.minute(), time.second()); } return datestr + timestr; } QString SharpFormat::getEventString( Event* event ) { QStringList list; list.append( event->getID("Sharp_DTM") ); list.append( event->categories().join(",") ); if ( !event->summary().isEmpty() ) list.append( event->summary() ); else list.append("" ); if ( !event->location().isEmpty() ) list.append( event->location() ); else list.append("" ); if ( !event->description().isEmpty() ) list.append( event->description() ); else list.append( "" ); if ( event->doesFloat () ) { list.append( dtToString( QDateTime(event->dtStart().date(), QTime(0,0,0)), false )); list.append( dtToString( QDateTime(event->dtEnd().date(),QTime(23,59,59)), false )); //6 list.append( "1" ); } else { list.append( dtToString( event->dtStart()) ); list.append( dtToString( event->dtEnd()) ); //6 list.append( "0" ); } bool noAlarm = true; if ( event->alarms().count() > 0 ) { Alarm * al = event->alarms().first(); if ( al->enabled() ) { noAlarm = false; list.append( "0" ); // yes, 0 == alarm list.append( QString::number( al->startOffset().asSeconds()/(-60) ) ); if ( al->type() == Alarm::Audio ) list.append( "1" ); // type audio else list.append( "0" ); // type silent } } if ( noAlarm ) { list.append( "1" ); // yes, 1 == no alarm list.append( "0" ); // no alarm offset list.append( "1" ); // type } // next is: 11 // next is: 11-16 are recurrence Recurrence* rec = event->recurrence(); bool writeEndDate = false; switch ( rec->doesRecur() ) { case Recurrence::rDaily: // 0 list.append( "0" ); list.append( QString::number( rec->frequency() ));//12 list.append( "0" ); list.append( "0" ); writeEndDate = true; break; case Recurrence::rWeekly:// 1 list.append( "1" ); list.append( QString::number( rec->frequency()) );//12 list.append( "0" ); { int days = 0; QBitArray weekDays = rec->days(); int i; for( i = 1; i <= 7; ++i ) { if ( weekDays[i-1] ) { days += 1 << (i-1); } } list.append( QString::number( days ) ); } //pending weekdays writeEndDate = true; break; case Recurrence::rMonthlyPos:// 2 list.append( "2" ); list.append( QString::number( rec->frequency()) );//12 writeEndDate = true; { int count = 1; - QPtrList<Recurrence::rMonthPos> rmp; + Q3PtrList<Recurrence::rMonthPos> rmp; rmp = rec->monthPositions(); if ( rmp.first()->negative ) count = 5 - rmp.first()->rPos - 1; else count = rmp.first()->rPos - 1; list.append( QString::number( count ) ); } list.append( "0" ); break; case Recurrence::rMonthlyDay:// 3 list.append( "3" ); list.append( QString::number( rec->frequency()) );//12 list.append( "0" ); list.append( "0" ); writeEndDate = true; break; case Recurrence::rYearlyMonth://4 list.append( "4" ); list.append( QString::number( rec->frequency()) );//12 list.append( "0" ); list.append( "0" ); writeEndDate = true; break; default: list.append( "255" ); list.append( QString() ); list.append( "0" ); list.append( QString() ); list.append( "0" ); list.append( "20991231T000000" ); break; } if ( writeEndDate ) { if ( rec->endDate().isValid() ) { // 15 + 16 list.append( "1" ); list.append( dtToString( rec->endDate(), false ) ); } else { list.append( "0" ); list.append( "20991231T000000" ); } } if ( event->doesFloat () ) { list.append( dtToString( event->dtStart(), false ).left( 8 )); list.append( dtToString( event->dtEnd(), false ).left( 8 )); //6 } else { list.append( QString() ); list.append( QString() ); } if (event->dtStart().date() == event->dtEnd().date() ) list.append( "0" ); else list.append( "1" ); for(QStringList::Iterator it=list.begin(); it!=list.end(); ++it){ QString& s = (*it); s.replace(QRegExp("\""), "\"\""); if(s.contains(QRegExp("[,\"\r\n]")) || s.stripWhiteSpace() != s){ s.prepend('\"'); s.append('\"'); } else if(s.isEmpty() && !s.isNull()){ s = "\"\""; } } return list.join(","); } QString SharpFormat::getTodoString( Todo* todo ) { QStringList list; list.append( todo->getID("Sharp_DTM") ); list.append( todo->categories().join(",") ); if ( todo->hasStartDate() ) { list.append( dtToString( todo->dtStart()) ); } else list.append( QString() ); if ( todo->hasDueDate() ) { QTime tim; if ( todo->doesFloat()) { list.append( dtToString( QDateTime(todo->dtDue().date(),QTime( 0,0,0 )), false)) ; } else { list.append( dtToString(todo->dtDue() ) ); } } else list.append( QString() ); if ( todo->isCompleted() ) { list.append( dtToString( todo->completed()) ); list.append( "0" ); // yes 0 == completed } else { list.append( dtToString( todo->completed()) ); list.append( "1" ); } list.append( QString::number( todo->priority() )); if( ! todo->summary().isEmpty() ) list.append( todo->summary() ); else list.append( "" ); if (! todo->description().isEmpty() ) list.append( todo->description() ); else list.append( "" ); for(QStringList::Iterator it=list.begin(); it!=list.end(); ++it){ QString& s = (*it); s.replace(QRegExp("\""), "\"\""); if(s.contains(QRegExp("[,\"\r\n]")) || s.stripWhiteSpace() != s){ s.prepend('\"'); s.append('\"'); } else if(s.isEmpty() && !s.isNull()){ s = "\"\""; } } return list.join(","); } QString SharpFormat::getPart( const QString & text, bool &ok, int &start ) { //qDebug("start %d ", start); QString retval =""; if ( text.at(start) == '"' ) { if ( text.mid( start,2) == "\"\"" && !( text.mid( start+2,1) == "\"")) { start = start +2; if ( text.mid( start,1) == "," ) { start += 1; } retval = ""; if ( text.mid( start,1) == "\n" ) { start += 1; ok = false; } return retval; } int hk = start+1; hk = text.find ('"',hk); while ( text.at(hk+1) == '"' ) hk = text.find ('"',hk+2); retval = text.mid( start+1, hk-start-1); start = hk+1; retval.replace( QRegExp("\"\""), "\""); if ( text.mid( start,1) == "," ) { start += 1; } if ( text.mid( start,1) == "\n" ) { start += 1; ok = false; } //qDebug("retval***%s*** ",retval.latin1() ); return retval; } else { int nl = text.find ("\n",start); int kom = text.find (',',start); if ( kom < nl ) { // qDebug("kom < nl %d ", kom); retval = text.mid(start, kom-start); start = kom+1; return retval; } else { if ( nl == kom ) { // qDebug(" nl == kom "); start = 0; ok = false; return "0"; } // qDebug(" nl < kom ", nl); retval = text.mid( start, nl-start); ok = false; start = nl+1; return retval; } } } bool SharpFormat::fromString( Calendar *calendar, const QString & text) { return false; } bool SharpFormat::fromString2Cal( Calendar *calendar,Calendar *existingCalendar, const QString & text, const QString & type) { // qDebug("test %s ", text.latin1()); diff --git a/libkcal/todo.cpp b/libkcal/todo.cpp index cc1c5ae..5a0c32e 100644 --- a/libkcal/todo.cpp +++ b/libkcal/todo.cpp @@ -434,250 +434,250 @@ void Todo::setHasDueDate(bool f) updated(); } #if 0 void Todo::setStatus(const QString &statStr) { if (mReadOnly) return; QString ss(statStr.upper()); if (ss == "X-ACTION") mStatus = NEEDS_ACTION; else if (ss == "NEEDS ACTION") mStatus = NEEDS_ACTION; else if (ss == "ACCEPTED") mStatus = ACCEPTED; else if (ss == "SENT") mStatus = SENT; else if (ss == "TENTATIVE") mStatus = TENTATIVE; else if (ss == "CONFIRMED") mStatus = CONFIRMED; else if (ss == "DECLINED") mStatus = DECLINED; else if (ss == "COMPLETED") mStatus = COMPLETED; else if (ss == "DELEGATED") mStatus = DELEGATED; updated(); } void Todo::setStatus(int status) { if (mReadOnly) return; mStatus = status; updated(); } int Todo::status() const { return mStatus; } QString Todo::statusStr() const { switch(mStatus) { case NEEDS_ACTION: return QString("NEEDS ACTION"); break; case ACCEPTED: return QString("ACCEPTED"); break; case SENT: return QString("SENT"); break; case TENTATIVE: return QString("TENTATIVE"); break; case CONFIRMED: return QString("CONFIRMED"); break; case DECLINED: return QString("DECLINED"); break; case COMPLETED: return QString("COMPLETED"); break; case DELEGATED: return QString("DELEGATED"); break; } return QString(""); } #endif bool Todo::isCompleted() const { if (mPercentComplete == 100) { return true; } else return false; } void Todo::setCompleted(bool completed) { if ( mHasRecurrenceID && completed && mPercentComplete != 100 ) { if ( !setRecurDates() ) completed = false; } if (completed) mPercentComplete = 100; else { mPercentComplete = 0; mHasCompletedDate = false; } updated(); } QDateTime Todo::completed() const { return mCompleted; } QString Todo::completedStr( bool shortF ) const { return KGlobal::locale()->formatDateTime(mCompleted, shortF); } void Todo::setCompleted(const QDateTime &completed) { //qDebug("Todo::setCompleted "); if ( mHasCompletedDate ) { // qDebug("has completed data - return "); return; } mHasCompletedDate = true; mPercentComplete = 100; mCompleted = getEvenTime(completed); updated(); } bool Todo::hasCompletedDate() const { return mHasCompletedDate; } int Todo::percentComplete() const { return mPercentComplete; } bool Todo::setRecurDates() { if ( !mHasRecurrenceID ) return true; int secs = mDtStart.secsTo( dtDue() ); bool ok; qDebug("T:setRecurDates() "); //qDebug("%s %s %s ",mDtStart.toString().latin1(), dtDue().toString().latin1(),mRecurrenceID.toString().latin1() ); QDateTime next = getNextOccurence( mRecurrenceID, &ok ); if ( ok ) { mRecurrenceID = next; mDtStart = next; setDtDue( next.addSecs( secs ) ); if ( QDateTime::currentDateTime() > next) return false; } else { setHasRecurrenceID( false ); recurrence()->unsetRecurs(); } return true; } void Todo::setPercentComplete(int v) { if ( mHasRecurrenceID && v == 100 && mPercentComplete != 100 ) { if ( !setRecurDates() ) v = 0; } mPercentComplete = v; if ( v != 100 ) mHasCompletedDate = false; updated(); } QDateTime Todo::getNextAlarmDateTime( bool * ok, int * offset, QDateTime start_dt ) const { *ok = false; if ( ! hasDueDate() || cancelled() || !alarmEnabled() ) { return QDateTime (); } // if the recurring todo is set to complete and requested time < start time of todo // we want to get the alarm. bool iscompleted = isCompleted(); if ( iscompleted && doesRecur() ) { Todo * to = (Todo*) this; to->checkSetCompletedFalse(); iscompleted = isCompleted(); if ( hasStartDate() && start_dt < dtStart() ){ iscompleted = false; } } if ( iscompleted ) { return QDateTime (); } QDateTime incidenceStart; incidenceStart = dtDue(); bool enabled = false; Alarm* alarm; int off = 0; QDateTime alarmStart = QDateTime::currentDateTime().addDays( 3650 );; // if ( QDateTime::currentDateTime() > incidenceStart ){ // *ok = false; // return incidenceStart; // } - for (QPtrListIterator<Alarm> it(mAlarms); (alarm = it.current()) != 0; ++it) { + for (Q3PtrListIterator<Alarm> it(mAlarms); (alarm = it.current()) != 0; ++it) { if (alarm->enabled()) { if ( alarm->hasTime () ) { if ( alarm->time() < alarmStart ) { alarmStart = alarm->time(); enabled = true; off = alarmStart.secsTo( incidenceStart ); } } else { int secs = alarm->startOffset().asSeconds(); if ( incidenceStart.addSecs( secs ) < alarmStart ) { alarmStart = incidenceStart.addSecs( secs ); enabled = true; off = -secs; } } } } if ( enabled ) { if ( alarmStart > start_dt ) { *ok = true; * offset = off; return alarmStart; } } *ok = false; return QDateTime (); } void Todo::checkSetCompletedFalse() { if ( !mHasRecurrenceID ) { qDebug("ERROR 1 in Todo::checkSetCompletedFalse"); return; } // qDebug("Todo::checkSetCompletedFalse()"); //qDebug("%s %s %s ",mDtStart.toString().latin1(), dtDue().toString().latin1(),mRecurrenceID.toString().latin1() ); if ( mPercentComplete == 100 ) { QDateTime dt = QDateTime::currentDateTime(); if ( dt > mDtStart && dt > mRecurrenceID ) { qDebug("start: %s --due: %s --recID: %s ",mDtStart.toString().latin1(), dtDue().toString().latin1(),mRecurrenceID.toString().latin1() ); setCompleted( false ); qDebug("Todo::checkSetCompletedFalse "); } } } QString Todo::durationText() { if ( mHasDueDate && hasStartDate() ) { int sec = dtStart().secsTo( dtDue() ); if ( doesFloat() ) sec += 86400; return durationText4Time( sec ); } return "---"; } diff --git a/libkcal/todo.h b/libkcal/todo.h index 2131732..cea976c 100644 --- a/libkcal/todo.h +++ b/libkcal/todo.h @@ -1,162 +1,164 @@ /* This file is part of libkcal. Copyright (c) 2001 Cornelius Schumacher <schumacher@kde.org> 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #ifndef TODO_H #define TODO_H // // Todo component, representing a VTODO object // #include "incidence.h" #include <qtimer.h> +//Added by qt3to4: +#include <Q3CString> namespace KCal { /** This class provides a Todo in the sense of RFC2445. */ class Todo : public QObject,public Incidence { Q_OBJECT public: Todo(); Todo(const Todo &); ~Todo(); typedef ListBase<Todo> List; - QCString type() const { return "Todo"; } + Q3CString type() const { return "Todo"; } IncTypeID typeID() const { return todoID; } /** Return an exact copy of this todo. */ Incidence *clone(); QDateTime getNextAlarmDateTime( bool * ok, int * offset, QDateTime start_dt ) const; /** for setting the todo's due date/time with a QDateTime. */ void setDtDue(const QDateTime &dtDue); /** returns an event's Due date/time as a QDateTime. */ QDateTime dtDue() const; /** returns an event's due time as a string formatted according to the users locale settings */ QString dtDueTimeStr() const; /** returns an event's due date as a string formatted according to the users locale settings */ QString dtDueDateStr(bool shortfmt=true) const; /** returns an event's due date and time as a string formatted according to the users locale settings */ QString dtDueStr(bool shortfmt=true) const; /** returns TRUE or FALSE depending on whether the todo has a due date */ bool hasDueDate() const; /** sets the event's hasDueDate value. */ void setHasDueDate(bool f); /* Looks for a subtodo (including itself ) which is not complete and is - overdue, or - due today. It returns 0 for nothing found, 1 for found a todo which is due today and no overdue found 2 for found a overdue todo */ int hasDueSubTodo( bool checkSubtodos = true ); /* same as above, but a specific date can be specified*/ int hasDueSubTodoForDate( const QDate & date, bool checkSubtodos ); /** sets the event's status to the string specified. The string * must be a recognized value for the status field, i.e. a string * equivalent of the possible status enumerations previously described. */ // void setStatus(const QString &statStr); /** sets the event's status to the value specified. See the enumeration * above for possible values. */ // void setStatus(int); /** return the event's status. */ // int status() const; /** return the event's status in string format. */ // QString statusStr() const; /** return, if this todo is completed */ bool isCompleted() const; /** set completed state of this todo */ void setCompleted(bool); /** Return how many percent of the task are completed. Returns a value between 0 and 100. */ int percentComplete() const; /** Set how many percent of the task are completed. Valid values are in the range from 0 to 100. */ void setPercentComplete(int); /** return date and time when todo was completed */ QDateTime completed() const; QString completedStr(bool shortF = true) const; /** set date and time of completion */ void setCompleted(const QDateTime &completed); /** Return true, if todo has a date associated with completion */ bool hasCompletedDate() const; bool contains ( Todo*); void checkSetCompletedFalse(); bool setRecurDates(); bool isRunning() {return mRunning;} bool hasRunningSub(); void setRunning( bool ); void setRunningFalse( QString ); void stopRunning(); int runTime(); QDateTime runStart () const { return mRunStart;} void saveRunningInfo( QString comment, QDateTime start, QDateTime end ); public slots: void saveRunningInfoToFile( QString st ); void saveRunningInfoToFile( ); void saveParents(); QString durationText(); private slots: void timerSlotSaveRunningInfoToFile( ); private: QString mLastSavedFileName; void restartSaveTimer( int secs ); int mCurrentTimerDelay; bool mRunning; QTimer * mRunSaveTimer; QDateTime mRunStart; QDateTime mRunLastSave; QDateTime mRunEnd; bool accept(Visitor &v) { return v.visit(this); } QDateTime mDtDue; // due date of todo bool mHasDueDate; // if todo has associated due date // int mStatus; // confirmed/delegated/tentative/etc QDateTime mCompleted; bool mHasCompletedDate; int mPercentComplete; }; bool operator==( const Todo&, const Todo& ); } #endif diff --git a/libkcal/vcaldrag.cpp b/libkcal/vcaldrag.cpp index f01f332..324981e 100644 --- a/libkcal/vcaldrag.cpp +++ b/libkcal/vcaldrag.cpp @@ -1,54 +1,54 @@ /* This file is part of libkcal. Copyright (c) 1998 Preston Brown Copyright (c) 2001 Cornelius Schumacher <schumacher@kde.org> 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #include "vcaldrag.h" #include "vcalformat.h" using namespace KCal; VCalDrag::VCalDrag( Calendar *cal, QWidget *parent, const char *name ) - : QStoredDrag( "text/x-vCalendar", parent, name ) + : Q3StoredDrag( "text/x-vCalendar", parent, name ) { VCalFormat format; setEncodedData( format.toString( cal ).utf8() ); } bool VCalDrag::canDecode( QMimeSource *me ) { return me->provides( "text/x-vCalendar" ); } bool VCalDrag::decode( QMimeSource *de, Calendar *cal ) { bool success = false; QByteArray payload = de->encodedData( "text/x-vCalendar" ); if ( payload.size() ) { QString txt = QString::fromUtf8( payload.data() ); VCalFormat format; success = format.fromString( cal, txt ); } return success; } diff --git a/libkcal/vcaldrag.h b/libkcal/vcaldrag.h index 3048124..68a320d 100644 --- a/libkcal/vcaldrag.h +++ b/libkcal/vcaldrag.h @@ -1,47 +1,47 @@ /* This file is part of libkcal. Copyright (c) 1998 Preston Brown Copyright (c) 2001 Cornelius Schumacher <schumacher@kde.org> 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #ifndef VCALDRAG_H #define VCALDRAG_H -#include <qdragobject.h> +#include <q3dragobject.h> namespace KCal { class Calendar; /** vCalendar drag&drop class. */ -class VCalDrag : public QStoredDrag { +class VCalDrag : public Q3StoredDrag { public: /** Create a drag&drop object for vCalendar component \a vcal. */ VCalDrag( Calendar *vcal, QWidget *parent = 0, const char *name = 0 ); ~VCalDrag() {}; /** Return, if drag&drop object can be decode to vCalendar. */ static bool canDecode( QMimeSource * ); /** Decode drag&drop object to vCalendar component \a vcal. */ static bool decode( QMimeSource *e, Calendar *cal ); }; } #endif diff --git a/libkcal/vcalformat.cpp b/libkcal/vcalformat.cpp index 2e19740..9cbaf16 100644 --- a/libkcal/vcalformat.cpp +++ b/libkcal/vcalformat.cpp @@ -1,867 +1,869 @@ /* This file is part of libkcal. Copyright (c) 1998 Preston Brwon Copyright (c) 2001 Cornelius Schumacher <schumacher@kde.org> 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #include <qapplication.h> #include <qdatetime.h> #include <qstring.h> -#include <qptrlist.h> +#include <q3ptrlist.h> #include <qregexp.h> #include <qclipboard.h> #include <qdialog.h> #include <qfile.h> +//Added by qt3to4: +#include <Q3CString> #include <kdebug.h> #include <kglobal.h> #include <kmessagebox.h> #include <kiconloader.h> #include <klocale.h> #include "vcc.h" #include "vobject.h" #include "vcaldrag.h" #include "calendar.h" #include "vcalformat.h" using namespace KCal; VCalFormat::VCalFormat() { mCalendar = 0; useLocalTime = false; } VCalFormat::~VCalFormat() { } void VCalFormat::setLocalTime ( bool b ) { useLocalTime = b; } bool VCalFormat::load(Calendar *calendar, const QString &fileName) { mCalendar = calendar; clearException(); if ( ! useLocalTime ) useLocalTime = mCalendar->isLocalTime(); VObject *vcal = 0; // this is not necessarily only 1 vcal. Could be many vcals, or include // a vcard... vcal = Parse_MIME_FromFileName(const_cast<char *>(QFile::encodeName(fileName).data())); if (!vcal) { setException(new ErrorFormat(ErrorFormat::CalVersionUnknown)); return FALSE; } // any other top-level calendar stuff should be added/initialized here // put all vobjects into their proper places populate(vcal); // clean up from vcal API stuff cleanVObjects(vcal); cleanStrTbl(); return true; } bool VCalFormat::save(Calendar *calendar, const QString &fileName) { mCalendar = calendar; if ( ! useLocalTime ) useLocalTime = mCalendar->isLocalTime(); QString tmpStr; VObject *vcal, *vo; vcal = newVObject(VCCalProp); // addPropValue(vcal,VCLocationProp, "0.0"); addPropValue(vcal,VCProdIdProp, productId()); tmpStr = mCalendar->getTimeZoneStr(); //qDebug("mCalendar->getTimeZoneStr() %s",tmpStr.latin1() ); addPropValue(vcal,VCTimeZoneProp, tmpStr.local8Bit()); addPropValue(vcal,VCVersionProp, _VCAL_VERSION); // TODO STUFF - QPtrList<Todo> todoList = mCalendar->rawTodos(); - QPtrListIterator<Todo> qlt(todoList); + Q3PtrList<Todo> todoList = mCalendar->rawTodos(); + Q3PtrListIterator<Todo> qlt(todoList); for (; qlt.current(); ++qlt) { vo = eventToVTodo(qlt.current()); addVObjectProp(vcal, vo); } // EVENT STUFF - QPtrList<Event> events = mCalendar->rawEvents(); + Q3PtrList<Event> events = mCalendar->rawEvents(); Event *ev; for(ev=events.first();ev;ev=events.next()) { vo = eventToVEvent(ev); addVObjectProp(vcal, vo); } writeVObjectToFile(QFile::encodeName(fileName).data() ,vcal); cleanVObjects(vcal); cleanStrTbl(); if (QFile::exists(fileName)) { return true; } else { return false; // error } } bool VCalFormat::fromString( Calendar *calendar, const QString &text ) { // TODO: Factor out VCalFormat::fromString() - QCString data = text.utf8(); + Q3CString data = text.utf8(); if ( !data.size() ) return false; VObject *vcal = Parse_MIME( data.data(), data.size()); if ( !vcal ) return false; VObjectIterator i; VObject *curvo; initPropIterator( &i, vcal ); // we only take the first object. TODO: parse all incidences. do { curvo = nextVObject( &i ); } while ( strcmp( vObjectName( curvo ), VCEventProp ) && strcmp( vObjectName( curvo ), VCTodoProp ) ); if ( strcmp( vObjectName( curvo ), VCEventProp ) == 0 ) { Event *event = VEventToEvent( curvo ); calendar->addEvent( event ); } else { qDebug("VCalFormat::fromString(): Unknown object type. "); deleteVObject( vcal ); return false; } deleteVObject( vcal ); return true; } QString VCalFormat::eventToString( Event * event, Calendar *calendar, bool useLocal) { if ( !event ) return QString::null; bool useL = useLocalTime; useLocalTime = useLocal; mCalendar = calendar; VObject *vevent = eventToVEvent( event ); char *buf = writeMemVObject( 0, 0, vevent ); QString result( buf ); cleanVObject( vevent ); useLocalTime = useL; return result; } QString VCalFormat::todoToString( Todo * todo, Calendar *calendar, bool useLocal ) { if ( !todo ) return QString::null; bool useL = useLocalTime; useLocalTime = useLocal; mCalendar = calendar; VObject *vevent = eventToVTodo( todo ); char *buf = writeMemVObject( 0, 0, vevent ); QString result( buf ); cleanVObject( vevent ); useLocalTime = useL; return result; } QString VCalFormat::toString( Calendar *calendar ) { // TODO: Factor out VCalFormat::asString() VObject *vcal = newVObject(VCCalProp); addPropValue( vcal, VCProdIdProp, CalFormat::productId() ); QString tmpStr = mCalendar->getTimeZoneStr(); addPropValue( vcal, VCTimeZoneProp, tmpStr.local8Bit() ); addPropValue( vcal, VCVersionProp, _VCAL_VERSION ); // TODO: Use all data. - QPtrList<Event> events = calendar->events(); + Q3PtrList<Event> events = calendar->events(); Event *event = events.first(); if ( !event ) return QString::null; VObject *vevent = eventToVEvent( event ); addVObjectProp( vcal, vevent ); char *buf = writeMemVObject( 0, 0, vcal ); QString result( buf ); cleanVObject( vcal ); return result; } VObject *VCalFormat::eventToVTodo(const Todo *anEvent) { VObject *vtodo; QString tmpStr; vtodo = newVObject(VCTodoProp); // due date if (anEvent->hasDueDate()) { tmpStr = qDateTimeToISO(anEvent->dtDue(), !anEvent->doesFloat()); addPropValue(vtodo, VCDueProp, tmpStr.local8Bit()); } // start date if (anEvent->hasStartDate()) { tmpStr = qDateTimeToISO(anEvent->dtStart(), !anEvent->doesFloat()); addPropValue(vtodo, VCDTstartProp, tmpStr.local8Bit()); } // creation date tmpStr = qDateTimeToISO(anEvent->created()); addPropValue(vtodo, VCDCreatedProp, tmpStr.local8Bit()); // unique id addPropValue(vtodo, VCUniqueStringProp, anEvent->uid().local8Bit()); // revision tmpStr.sprintf("%i", anEvent->revision()); addPropValue(vtodo, VCSequenceProp, tmpStr.local8Bit()); // last modification date tmpStr = qDateTimeToISO(anEvent->lastModified()); addPropValue(vtodo, VCLastModifiedProp, tmpStr.local8Bit()); // organizer stuff tmpStr = "MAILTO:" + anEvent->organizer(); addPropValue(vtodo, ICOrganizerProp, tmpStr.local8Bit()); // attendees if (anEvent->attendeeCount() != 0) { - QPtrList<Attendee> al = anEvent->attendees(); - QPtrListIterator<Attendee> ai(al); + Q3PtrList<Attendee> al = anEvent->attendees(); + Q3PtrListIterator<Attendee> ai(al); Attendee *curAttendee; for (; ai.current(); ++ai) { curAttendee = ai.current(); if (!curAttendee->email().isEmpty() && !curAttendee->name().isEmpty()) tmpStr = "MAILTO:" + curAttendee->name() + " <" + curAttendee->email() + ">"; else if (curAttendee->name().isEmpty()) tmpStr = "MAILTO: " + curAttendee->email(); else if (curAttendee->email().isEmpty()) tmpStr = "MAILTO: " + curAttendee->name(); else if (curAttendee->name().isEmpty() && curAttendee->email().isEmpty()) kdDebug(5800) << "warning! this Event has an attendee w/o name or email!" << endl; VObject *aProp = addPropValue(vtodo, VCAttendeeProp, tmpStr.local8Bit()); addPropValue(aProp, VCRoleProp, writeRole(curAttendee->role())); addPropValue(aProp, VCRSVPProp, curAttendee->RSVP() ? "TRUE" : "FALSE"); addPropValue(aProp, VCStatusProp, writeStatus(curAttendee->status())); } } // description BL: if (!anEvent->description().isEmpty()) { VObject *d = addPropValue(vtodo, VCDescriptionProp, anEvent->description().local8Bit()); if (anEvent->description().find('\n') != -1) addProp(d, VCQuotedPrintableProp); } // summary if (!anEvent->summary().isEmpty()) addPropValue(vtodo, VCSummaryProp, anEvent->summary().local8Bit()); if (!anEvent->location().isEmpty()) addPropValue(vtodo, VCLocationProp, anEvent->location().local8Bit()); // completed // status // backward compatibility, KOrganizer used to interpret only these two values addPropValue(vtodo, VCStatusProp, anEvent->isCompleted() ? "COMPLETED" : "NEEDS_ACTION"); // completion date if (anEvent->hasCompletedDate()) { tmpStr = qDateTimeToISO(anEvent->completed()); addPropValue(vtodo, VCCompletedProp, tmpStr.local8Bit()); } // priority tmpStr.sprintf("%i",anEvent->priority()); addPropValue(vtodo, VCPriorityProp, tmpStr.local8Bit()); // related event - if (anEvent->relatedToUid()) { + if (!anEvent->relatedToUid().isEmpty()) { addPropValue(vtodo, VCRelatedToProp, anEvent->relatedToUid().local8Bit()); } // categories QStringList tmpStrList = anEvent->categories(); tmpStr = ""; QString catStr; for ( QStringList::Iterator it = tmpStrList.begin(); it != tmpStrList.end(); ++it ) { catStr = *it; if (catStr[0] == ' ') tmpStr += catStr.mid(1); else tmpStr += catStr; // this must be a ';' character as the vCalendar specification requires! // vcc.y has been hacked to translate the ';' to a ',' when the vcal is // read in. tmpStr += ";"; } if (!tmpStr.isEmpty()) { tmpStr.truncate(tmpStr.length()-1); addPropValue(vtodo, VCCategoriesProp, tmpStr.local8Bit()); } // alarm stuff kdDebug(5800) << "vcalformat::eventToVTodo was called" << endl; - QPtrList<Alarm> alarms = anEvent->alarms(); + Q3PtrList<Alarm> alarms = anEvent->alarms(); Alarm* alarm; for (alarm = alarms.first(); alarm; alarm = alarms.next()) { if (alarm->enabled()) { VObject *a; tmpStr = qDateTimeToISO(alarm->time()); if (alarm->type() == Alarm::Audio) { a = addProp(vtodo, VCAAlarmProp); addPropValue(a, VCRunTimeProp, tmpStr.local8Bit()); addPropValue(a, VCRepeatCountProp, "1"); addPropValue(a, VCAudioContentProp, QFile::encodeName(alarm->audioFile())); } else if (alarm->type() == Alarm::Procedure) { a = addProp(vtodo, VCPAlarmProp); addPropValue(a, VCRunTimeProp, tmpStr.local8Bit()); addPropValue(a, VCRepeatCountProp, "1"); addPropValue(a, VCProcedureNameProp, QFile::encodeName(alarm->programFile())); } else { a = addProp(vtodo, VCDAlarmProp); addPropValue(a, VCRunTimeProp, tmpStr.local8Bit()); addPropValue(a, VCRepeatCountProp, "1"); addPropValue(a, VCDisplayStringProp, "beep!"); } } } if (anEvent->pilotId()) { // pilot sync stuff tmpStr.sprintf("%i",anEvent->pilotId()); addPropValue(vtodo, XPilotIdProp, tmpStr.local8Bit()); tmpStr.sprintf("%i",anEvent->syncStatus()); addPropValue(vtodo, XPilotStatusProp, tmpStr.local8Bit()); } return vtodo; } VObject* VCalFormat::eventToVEvent(Event *anEvent) { VObject *vevent; QString tmpStr; vevent = newVObject(VCEventProp); // start and end time tmpStr = qDateTimeToISO(anEvent->dtStart(), !anEvent->doesFloat()); addPropValue(vevent, VCDTstartProp, tmpStr.local8Bit()); // events that have time associated but take up no time should // not have both DTSTART and DTEND. if (anEvent->dtStart() != anEvent->dtEnd()) { tmpStr = qDateTimeToISO(anEvent->dtEnd(), !anEvent->doesFloat()); addPropValue(vevent, VCDTendProp, tmpStr.local8Bit()); } // creation date tmpStr = qDateTimeToISO(anEvent->created()); addPropValue(vevent, VCDCreatedProp, tmpStr.local8Bit()); // unique id addPropValue(vevent, VCUniqueStringProp, anEvent->uid().local8Bit()); // revision tmpStr.sprintf("%i", anEvent->revision()); addPropValue(vevent, VCSequenceProp, tmpStr.local8Bit()); // last modification date tmpStr = qDateTimeToISO(anEvent->lastModified()); addPropValue(vevent, VCLastModifiedProp, tmpStr.local8Bit()); // attendee and organizer stuff tmpStr = "MAILTO:" + anEvent->organizer(); addPropValue(vevent, ICOrganizerProp, tmpStr.local8Bit()); if (anEvent->attendeeCount() != 0) { - QPtrList<Attendee> al = anEvent->attendees(); - QPtrListIterator<Attendee> ai(al); + Q3PtrList<Attendee> al = anEvent->attendees(); + Q3PtrListIterator<Attendee> ai(al); Attendee *curAttendee; // TODO: Put this functionality into Attendee class for (; ai.current(); ++ai) { curAttendee = ai.current(); if (!curAttendee->email().isEmpty() && !curAttendee->name().isEmpty()) tmpStr = "MAILTO:" + curAttendee->name() + " <" + curAttendee->email() + ">"; else if (curAttendee->name().isEmpty()) tmpStr = "MAILTO: " + curAttendee->email(); else if (curAttendee->email().isEmpty()) tmpStr = "MAILTO: " + curAttendee->name(); else if (curAttendee->name().isEmpty() && curAttendee->email().isEmpty()) kdDebug(5800) << "warning! this Event has an attendee w/o name or email!" << endl; VObject *aProp = addPropValue(vevent, VCAttendeeProp, tmpStr.local8Bit()); addPropValue(aProp, VCRoleProp, writeRole(curAttendee->role())); addPropValue(aProp, VCRSVPProp, curAttendee->RSVP() ? "TRUE" : "FALSE"); addPropValue(aProp, VCStatusProp, writeStatus(curAttendee->status())); } } // recurrence rule stuff if (anEvent->doesRecur()) { // some more variables - QPtrList<Recurrence::rMonthPos> tmpPositions; - QPtrList<int> tmpDays; + Q3PtrList<Recurrence::rMonthPos> tmpPositions; + Q3PtrList<int> tmpDays; int *tmpDay; Recurrence::rMonthPos *tmpPos; QString tmpStr2; int i; switch(anEvent->recurrence()->doesRecur()) { case Recurrence::rDaily: tmpStr.sprintf("D%i ",anEvent->recurrence()->frequency()); // if (anEvent->rDuration > 0) // tmpStr += "#"; break; case Recurrence::rWeekly: tmpStr.sprintf("W%i ",anEvent->recurrence()->frequency()); for (i = 0; i < 7; i++) { if (anEvent->recurrence()->days().testBit(i)) tmpStr += dayFromNum(i); } break; case Recurrence::rMonthlyPos: tmpStr.sprintf("MP%i ", anEvent->recurrence()->frequency()); // write out all rMonthPos's tmpPositions = anEvent->recurrence()->monthPositions(); for (tmpPos = tmpPositions.first(); tmpPos; tmpPos = tmpPositions.next()) { tmpStr2.sprintf("%i", tmpPos->rPos); if (tmpPos->negative) tmpStr2 += "- "; else tmpStr2 += "+ "; tmpStr += tmpStr2; for (i = 0; i < 7; i++) { if (tmpPos->rDays.testBit(i)) tmpStr += dayFromNum(i); } } // loop for all rMonthPos's break; case Recurrence::rMonthlyDay: tmpStr.sprintf("MD%i ", anEvent->recurrence()->frequency()); // write out all rMonthDays; tmpDays = anEvent->recurrence()->monthDays(); for (tmpDay = tmpDays.first(); tmpDay; tmpDay = tmpDays.next()) { tmpStr2.sprintf("%i ", *tmpDay); tmpStr += tmpStr2; } break; case Recurrence::rYearlyMonth: tmpStr.sprintf("YM%i ", anEvent->recurrence()->frequency()); // write out all the rYearNums; tmpDays = anEvent->recurrence()->yearNums(); for (tmpDay = tmpDays.first(); tmpDay; tmpDay = tmpDays.next()) { tmpStr2.sprintf("%i ", *tmpDay); tmpStr += tmpStr2; } break; case Recurrence::rYearlyDay: tmpStr.sprintf("YD%i ", anEvent->recurrence()->frequency()); // write out all the rYearNums; tmpDays = anEvent->recurrence()->yearNums(); for (tmpDay = tmpDays.first(); tmpDay; tmpDay = tmpDays.next()) { tmpStr2.sprintf("%i ", *tmpDay); tmpStr += tmpStr2; } break; default: kdDebug(5800) << "ERROR, it should never get here in eventToVEvent!" << endl; break; } // switch if (anEvent->recurrence()->duration() > 0) { tmpStr2.sprintf("#%i",anEvent->recurrence()->duration()); tmpStr += tmpStr2; } else if (anEvent->recurrence()->duration() == -1) { tmpStr += "#0"; // defined as repeat forever } else { - tmpStr += qDateTimeToISO(anEvent->recurrence()->endDate(), FALSE); + tmpStr += qDateTimeToISO((QDateTime)anEvent->recurrence()->endDate(), FALSE); } addPropValue(vevent,VCRRuleProp, tmpStr.local8Bit()); } // event repeats // exceptions to recurrence DateList dateList = anEvent->exDates(); DateList::ConstIterator it; QString tmpStr2; for (it = dateList.begin(); it != dateList.end(); ++it) { tmpStr = qDateToISO(*it) + ";"; tmpStr2 += tmpStr; } if (!tmpStr2.isEmpty()) { tmpStr2.truncate(tmpStr2.length()-1); addPropValue(vevent, VCExpDateProp, tmpStr2.local8Bit()); } // description if (!anEvent->description().isEmpty()) { VObject *d = addPropValue(vevent, VCDescriptionProp, anEvent->description().local8Bit()); if (anEvent->description().find('\n') != -1) addProp(d, VCQuotedPrintableProp); } // summary if (!anEvent->summary().isEmpty()) addPropValue(vevent, VCSummaryProp, anEvent->summary().local8Bit()); if (!anEvent->location().isEmpty()) addPropValue(vevent, VCLocationProp, anEvent->location().local8Bit()); // status // TODO: define Event status // addPropValue(vevent, VCStatusProp, anEvent->statusStr().local8Bit()); // secrecy const char *text = 0; switch (anEvent->secrecy()) { case Incidence::SecrecyPublic: text = "PUBLIC"; break; case Incidence::SecrecyPrivate: text = "PRIVATE"; break; case Incidence::SecrecyConfidential: text = "CONFIDENTIAL"; break; } if (text) { addPropValue(vevent, VCClassProp, text); } // categories QStringList tmpStrList = anEvent->categories(); tmpStr = ""; QString catStr; for ( QStringList::Iterator it = tmpStrList.begin(); it != tmpStrList.end(); ++it ) { catStr = *it; if (catStr[0] == ' ') tmpStr += catStr.mid(1); else tmpStr += catStr; // this must be a ';' character as the vCalendar specification requires! // vcc.y has been hacked to translate the ';' to a ',' when the vcal is // read in. tmpStr += ";"; } if (!tmpStr.isEmpty()) { tmpStr.truncate(tmpStr.length()-1); addPropValue(vevent, VCCategoriesProp, tmpStr.local8Bit()); } // attachments // TODO: handle binary attachments! - QPtrList<Attachment> attachments = anEvent->attachments(); + Q3PtrList<Attachment> attachments = anEvent->attachments(); for ( Attachment *at = attachments.first(); at; at = attachments.next() ) addPropValue(vevent, VCAttachProp, at->uri().local8Bit()); // resources tmpStrList = anEvent->resources(); tmpStr = tmpStrList.join(";"); if (!tmpStr.isEmpty()) addPropValue(vevent, VCResourcesProp, tmpStr.local8Bit()); // alarm stuff - QPtrList<Alarm> alarms = anEvent->alarms(); + Q3PtrList<Alarm> alarms = anEvent->alarms(); Alarm* alarm; for (alarm = alarms.first(); alarm; alarm = alarms.next()) { if (alarm->enabled()) { VObject *a ; tmpStr = qDateTimeToISO(alarm->time()); if (alarm->type() == Alarm::Audio) { a = addProp(vevent, VCAAlarmProp); addPropValue(a, VCRunTimeProp, tmpStr.local8Bit()); addPropValue(a, VCRepeatCountProp, "1"); addPropValue(a, VCAudioContentProp, QFile::encodeName(alarm->audioFile())); } if (alarm->type() == Alarm::Procedure) { a = addProp(vevent, VCPAlarmProp); addPropValue(a, VCRunTimeProp, tmpStr.local8Bit()); addPropValue(a, VCRepeatCountProp, "1"); addPropValue(a, VCProcedureNameProp, QFile::encodeName(alarm->programFile())); } else { a = addProp(vevent, VCDAlarmProp); addPropValue(a, VCRunTimeProp, tmpStr.local8Bit()); addPropValue(a, VCRepeatCountProp, "1"); addPropValue(a, VCDisplayStringProp, "beep!"); } } } // priority tmpStr.sprintf("%i",anEvent->priority()); addPropValue(vevent, VCPriorityProp, tmpStr.local8Bit()); // transparency tmpStr.sprintf("%i",anEvent->transparency()); addPropValue(vevent, VCTranspProp, tmpStr.local8Bit()); // related event - if (anEvent->relatedToUid()) { + if (!anEvent->relatedToUid().isEmpty()) { addPropValue(vevent, VCRelatedToProp, anEvent->relatedToUid().local8Bit()); } if (anEvent->pilotId()) { // pilot sync stuff tmpStr.sprintf("%i",anEvent->pilotId()); addPropValue(vevent, XPilotIdProp, tmpStr.local8Bit()); tmpStr.sprintf("%i",anEvent->syncStatus()); addPropValue(vevent, XPilotStatusProp, tmpStr.local8Bit()); } return vevent; } Todo *VCalFormat::VTodoToEvent(VObject *vtodo) { VObject *vo; VObjectIterator voi; char *s; Todo *anEvent = new Todo; // creation date if ((vo = isAPropertyOf(vtodo, VCDCreatedProp)) != 0) { anEvent->setCreated(ISOToQDateTime(s = fakeCString(vObjectUStringZValue(vo)))); deleteStr(s); } // unique id vo = isAPropertyOf(vtodo, VCUniqueStringProp); // while the UID property is preferred, it is not required. We'll use the // default Event UID if none is given. if (vo) { anEvent->setUid(s = fakeCString(vObjectUStringZValue(vo))); deleteStr(s); } // last modification date if ((vo = isAPropertyOf(vtodo, VCLastModifiedProp)) != 0) { anEvent->setLastModified(ISOToQDateTime(s = fakeCString(vObjectUStringZValue(vo)))); deleteStr(s); } else anEvent->setLastModified(QDateTime(QDate::currentDate(), QTime::currentTime())); // organizer // if our extension property for the event's ORGANIZER exists, add it. if ((vo = isAPropertyOf(vtodo, ICOrganizerProp)) != 0) { anEvent->setOrganizer(s = fakeCString(vObjectUStringZValue(vo))); deleteStr(s); } else { anEvent->setOrganizer(mCalendar->getEmail()); } // attendees. initPropIterator(&voi, vtodo); while (moreIteration(&voi)) { vo = nextVObject(&voi); if (strcmp(vObjectName(vo), VCAttendeeProp) == 0) { Attendee *a; VObject *vp; s = fakeCString(vObjectUStringZValue(vo)); QString tmpStr = QString::fromLocal8Bit(s); deleteStr(s); tmpStr = tmpStr.simplifyWhiteSpace(); int emailPos1, emailPos2; if ((emailPos1 = tmpStr.find('<')) > 0) { // both email address and name emailPos2 = tmpStr.findRev('>'); a = new Attendee(tmpStr.left(emailPos1 - 1), tmpStr.mid(emailPos1 + 1, emailPos2 - (emailPos1 + 1))); } else if (tmpStr.find('@') > 0) { // just an email address a = new Attendee(0, tmpStr); } else { // just a name // QString email = tmpStr.replace( QRegExp(" "), "." ); a = new Attendee(tmpStr,0); } // is there a Role property? if ((vp = isAPropertyOf(vo, VCRoleProp)) != 0) a->setRole(readRole(vObjectStringZValue(vp))); // is there an RSVP property? if ((vp = isAPropertyOf(vo, VCRSVPProp)) != 0) a->setRSVP(vObjectStringZValue(vp)); // is there a status property? if ((vp = isAPropertyOf(vo, VCStatusProp)) != 0) a->setStatus(readStatus(vObjectStringZValue(vp))); // add the attendee anEvent->addAttendee(a); } } // description for todo if ((vo = isAPropertyOf(vtodo, VCDescriptionProp)) != 0) { s = fakeCString(vObjectUStringZValue(vo)); anEvent->setDescription(QString::fromLocal8Bit(s)); deleteStr(s); } // summary if ((vo = isAPropertyOf(vtodo, VCSummaryProp))) { s = fakeCString(vObjectUStringZValue(vo)); anEvent->setSummary(QString::fromLocal8Bit(s)); deleteStr(s); } if ((vo = isAPropertyOf(vtodo, VCLocationProp))) { s = fakeCString(vObjectUStringZValue(vo)); anEvent->setLocation(QString::fromLocal8Bit(s)); deleteStr(s); } // completed // was: status if ((vo = isAPropertyOf(vtodo, VCStatusProp)) != 0) { s = fakeCString(vObjectUStringZValue(vo)); if (strcmp(s,"COMPLETED") == 0) { anEvent->setCompleted(true); } else { anEvent->setCompleted(false); } deleteStr(s); } else anEvent->setCompleted(false); // completion date if ((vo = isAPropertyOf(vtodo, VCCompletedProp)) != 0) { anEvent->setCompleted(ISOToQDateTime(s = fakeCString(vObjectUStringZValue(vo)))); deleteStr(s); } // priority if ((vo = isAPropertyOf(vtodo, VCPriorityProp))) { anEvent->setPriority(atoi(s = fakeCString(vObjectUStringZValue(vo)))); deleteStr(s); } // due date if ((vo = isAPropertyOf(vtodo, VCDueProp)) != 0) { anEvent->setDtDue(ISOToQDateTime(s = fakeCString(vObjectUStringZValue(vo)))); deleteStr(s); anEvent->setHasDueDate(true); } else { anEvent->setHasDueDate(false); } // start time if ((vo = isAPropertyOf(vtodo, VCDTstartProp)) != 0) { anEvent->setDtStart(ISOToQDateTime(s = fakeCString(vObjectUStringZValue(vo)))); // kdDebug(5800) << "s is " << // s << ", ISO is " << ISOToQDateTime(s = fakeCString(vObjectUStringZValue(vo))).toString() << endl; deleteStr(s); anEvent->setHasStartDate(true); } else { anEvent->setHasStartDate(false); } /* alarm stuff */ //kdDebug(5800) << "vcalformat::VTodoToEvent called" << endl; if ((vo = isAPropertyOf(vtodo, VCDAlarmProp))) { Alarm* alarm = anEvent->newAlarm(); VObject *a; if ((a = isAPropertyOf(vo, VCRunTimeProp))) { alarm->setTime(ISOToQDateTime(s = fakeCString(vObjectUStringZValue(a)))); deleteStr(s); } alarm->setEnabled(true); if ((vo = isAPropertyOf(vtodo, VCPAlarmProp))) { if ((a = isAPropertyOf(vo, VCProcedureNameProp))) { s = fakeCString(vObjectUStringZValue(a)); alarm->setProcedureAlarm(QFile::decodeName(s)); deleteStr(s); } } if ((vo = isAPropertyOf(vtodo, VCAAlarmProp))) { if ((a = isAPropertyOf(vo, VCAudioContentProp))) { s = fakeCString(vObjectUStringZValue(a)); alarm->setAudioAlarm(QFile::decodeName(s)); deleteStr(s); } } } // related todo if ((vo = isAPropertyOf(vtodo, VCRelatedToProp)) != 0) { anEvent->setRelatedToUid(s = fakeCString(vObjectUStringZValue(vo))); deleteStr(s); mTodosRelate.append(anEvent); @@ -1219,497 +1221,497 @@ Event* VCalFormat::VEventToEvent(VObject *vevent) } else { // e.g. YD1 123 #0 while (index < last) { int index2 = tmpStr.find(' ', index); tmpDay = tmpStr.mid(index, (index2-index)).toShort(); index = index2+1; anEvent->recurrence()->addYearlyNum(tmpDay); } // while != # } index = last; if (tmpStr.mid(index,1) == "#") index++; if (tmpStr.find('T', index) != -1) { QDate rEndDate = (ISOToQDateTime(tmpStr.mid(index, tmpStr.length()-index))).date(); anEvent->recurrence()->setYearly(Recurrence::rYearlyDay, rFreq, rEndDate); } else { int rDuration = tmpStr.mid(index, tmpStr.length()-index).toInt(); if (rDuration == 0) anEvent->recurrence()->setYearly(Recurrence::rYearlyDay, rFreq, -1); else anEvent->recurrence()->setYearly(Recurrence::rYearlyDay, rFreq, rDuration); } } else { kdDebug(5800) << "we don't understand this type of recurrence!" << endl; } // if } // repeats // recurrence exceptions if ((vo = isAPropertyOf(vevent, VCExpDateProp)) != 0) { s = fakeCString(vObjectUStringZValue(vo)); QStringList exDates = QStringList::split(",",s); QStringList::ConstIterator it; for(it = exDates.begin(); it != exDates.end(); ++it ) { anEvent->addExDate(ISOToQDate(*it)); } deleteStr(s); } // summary if ((vo = isAPropertyOf(vevent, VCSummaryProp))) { s = fakeCString(vObjectUStringZValue(vo)); anEvent->setSummary(QString::fromLocal8Bit(s)); deleteStr(s); } if ((vo = isAPropertyOf(vevent, VCLocationProp))) { s = fakeCString(vObjectUStringZValue(vo)); anEvent->setLocation(QString::fromLocal8Bit(s)); deleteStr(s); } // description if ((vo = isAPropertyOf(vevent, VCDescriptionProp)) != 0) { s = fakeCString(vObjectUStringZValue(vo)); if (!anEvent->description().isEmpty()) { anEvent->setDescription(anEvent->description() + "\n" + QString::fromLocal8Bit(s)); } else { anEvent->setDescription(QString::fromLocal8Bit(s)); } deleteStr(s); } // some stupid vCal exporters ignore the standard and use Description // instead of Summary for the default field. Correct for this. if (anEvent->summary().isEmpty() && !(anEvent->description().isEmpty())) { QString tmpStr = anEvent->description().simplifyWhiteSpace(); anEvent->setDescription(""); anEvent->setSummary(tmpStr); } #if 0 // status if ((vo = isAPropertyOf(vevent, VCStatusProp)) != 0) { QString tmpStr(s = fakeCString(vObjectUStringZValue(vo))); deleteStr(s); // TODO: Define Event status // anEvent->setStatus(tmpStr); } else // anEvent->setStatus("NEEDS ACTION"); #endif // secrecy int secrecy = Incidence::SecrecyPublic; if ((vo = isAPropertyOf(vevent, VCClassProp)) != 0) { s = fakeCString(vObjectUStringZValue(vo)); if (strcmp(s,"PRIVATE") == 0) { secrecy = Incidence::SecrecyPrivate; } else if (strcmp(s,"CONFIDENTIAL") == 0) { secrecy = Incidence::SecrecyConfidential; } deleteStr(s); } anEvent->setSecrecy(secrecy); // categories QStringList tmpStrList; if ((vo = isAPropertyOf(vevent, VCCategoriesProp)) != 0) { s = fakeCString(vObjectUStringZValue(vo)); QString categories = QString::fromLocal8Bit(s); deleteStr(s); tmpStrList = QStringList::split( ';', categories ); anEvent->setCategories(tmpStrList); } // attachments initPropIterator(&voi, vevent); while (moreIteration(&voi)) { vo = nextVObject(&voi); if (strcmp(vObjectName(vo), VCAttachProp) == 0) { s = fakeCString(vObjectUStringZValue(vo)); anEvent->addAttachment(new Attachment(QString(s))); deleteStr(s); } } // resources if ((vo = isAPropertyOf(vevent, VCResourcesProp)) != 0) { QString resources = (s = fakeCString(vObjectUStringZValue(vo))); deleteStr(s); tmpStrList = QStringList::split( ';', resources ); anEvent->setResources(tmpStrList); } /* alarm stuff */ if ((vo = isAPropertyOf(vevent, VCDAlarmProp))) { Alarm* alarm = anEvent->newAlarm(); VObject *a; if ((a = isAPropertyOf(vo, VCRunTimeProp))) { alarm->setTime(ISOToQDateTime(s = fakeCString(vObjectUStringZValue(a)))); deleteStr(s); } alarm->setEnabled(true); if ((vo = isAPropertyOf(vevent, VCPAlarmProp))) { if ((a = isAPropertyOf(vo, VCProcedureNameProp))) { s = fakeCString(vObjectUStringZValue(a)); alarm->setProcedureAlarm(QFile::decodeName(s)); deleteStr(s); } } if ((vo = isAPropertyOf(vevent, VCAAlarmProp))) { if ((a = isAPropertyOf(vo, VCAudioContentProp))) { s = fakeCString(vObjectUStringZValue(a)); alarm->setAudioAlarm(QFile::decodeName(s)); deleteStr(s); } } } // priority if ((vo = isAPropertyOf(vevent, VCPriorityProp))) { anEvent->setPriority(atoi(s = fakeCString(vObjectUStringZValue(vo)))); deleteStr(s); } // transparency if ((vo = isAPropertyOf(vevent, VCTranspProp)) != 0) { int i = atoi(s = fakeCString(vObjectUStringZValue(vo))); anEvent->setTransparency( i == 1 ? Event::Transparent : Event::Opaque ); deleteStr(s); } // related event if ((vo = isAPropertyOf(vevent, VCRelatedToProp)) != 0) { anEvent->setRelatedToUid(s = fakeCString(vObjectUStringZValue(vo))); deleteStr(s); mEventsRelate.append(anEvent); } /* PILOT SYNC STUFF */ if ((vo = isAPropertyOf(vevent, XPilotIdProp))) { anEvent->setPilotId(atoi(s = fakeCString(vObjectUStringZValue(vo)))); deleteStr(s); } else anEvent->setPilotId(0); if ((vo = isAPropertyOf(vevent, XPilotStatusProp))) { anEvent->setSyncStatus(atoi(s = fakeCString(vObjectUStringZValue(vo)))); deleteStr(s); } else anEvent->setSyncStatus(Event::SYNCMOD); return anEvent; } QString VCalFormat::qDateToISO(const QDate &qd) { QString tmpStr; - ASSERT(qd.isValid()); + Q_ASSERT(qd.isValid()); tmpStr.sprintf("%.2d%.2d%.2d", qd.year(), qd.month(), qd.day()); return tmpStr; } QString VCalFormat::qDateTimeToISO(const QDateTime &qdt, bool zulu) { QString tmpStr; - ASSERT(qdt.date().isValid()); - ASSERT(qdt.time().isValid()); + Q_ASSERT(qdt.date().isValid()); + Q_ASSERT(qdt.time().isValid()); if (zulu && !useLocalTime ) { QDateTime tmpDT = qdt.addSecs ( -KGlobal::locale()->localTimeOffset( qdt )*60); tmpStr.sprintf("%.2d%.2d%.2dT%.2d%.2d%.2dZ", tmpDT.date().year(), tmpDT.date().month(), tmpDT.date().day(), tmpDT.time().hour(), tmpDT.time().minute(), tmpDT.time().second()); } else { tmpStr.sprintf("%.2d%.2d%.2dT%.2d%.2d%.2d", qdt.date().year(), qdt.date().month(), qdt.date().day(), qdt.time().hour(), qdt.time().minute(), qdt.time().second()); } return tmpStr; } QDateTime VCalFormat::ISOToQDateTime(const QString & dtStr) { QDate tmpDate; QTime tmpTime; QString tmpStr; int year, month, day, hour, minute, second; tmpStr = dtStr; year = tmpStr.left(4).toInt(); month = tmpStr.mid(4,2).toInt(); day = tmpStr.mid(6,2).toInt(); hour = tmpStr.mid(9,2).toInt(); minute = tmpStr.mid(11,2).toInt(); second = tmpStr.mid(13,2).toInt(); tmpDate.setYMD(year, month, day); tmpTime.setHMS(hour, minute, second); - ASSERT(tmpDate.isValid()); - ASSERT(tmpTime.isValid()); + Q_ASSERT(tmpDate.isValid()); + Q_ASSERT(tmpTime.isValid()); QDateTime tmpDT(tmpDate, tmpTime); // correct for GMT if string is in Zulu format if (dtStr.at(dtStr.length()-1) == 'Z') tmpDT = tmpDT.addSecs (KGlobal::locale()->localTimeOffset( tmpDT )*60); return tmpDT; } QDate VCalFormat::ISOToQDate(const QString &dateStr) { int year, month, day; year = dateStr.left(4).toInt(); month = dateStr.mid(4,2).toInt(); day = dateStr.mid(6,2).toInt(); return(QDate(year, month, day)); } // take a raw vcalendar (i.e. from a file on disk, clipboard, etc. etc. // and break it down from it's tree-like format into the dictionary format // that is used internally in the VCalFormat. void VCalFormat::populate(VObject *vcal) { // this function will populate the caldict dictionary and other event // lists. It turns vevents into Events and then inserts them. VObjectIterator i; VObject *curVO, *curVOProp; Event *anEvent; if ((curVO = isAPropertyOf(vcal, ICMethodProp)) != 0) { char *methodType = 0; methodType = fakeCString(vObjectUStringZValue(curVO)); kdDebug() << "This calendar is an iTIP transaction of type '" << methodType << "'" << endl; delete methodType; } // warn the user that we might have trouble reading non-known calendar. if ((curVO = isAPropertyOf(vcal, VCProdIdProp)) != 0) { char *s = fakeCString(vObjectUStringZValue(curVO)); if (strcmp(productId().local8Bit(), s) != 0) kdDebug() << "This vCalendar file was not created by KOrganizer " "or any other product we support. Loading anyway..." << endl; mLoadedProductId = s; deleteStr(s); } // warn the user we might have trouble reading this unknown version. if ((curVO = isAPropertyOf(vcal, VCVersionProp)) != 0) { char *s = fakeCString(vObjectUStringZValue(curVO)); if (strcmp(_VCAL_VERSION, s) != 0) kdDebug() << "This vCalendar file has version " << s << "We only support " << _VCAL_VERSION << endl; deleteStr(s); } // set the time zone if ((curVO = isAPropertyOf(vcal, VCTimeZoneProp)) != 0) { if ( vObjectUStringZValue(curVO) != 0 ) { char *s = fakeCString(vObjectUStringZValue(curVO)); mCalendar->setTimeZone(s); deleteStr(s); } } // Store all events with a relatedTo property in a list for post-processing mEventsRelate.clear(); mTodosRelate.clear(); initPropIterator(&i, vcal); // go through all the vobjects in the vcal while (moreIteration(&i)) { curVO = nextVObject(&i); /************************************************************************/ // now, check to see that the object is an event or todo. if (strcmp(vObjectName(curVO), VCEventProp) == 0) { if ((curVOProp = isAPropertyOf(curVO, XPilotStatusProp)) != 0) { char *s; s = fakeCString(vObjectUStringZValue(curVOProp)); // check to see if event was deleted by the kpilot conduit if (atoi(s) == Event::SYNCDEL) { deleteStr(s); kdDebug(5800) << "skipping pilot-deleted event" << endl; goto SKIP; } deleteStr(s); } // this code checks to see if we are trying to read in an event // that we already find to be in the calendar. If we find this // to be the case, we skip the event. if ((curVOProp = isAPropertyOf(curVO, VCUniqueStringProp)) != 0) { char *s = fakeCString(vObjectUStringZValue(curVOProp)); QString tmpStr(s); deleteStr(s); if (mCalendar->event(tmpStr)) { goto SKIP; } if (mCalendar->todo(tmpStr)) { goto SKIP; } } if ((!(curVOProp = isAPropertyOf(curVO, VCDTstartProp))) && (!(curVOProp = isAPropertyOf(curVO, VCDTendProp)))) { kdDebug(5800) << "found a VEvent with no DTSTART and no DTEND! Skipping..." << endl; goto SKIP; } anEvent = VEventToEvent(curVO); // we now use addEvent instead of insertEvent so that the // signal/slot get connected. if (anEvent) { if ( !anEvent->dtStart().isValid() || !anEvent->dtEnd().isValid() ) { kdDebug() << "VCalFormat::populate(): Event has invalid dates." << endl; } else { mCalendar->addEvent(anEvent); } } else { // some sort of error must have occurred while in translation. goto SKIP; } } else if (strcmp(vObjectName(curVO), VCTodoProp) == 0) { Todo *aTodo = VTodoToEvent(curVO); mCalendar->addTodo(aTodo); } else if ((strcmp(vObjectName(curVO), VCVersionProp) == 0) || (strcmp(vObjectName(curVO), VCProdIdProp) == 0) || (strcmp(vObjectName(curVO), VCTimeZoneProp) == 0)) { // do nothing, we know these properties and we want to skip them. // we have either already processed them or are ignoring them. ; } else { kdDebug(5800) << "Ignoring unknown vObject \"" << vObjectName(curVO) << "\"" << endl; } SKIP: ; } // while // Post-Process list of events with relations, put Event objects in relation Event *ev; for ( ev=mEventsRelate.first(); ev != 0; ev=mEventsRelate.next() ) { Incidence * inc = mCalendar->event(ev->relatedToUid()); if ( inc ) ev->setRelatedTo( inc ); } Todo *todo; for ( todo=mTodosRelate.first(); todo != 0; todo=mTodosRelate.next() ) { Incidence * inc = mCalendar->todo(todo->relatedToUid()); if ( inc ) todo->setRelatedTo( inc ); } } const char *VCalFormat::dayFromNum(int day) { const char *days[7] = { "MO ", "TU ", "WE ", "TH ", "FR ", "SA ", "SU " }; return days[day]; } int VCalFormat::numFromDay(const QString &day) { if (day == "MO ") return 0; if (day == "TU ") return 1; if (day == "WE ") return 2; if (day == "TH ") return 3; if (day == "FR ") return 4; if (day == "SA ") return 5; if (day == "SU ") return 6; return -1; // something bad happened. :) } Attendee::Role VCalFormat::readRole(const char *s) const { QString statStr = s; statStr = statStr.upper(); Attendee::Role role = Attendee::ReqParticipant; if ( statStr == "OWNER") role = Attendee::Chair; // enum Role { ReqParticipant, OptParticipant, NonParticipant, Chair }; return role; } -QCString VCalFormat::writeRole(Attendee::Role role) const +Q3CString VCalFormat::writeRole(Attendee::Role role) const { if ( role == Attendee::Chair ) return "OWNER"; return "ATTENDEE"; } Attendee::PartStat VCalFormat::readStatus(const char *s) const { QString statStr = s; statStr = statStr.upper(); Attendee::PartStat status; if (statStr == "X-ACTION") status = Attendee::NeedsAction; else if (statStr == "NEEDS ACTION") status = Attendee::NeedsAction; else if (statStr== "ACCEPTED") status = Attendee::Accepted; else if (statStr== "SENT") status = Attendee::NeedsAction; else if (statStr== "TENTATIVE") status = Attendee::Tentative; else if (statStr== "CONFIRMED") status = Attendee::Accepted; else if (statStr== "DECLINED") status = Attendee::Declined; else if (statStr== "COMPLETED") status = Attendee::Completed; else if (statStr== "DELEGATED") status = Attendee::Delegated; else { kdDebug(5800) << "error setting attendee mStatus, unknown mStatus!" << endl; status = Attendee::NeedsAction; } return status; } -QCString VCalFormat::writeStatus(Attendee::PartStat status) const +Q3CString VCalFormat::writeStatus(Attendee::PartStat status) const { switch(status) { default: case Attendee::NeedsAction: return "NEEDS ACTION"; break; case Attendee::Accepted: return "ACCEPTED"; break; case Attendee::Declined: return "DECLINED"; break; case Attendee::Tentative: return "TENTATIVE"; break; case Attendee::Delegated: return "DELEGATED"; break; case Attendee::Completed: return "COMPLETED"; break; case Attendee::InProcess: return "NEEDS ACTION"; break; } } diff --git a/libkcal/vcalformat.h b/libkcal/vcalformat.h index 6dae3d2..cac9634 100644 --- a/libkcal/vcalformat.h +++ b/libkcal/vcalformat.h @@ -1,113 +1,116 @@ /* This file is part of libkcal. Copyright (c) 1998 Preston Brown Copyright (c) 2001 Cornelius Schumacher <schumacher@kde.org> 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #ifndef _VCALFORMAT_H #define _VCALFORMAT_H #include "calformat.h" +//Added by qt3to4: +#include <Q3CString> +#include <Q3PtrList> #define _VCAL_VERSION "1.0" class VObject; namespace KCal { /** This class implements the vCalendar format. It provides methods for loading/saving/converting vCalendar format data into the internal KOrganizer representation as Calendar and Events. @short vCalendar format implementation */ class VCalFormat : public CalFormat { public: VCalFormat(); virtual ~VCalFormat(); /** loads a calendar on disk in vCalendar format into the current calendar. * any information already present is lost. Returns TRUE if successful, * else returns FALSE. * @param fileName the name of the calendar on disk. */ bool load(Calendar *,const QString &fileName ); /** writes out the calendar to disk in vCalendar format. Returns true if * successful and false on error. * @param fileName the name of the file */ bool save(Calendar *,const QString &fileName ); /** Parse string and populate calendar with that information. */ bool fromString( Calendar *, const QString & ); /** Return calendar information as string. */ void setLocalTime ( bool ); QString toString( Calendar * ); QString eventToString( Event *, Calendar *calendar, bool useLocalTime = true ); QString todoToString( Todo * ,Calendar *calendar, bool useLocalTime = true ); protected: /** translates a VObject of the TODO type into a Event */ Todo *VTodoToEvent(VObject *vtodo); /** translates a VObject into a Event and returns a pointer to it. */ Event *VEventToEvent(VObject *vevent); /** translate a Event into a VTodo-type VObject and return pointer */ VObject *eventToVTodo(const Todo *anEvent); /** translate a Event into a VObject and returns a pointer to it. */ VObject* eventToVEvent(Event *anEvent); /** takes a QDate and returns a string in the format YYYYMMDDTHHMMSS */ QString qDateToISO(const QDate &); /** takes a QDateTime and returns a string in format YYYYMMDDTHHMMSS */ QString qDateTimeToISO(const QDateTime &, bool zulu=TRUE); /** takes a string in the format YYYYMMDDTHHMMSS and returns a * valid QDateTime. */ QDateTime ISOToQDateTime(const QString & dtStr); /** takes a string in the format YYYYMMDD and returns a * valid QDate. */ QDate ISOToQDate(const QString & dtStr); /** takes a vCalendar tree of VObjects, and puts all of them that have * the "event" property into the dictionary, todos in the todo-list, etc. */ void populate(VObject *vcal); /** takes a number 0 - 6 and returns the two letter string of that day, * i.e. MO, TU, WE, etc. */ const char *dayFromNum(int day); /** the reverse of the above function. */ int numFromDay(const QString &day); - Attendee::Role VCalFormat::readRole(const char *s) const; - QCString writeRole(Attendee::Role role) const; + Attendee::Role readRole(const char *s) const; + Q3CString writeRole(Attendee::Role role) const; Attendee::PartStat readStatus(const char *s) const; - QCString writeStatus(Attendee::PartStat status) const; + Q3CString writeStatus(Attendee::PartStat status) const; private: Calendar *mCalendar; bool useLocalTime; - QPtrList<Event> mEventsRelate; // events with relations - QPtrList<Todo> mTodosRelate; // todos with relations + Q3PtrList<Event> mEventsRelate; // events with relations + Q3PtrList<Todo> mTodosRelate; // todos with relations }; } #endif |