QString UtilMethods::getCurrentDate(int format)
{
    KDateTime now = KDateTime::currentLocalDateTime();
    QString toTxt = "";
    switch(format) {
        case EDefault: {
            toTxt = now.date().toString(Qt::TextDate);
        }break;

        case ESystemLocaleShortDate: {
            toTxt = now.date().toString(Qt::SystemLocaleShortDate);
        }break;
        case ESystemLocaleLongDate: {
            toTxt = now.date().toString(Qt::SystemLocaleLongDate);
        }break;
        case EDefaultLocaleShortDate: {
            toTxt = now.date().toString(Qt::DefaultLocaleShortDate);
        }break;
        case EDefaultLocaleLongDate: {
            toTxt = now.date().toString(Qt::DefaultLocaleLongDate);
        }break;

    }
    return toTxt;
}
Esempio n. 2
0
void tst_storage::tst_alldayUtc()
{
  // test event saved with UTC time
  auto event = KCalCore::Event::Ptr(new KCalCore::Event);
  QDate startDate(2013, 12, 1);
  event->setDtStart(KDateTime(startDate, QTime(), KDateTime::UTC));
  event->setAllDay(true);
  event->setSummary("test event utc");

  QCOMPARE(event->allDay(), true);

  m_calendar->addEvent(event, NotebookId);
  m_storage->save();
  QString uid = event->uid();
  reloadDb();

  auto fetchedEvent = m_calendar->event(uid);
  QVERIFY(fetchedEvent.data());
  QVERIFY(fetchedEvent->dtStart().isUtc());

  KDateTime localStart = fetchedEvent->dtStart().toLocalZone();
  QVERIFY(localStart.time() == QTime(2, 0));

  KDateTime localEnd = fetchedEvent->dtEnd().toLocalZone();
  QVERIFY(localEnd.time() == QTime(2, 0));

  QCOMPARE(localEnd.date(), localStart.date().addDays(1));
}
Esempio n. 3
0
QString DateStringBuilder::getDateString(const KDateTime &dateTime, bool grouped)
{
    if (!dateTime.isValid() || dateTime.isNull()) {
        return QString();
    }
    QString day;
    if (QDateTime().currentDateTime().date() == dateTime.date()) {
        day = i18nc( "today", "Today" );
    }
    if (QDateTime().currentDateTime().date().addDays(1) == dateTime.date()) {
        day = i18nc( "tomorrow", "Tomorrow" );
    }
    if (QDateTime().currentDateTime().date() == dateTime.date().addDays(1)) {
        day = i18nc( "yesterday", "Yesterday" );
    }
    if (!grouped && !day.isEmpty()) {
        return day.append("/t").append(dateTime.toString("%d.%m.%Y"));
    }

    if (!grouped && day.isEmpty()) {
        return dateTime.toString("%:a %d.%m.%Y");
    }

    if (QDateTime().currentDateTime().date().weekNumber() == dateTime.date().weekNumber()) {
        return dateTime.toString("%A");
    }

    //TODO last week

    return dateTime.toString("%B");
    //KGlobal::locale()->formatDate(pimitem->getPrimaryDate().dateTime());
    //return pimitem->getPrimaryDate().dateTime().toString("ddd dd.MM hh:mm");
    //return dateTime.toString("%:a %d.%m.%Y");
}
/******************************************************************************
* If the minimum and maximum date/times fall on the same date, set the minimum
* and maximum times in the time edit box.
*/
void AlarmTimeWidget::setMaxMinTimeIf(const KDateTime& now)
{
	int   mint = 0;
	QTime maxt = time_23_59;
	mMinMaxTimeSet = false;
	if (mMaxDateTime.isValid())
	{
		bool set = true;
		KDateTime minDT;
		if (mMinDateTimeIsNow)
			minDT = now.addSecs(60);
		else if (mMinDateTime.isValid())
			minDT = mMinDateTime;
		else
			set = false;
		if (set  &&  mMaxDateTime.date() == minDT.date())
		{
			// The minimum and maximum times are on the same date, so
			// constrain the time value.
			mint = minDT.time().hour()*60 + minDT.time().minute();
			maxt = mMaxDateTime.time();
			mMinMaxTimeSet = true;
		}
	}
	mTimeEdit->setMinimum(mint);
	mTimeEdit->setMaximum(maxt);
	mTimeEdit->setWrapping(!mint  &&  maxt == time_23_59);
}
Esempio n. 5
0
bool Recurrence::recursAt( const KDateTime &dt ) const
{
  // Convert to recurrence's time zone for date comparisons, and for more efficient time comparisons
  KDateTime dtrecur = dt.toTimeSpec( d->mStartDateTime.timeSpec() );

  // if it's excluded anyway, don't bother to check if it recurs at all.
  if ( d->mExDateTimes.containsSorted( dtrecur ) ||
       d->mExDates.containsSorted( dtrecur.date() ) ) {
    return false;
  }
  int i, end;
  for ( i = 0, end = d->mExRules.count();  i < end;  ++i ) {
    if ( d->mExRules[i]->recursAt( dtrecur ) ) {
      return false;
    }
  }

  // Check explicit recurrences, then rrules.
  if ( startDateTime() == dtrecur || d->mRDateTimes.containsSorted( dtrecur ) ) {
    return true;
  }
  for ( i = 0, end = d->mRRules.count();  i < end;  ++i ) {
    if ( d->mRRules[i]->recursAt( dtrecur ) ) {
      return true;
    }
  }

  return false;
}
Esempio n. 6
0
void CalSettings::loadSpecial(const QUrl& url, const QColor& color)
{
    if (url.isEmpty())
    {
        qCDebug(DIGIKAM_GENERAL_LOG) << "Loading calendar from file failed: No valid url provided!";
        return;
    }

    KCalCore::MemoryCalendar::Ptr memCal(new KCalCore::MemoryCalendar(QString::fromLatin1("UTC")));
    KCalCore::FileStorage::Ptr fileStorage(new KCalCore::FileStorage(memCal, url.toLocalFile(), new KCalCore::ICalFormat));

    qCDebug(DIGIKAM_GENERAL_LOG) << "Loading calendar from file " << url.toLocalFile();

    if (!fileStorage->load())
    {
        qCDebug(DIGIKAM_GENERAL_LOG) << "Failed!";
    }
    else
    {
        CalSystem calSys;
        QDate     qFirst, qLast;

        qFirst = calSys.date(params.year, 1, 1);
        qLast  = calSys.date(params.year + 1, 1, 1);
        qLast  = qLast.addDays(-1);

        KDateTime dtFirst(qFirst);
        KDateTime dtLast(qLast);
        KDateTime dtCurrent;

        int counter                = 0;
        KCalCore::Event::List list = memCal->rawEvents(qFirst, qLast);

        foreach(const KCalCore::Event::Ptr event, list)
        {
            qCDebug(DIGIKAM_GENERAL_LOG) << event->summary() << endl << "--------";
            counter++;

            if (event->recurs())
            {
                KCalCore::Recurrence* const recur = event->recurrence();

                for (dtCurrent = recur->getNextDateTime(dtFirst.addDays(-1));
                     (dtCurrent <= dtLast) && dtCurrent.isValid();
                     dtCurrent = recur->getNextDateTime(dtCurrent))
                {
                    addSpecial(dtCurrent.date(), Day(color, event->summary()));
                }
            }
            else
            {
                addSpecial(event->dtStart().date(), Day(color, event->summary()));
            }
        }

        qCDebug(DIGIKAM_GENERAL_LOG) << "Loaded " << counter << " events";
        memCal->close();
        fileStorage->close();
    }
/******************************************************************************
* Set the minimum date/time to track the current time.
*/
void AlarmTimeWidget::setMinDateTimeIsCurrent()
{
	mMinDateTimeIsNow = true;
	mMinDateTime = KDateTime();
	KDateTime now = KDateTime::currentDateTime(mTimeSpec);
	mDateEdit->setMinDate(now.date());
	setMaxMinTimeIf(now);
}
Esempio n. 8
0
QString DateStringBuilder::getGroupedDate(const KDateTime &dateTime)
{
    if (!dateTime.isValid() || dateTime.isNull()) {
        return QString();
    }
    QDate currentDate = QDateTime::currentDateTime().date();
    if (currentDate.weekNumber() == dateTime.date().weekNumber()) { //this week
        return getDayName(dateTime);
    }
    if (currentDate.addDays(-7).weekNumber() == dateTime.date().weekNumber()) { //last week
        return i18n("Last Week");
    }
    if (currentDate.year() == dateTime.date().year()) { //this year
        return dateTime.toString("%B");
    }
    return dateTime.toString("%B %Y");
}
Esempio n. 9
0
static QString yearForDate( const QString &upnpDate )
{
    KDateTime dateTime = KDateTime::fromString( upnpDate );
    int year = dateTime.date().year();
    if( !dateTime.isValid() ) {
        year = 0;
    }
    return QString::number( year );
}
Esempio n. 10
0
QString getDayName(const KDateTime &dateTime)
{
    if (!dateTime.isValid() || dateTime.isNull()) {
        return QString();
    }
    QString day;
    if (QDateTime().currentDateTime().date() == dateTime.date()) {
        return i18n("Today" );
    }
    if (QDateTime().currentDateTime().date().addDays(1) == dateTime.date()) {
        return i18n( "Tomorrow" );
    }
    if (QDateTime().currentDateTime().date() == dateTime.date().addDays(1)) {
        return i18n("Yesterday" );
    }
    return dateTime.toString("%A");

}
Esempio n. 11
0
QDate Event::dateEnd() const
{
  KDateTime end = dtEnd().toTimeSpec( dtStart() );
  if ( allDay() ) {
    return end.date();
  } else {
    return end.addSecs(-1).date();
  }
}
Esempio n. 12
0
QString DateStringBuilder::getShortDate(const KDateTime &dateTime)
{
    if (!dateTime.isValid() || dateTime.isNull()) {
        return QString();
    }
    QDate currentDate = QDateTime().currentDateTime().date();
    if (currentDate.weekNumber() == dateTime.date().weekNumber() || currentDate.addDays(1) == dateTime.date()) { //this week or tomorrow (i.e. on sunday)
        return getDayName(dateTime);
    }
    if (currentDate.year() == dateTime.date().year()) { //this year
        //Micro optimization because this function showed up as hotspot
        static QCache<uint, QString> cache;
        uint hash = dateTime.date().month() ^ dateTime.date().day();
        if (!cache.contains(hash)) {
            cache.insert(hash, new QString(dateTime.toString("%d.%m")));
        }
        return *cache[hash];
    }
    return dateTime.toString("%d.%m.%Y");
}
/******************************************************************************
* Called every minute to update the alarm time data entry fields.
* If the maximum date/time has been reached, a 'pastMax()' signal is emitted.
*/
void AlarmTimeWidget::updateTimes()
{
	KDateTime now;
	if (mMinDateTimeIsNow)
	{
		// Make sure that the minimum date is updated when the day changes
		now = KDateTime::currentDateTime(mTimeSpec);
		mDateEdit->setMinDate(now.date());
	}
	if (mMaxDateTime.isValid())
	{
		if (!now.isValid())
			now = KDateTime::currentDateTime(mTimeSpec);
		if (!mPastMax)
		{
			// Check whether the maximum date/time has now been reached
			if (now.date() >= mMaxDateTime.date())
			{
				// The current date has reached or has passed the maximum date
				if (now.date() > mMaxDateTime.date()
				||  (!mAnyTime && now.time() > mTimeEdit->maxTime()))
				{
					mPastMax = true;
					emit pastMax();
				}
				else if (mMinDateTimeIsNow  &&  !mMinMaxTimeSet)
				{
					// The minimum date/time tracks the clock, so set the minimum
					// and maximum times
					setMaxMinTimeIf(now);
				}
			}
		}
		setMaxDelayTime(now);
	}

	if (mAtTimeRadio->isChecked())
		dateTimeChanged();
	else
		delayTimeChanged(mDelayTimeEdit->value());
}
void ComingUpViewItemModel::updateEvents()
{
    modelEventList->clear();
    theData.clear();

    QList<CalendarEvent*>& eventList = viewManager.GetEvents();

    //int eventsLimitedTo = 3, comingUpEventCnt=0;
    int cntr = eventList.count();
    QDate today = QDate::currentDate();
    KDateTime daysLaterDate = KDateTime(today.addDays(7));

    for ( int i=0;i<cntr;i++ ) {
        CalendarEvent* event = eventList.at(i);
        bool addEvent = false;
        //Bug#7244 Author: [email protected]
        //Fixed the issue with display of "coming up" "Later" event list
        if ( restrictEventCount == true ) {
            if ( today == event->StartDate().date() )
            {
             addEvent = true;
            }
        } else {
            if(event->StartDate().date() > daysLaterDate.date()) {
                break;
            } else if ( event->StartDate().date() > today )
            {
                addEvent = true;
            }
        }

        if ( addEvent ) {
            modelEventList->append(event);
            QString dateString;
            //Bug#7320 Author: [email protected]
            //This piece of code fixes the issue with display of event
            //If today: Display time followed by event
            //Else Display Date-time followed by event
            if(today == event->StartDate().date()) {
                dateString = event->StartDate().toString ( "hh:mm AP" );
            } else {
                dateString = event->StartDate().toString ( "ddd dd hh:mm AP" );
            }
            QString alarmsString("alarmOFF");
            if ( event->Alarm() ) {
                alarmsString = "alarmON";
            }
            theData.append( QStringList() << dateString << event->Description() << alarmsString );
        }
    }
}
/******************************************************************************
* Set the maximum value for the delay time edit box, depending on the maximum
* value for the date/time.
*/
void AlarmTimeWidget::setMaxDelayTime(const KDateTime& now)
{
	int maxVal = maxDelayTime;
	if (mMaxDateTime.isValid())
	{
		if (now.date().daysTo(mMaxDateTime.date()) < 100)    // avoid possible 32-bit overflow on secsTo()
		{
			KDateTime dt(now);
			dt.setTime(QTime(now.time().hour(), now.time().minute(), 0));   // round down to nearest minute
			maxVal = dt.secsTo(mMaxDateTime) / 60;
			if (maxVal > maxDelayTime)
				maxVal = maxDelayTime;
		}
	}
	mDelayTimeEdit->setMaximum(maxVal);
}
Esempio n. 16
0
QString Stringify::formatDate( const KDateTime &dt, bool shortfmt, const KDateTime::Spec &spec )
{
  if ( spec.isValid() ) {

    QString timeZone;
    if ( spec.timeZone() != KSystemTimeZones::local() ) {
      timeZone = ' ' + spec.timeZone().name();
    }

    return
      KGlobal::locale()->formatDate( dt.toTimeSpec( spec ).date(),
                                     ( shortfmt ? KLocale::ShortDate : KLocale::LongDate ) ) +
      timeZone;
  } else {
    return
      KGlobal::locale()->formatDate( dt.date(),
                                     ( shortfmt ? KLocale::ShortDate : KLocale::LongDate ) );
  }
}
Esempio n. 17
0
int RecurrenceActions::availableOccurrences( const Incidence::Ptr &incidence,
                                             const KDateTime &selectedOccurrence )
{
  int result = NoOccurrence;

  if ( incidence->recurrence()->recursOn( selectedOccurrence.date(),
                                          selectedOccurrence.timeSpec() ) ) {
    result |= SelectedOccurrence;
  }

  if ( incidence->recurrence()->getPreviousDateTime( selectedOccurrence ).isValid() ) {
    result |= PastOccurrences;
  }

  if ( incidence->recurrence()->getNextDateTime( selectedOccurrence ).isValid() ) {
    result |= FutureOccurrences;
  }

  return result;
}
void KoRdfCalendarEvent::setupStylesheetReplacementMapping(QMap<QString, QString> &m)
{
    m["%UID%"] = m_uid;
    m["%START%"] = KGlobal::locale()->formatDateTime(m_dtstart.dateTime());
    m["%END%"] = KGlobal::locale()->formatDateTime(m_dtend.dateTime());
    m["%SUMMARY%"] = m_summary;
    m["%LOCATION%"] = m_location;
    QMap< QString, KDateTime > times;
    times["START"] = m_dtstart;
    times["END"] = m_dtend;
    for (QMap< QString, KDateTime >::iterator ti = times.begin(); ti != times.end(); ++ti) {
        QString key = QString("%") + ti.key();
        KDateTime dt = ti.value();
        QDate qd = dt.date();
        m[key + "-YEAR%"] = qd.year();
        m[key + "-MONTH-NUM%"] = qd.month();
        m[key + "-MONTH-NAME%"] = QDate::shortMonthName(qd.month());
        m[key + "-DAY-NUM%"] = qd.day();
        m[key + "-DAY-NAME%"] = QDate::shortDayName(qd.day());
    }
}
SummaryEventInfo::List SummaryEventInfo::eventsForDate( const QDate &date,
                                                        KCal::Calendar *calendar )
{
  KCal::Event *ev;

  KCal::Event::List events = calendar->events( date, calendar->timeSpec() );
  KCal::Event::List::ConstIterator it = events.constBegin();

  KDateTime qdt;
  KDateTime::Spec spec = KSystemTimeZones::local();
  KDateTime currentDateTime = KDateTime::currentDateTime( spec );
  QDate currentDate = currentDateTime.date();

  // sort the events for this date by summary
  events = KCal::Calendar::sortEvents( &events,
                                       KCal::EventSortSummary,
                                       KCal::SortDirectionAscending );
  // sort the events for this date by start date
  events = KCal::Calendar::sortEvents( &events,
                                       KCal::EventSortStartDate,
                                       KCal::SortDirectionAscending );

  List eventInfoList;

  for ( it=events.constBegin(); it != events.constEnd(); ++it ) {
    ev = *it;
    int daysTo = -1;

    // Count number of days remaining in multiday event
    int span = 1;
    int dayof = 1;
    if ( ev->isMultiDay() ) {
      QDate d = ev->dtStart().date();
      if ( d < currentDate ) {
        dayof += d.daysTo( currentDate );
        span += d.daysTo( currentDate );
        d = currentDate;
      }
      while ( d < ev->dtEnd().date() ) {
        if ( d < date ) {
          dayof++;
        }
        span++;
        d = d.addDays( 1 );
      }
    }

    QDate startOfMultiday = ev->dtStart().date();
    if ( startOfMultiday < currentDate ) {
      startOfMultiday = currentDate;
    }
    bool firstDayOfMultiday = ( date == startOfMultiday );

    // If this date is part of a floating, multiday event, then we
    // only make a print for the first day of the event.
    if ( ev->isMultiDay() && ev->allDay() &&
         ( currentDate > ev->dtStart().date() || !firstDayOfMultiday ) ) {
      continue;
    }
    // If the event is already over, then it isn't upcoming. so don't print it.
    if ( !ev->allDay() ) {
      if ( ev->recurs() ) {
        KDateTime kdt( date, QTime( 0, 0, 0 ), KSystemTimeZones::local() );
        kdt = kdt.addSecs( -1 );
        if ( currentDateTime > ev->recurrence()->getNextDateTime( kdt ) ) {
          continue;
        }
      } else {
        if ( currentDateTime > ev->dtEnd() ) {
          continue;
        }
      }
    }

    SummaryEventInfo *summaryEvent = new SummaryEventInfo();
    eventInfoList.append( summaryEvent );

    // Event
    summaryEvent->ev = ev;

    // Start date label
    QString str = "";
    QDate sD = QDate( date.year(), date.month(), date.day() );
    if ( ( sD.month() == currentDate.month() ) &&
          ( sD.day()   == currentDate.day() ) ) {
      str = i18nc( "the appointment is today", "Today" );
      summaryEvent->makeBold = true;
    } else if ( ( sD.month() == currentDate.addDays( 1 ).month() ) &&
                ( sD.day()   == currentDate.addDays( 1 ).day() ) ) {
      str = i18nc( "the appointment is tomorrow", "Tomorrow" );
    } else {
      str = KGlobal::locale()->formatDate( sD, KLocale::FancyLongDate );
    }
    summaryEvent->startDate = str;

    // Print the date span for multiday, floating events, for the
    // first day of the event only.
    if ( ev->isMultiDay() && ev->allDay() && firstDayOfMultiday && span > 1 ) {
      str = IncidenceFormatter::dateToString( ev->dtStart(), false, spec ) +
            " -\n " +
            IncidenceFormatter::dateToString( ev->dtEnd(), false, spec );
    }
    summaryEvent->dateSpan = str;

    // Days to go label
    str = "";
    dateDiff( startOfMultiday, daysTo );
    if ( ev->isMultiDay() && !ev->allDay() ) {
      dateDiff( date, daysTo );
    }
    if ( daysTo > 0 ) {
      str = i18np( "in 1 day", "in %1 days", daysTo );
    } else {
      if ( !ev->allDay() ) {
        int secs;
        if ( !ev->recurs() ) {
          secs = currentDateTime.secsTo( ev->dtStart() );
        } else {
          KDateTime kdt( date, QTime( 0, 0, 0 ), KSystemTimeZones::local() );
          kdt = kdt.addSecs( -1 );
          KDateTime next = ev->recurrence()->getNextDateTime( kdt );
          secs = currentDateTime.secsTo( next );
        }
        if ( secs > 0 ) {
          str = i18nc( "eg. in 1 hour 2 minutes", "in " );
          int hours = secs / 3600;
          if ( hours > 0 ) {
            str += i18ncp( "use abbreviation for hour to keep the text short",
                           "1 hr", "%1 hrs", hours );
            str += ' ';
            secs -= ( hours * 3600 );
          }
          int mins = secs / 60;
          if ( mins > 0 ) {
            str += i18ncp( "use abbreviation for minute to keep the text short",
                           "1 min", "%1 mins", mins );
          }
        } else {
          str = i18n( "now" );
        }
      } else {
        str = i18n( "all day" );
      }
    }
    summaryEvent->daysToGo = str;

    // Summary label
    str = ev->richSummary();
    if ( ev->isMultiDay() &&  !ev->allDay() ) {
      str.append( QString( " (%1/%2)" ).arg( dayof ).arg( span ) );
    }
    summaryEvent->summaryText = str;
    summaryEvent->summaryUrl = ev->uid();
    QString tipText( KCal::IncidenceFormatter::toolTipStr( calendar, ev, date, true, spec ) );
    if ( !tipText.isEmpty() ) {
      summaryEvent->summaryTooltip = tipText;
    }

    // Time range label (only for non-floating events)
    str = "";
    if ( !ev->allDay() ) {
      QTime sST = ev->dtStart().toTimeSpec( spec ).time();
      QTime sET = ev->dtEnd().toTimeSpec( spec ).time();
      if ( ev->isMultiDay() ) {
        if ( ev->dtStart().date() < date ) {
          sST = QTime( 0, 0 );
        }
        if ( ev->dtEnd().date() > date ) {
          sET = QTime( 23, 59 );
        }
      }
      str = i18nc( "Time from - to", "%1 - %2",
                    KGlobal::locale()->formatTime( sST ),
                    KGlobal::locale()->formatTime( sET ) );
      summaryEvent->timeRange = str;
    }

    // For recurring events, append the next occurrence to the time range label
    if ( ev->recurs() ) {
      KDateTime kdt( date, QTime( 0, 0, 0 ), KSystemTimeZones::local() );
      kdt = kdt.addSecs( -1 );
      KDateTime next = ev->recurrence()->getNextDateTime( kdt );
      QString tmp = IncidenceFormatter::dateTimeToString(
        ev->recurrence()->getNextDateTime( next ), ev->allDay(),
        true, KSystemTimeZones::local() );
      if ( !summaryEvent->timeRange.isEmpty() ) {
        summaryEvent->timeRange += "<br>";
      }
      summaryEvent->timeRange += "<font size=\"small\"><i>" +
                                 i18nc( "next occurrence", "Next: %1", tmp ) +
                                 "</i></font>";
    }
  }

  return eventInfoList;
}
Esempio n. 20
0
    Incidence::Ptr pasteIncidence( const Incidence::Ptr &incidence,
                                   KDateTime newDateTime,
                                   const QFlags<PasteFlag> &pasteOptions )
    {
      Incidence::Ptr inc( incidence );

      if ( inc ) {
        inc = Incidence::Ptr( inc->clone() );
        inc->recreate();
      }

      if ( inc && newDateTime.isValid() ) {
        if ( inc->type() == Incidence::TypeEvent ) {
          Event::Ptr event = inc.staticCast<Event>();
          if ( pasteOptions & FlagPasteAtOriginalTime ) {
            // Set date and preserve time and timezone stuff
            const QDate date = newDateTime.date();
            newDateTime = event->dtStart();
            newDateTime.setDate( date );
          }

          // in seconds
          const int durationInSeconds = event->dtStart().secsTo( event->dtEnd() );
          const int durationInDays = event->dtStart().daysTo( event->dtEnd() );

          event->setDtStart( newDateTime );

          if ( newDateTime.isDateOnly() ) {
            event->setDtEnd( newDateTime.addDays( durationInDays ) );
          } else {
            event->setDtEnd( newDateTime.addSecs( durationInSeconds ) );
          }

        } else if ( inc->type() == Incidence::TypeTodo ) {
          Todo::Ptr aTodo = inc.staticCast<Todo>();
          const bool pasteAtDtStart = ( pasteOptions & FlagTodosPasteAtDtStart );
          if ( pasteOptions & FlagPasteAtOriginalTime ) {
            // Set date and preserve time and timezone stuff
            const QDate date = newDateTime.date();
            newDateTime = pasteAtDtStart ? aTodo->dtStart() : aTodo->dtDue();
            newDateTime.setDate( date );
          }
          if ( pasteAtDtStart ) {
            aTodo->setDtStart( newDateTime );
          } else {
            aTodo->setDtDue( newDateTime );
          }

        } else if ( inc->type() == Incidence::TypeJournal ) {
          if ( pasteOptions & FlagPasteAtOriginalTime ) {
            // Set date and preserve time and timezone stuff
            const QDate date = newDateTime.date();
            newDateTime = inc->dtStart();
            newDateTime.setDate( date );
          }
          inc->setDtStart( newDateTime );
        } else {
          kDebug() << "Trying to paste unknown incidence of type" << int( inc->type() );
        }
      }

      return inc;
    }
void KCalResourceSlox::parseRecurrence( const QDomNode &node, Event *event )
{
  QString type;

  int dailyValue = -1;
  KDateTime end;

  int weeklyValue = -1;
  QBitArray days( 7 ); // days, starting with monday
  bool daysSet = false;

  int monthlyValueDay = -1;
  int monthlyValueMonth = -1;

  int yearlyValueDay = -1;
  int yearlyMonth = -1;

  int monthly2Recurrency = 0;
  int monthly2Day = 0;
  int monthly2ValueMonth = -1;

  int yearly2Recurrency = 0;
  int yearly2Day = 0;
  int yearly2Month = -1;

  DateList deleteExceptions;

  QDomNode n;

  for( n = node.firstChild(); !n.isNull(); n = n.nextSibling() ) {
    QDomElement e = n.toElement();
    QString tag = e.tagName();
    QString text = decodeText( e.text() );
    kDebug() << tag << ":" << text;

    if ( tag == fieldName( RecurrenceType ) ) {
      type = text;
    } else if ( tag == "daily_value" ) {
      dailyValue = text.toInt();
    } else if ( tag == fieldName( RecurrenceEnd ) ) {
      end = WebdavHandler::sloxToKDateTime( text );
    } else if ( tag == "weekly_value" ) {
      weeklyValue = text.toInt();
    } else if ( tag.left( 11 ) == "weekly_day_" ) {
      int day = tag.mid( 11, 1 ).toInt();
      int index;
      if ( day == 1 ) index = 0;
      else index = day - 2;
      days.setBit( index );
    } else if ( tag == "monthly_value_day" ) {
      monthlyValueDay = text.toInt();
    } else if ( tag == "monthly_value_month" ) {
      monthlyValueMonth = text.toInt();
    } else if ( tag == "yearly_value_day" ) {
      yearlyValueDay = text.toInt();
    } else if ( tag == "yearly_month" ) {
      yearlyMonth = text.toInt();
    } else if ( tag == "monthly2_recurrency" ) {
      monthly2Recurrency = text.toInt();
    } else if ( tag == "monthly2_day" ) {
      monthly2Day = text.toInt();
    } else if ( tag == "monthly2_value_month" ) {
      monthly2ValueMonth = text.toInt();
    } else if ( tag == "yearly2_reccurency" ) { // this is not a typo, this is what SLOX really sends!
      yearly2Recurrency = text.toInt();
    } else if ( tag == "yearly2_day" ) {
      yearly2Day = text.toInt();
    } else if ( tag == "yearly2_month" ) {
      yearly2Month = text.toInt() + 1;
    // OX recurrence fields
    } else if ( tag == "interval" ) {
      dailyValue = text.toInt();
      weeklyValue = text.toInt();
      monthlyValueMonth = text.toInt();
      monthly2ValueMonth = text.toInt();
    } else if ( tag == "days" ) {
      int tmp = text.toInt();  // OX encodes days binary: 1=Su, 2=Mo, 4=Tu, ...
      for ( int i = 0; i < 7; ++i ) {
        if ( tmp & (1 << i) )
          days.setBit( (i + 6) % 7 );
      }
      daysSet = true;
    } else if ( tag == "day_in_month" ) {
      monthlyValueDay = text.toInt();
      monthly2Recurrency = text.toInt();
      yearlyValueDay = text.toInt();
      yearly2Recurrency = text.toInt();
    } else if ( tag == "month" ) {
      yearlyMonth = text.toInt() + 1; // starts at 0
      yearly2Month = text.toInt() + 1;
    } else if ( tag == fieldName( RecurrenceDelEx ) ) {
      QStringList exdates = text.split( "," );
      QStringList::ConstIterator it;
      for ( it = exdates.constBegin(); it != exdates.constEnd(); ++it )
        deleteExceptions.append( WebdavHandler::sloxToKDateTime( *it ).date() );
    }
  }

  if ( daysSet && type == "monthly" )
    type = "monthly2"; // HACK: OX doesn't cleanly distinguish between monthly and monthly2
  if ( daysSet && type == "yearly" )
    type = "yearly2";

  Recurrence *r = event->recurrence();

  if ( type == "daily" ) {
    r->setDaily( dailyValue );
  } else if ( type == "weekly" ) {
    r->setWeekly( weeklyValue, days );
  } else if ( type == "monthly" ) {
    r->setMonthly( monthlyValueMonth );
    r->addMonthlyDate( monthlyValueDay );
  } else if ( type == "yearly" ) {
    r->setYearly( 1 );
    r->addYearlyDate( yearlyValueDay );
    r->addYearlyMonth( yearlyMonth );
  } else if ( type == "monthly2" ) {
    r->setMonthly( monthly2ValueMonth );
    QBitArray _days( 7 );
    if ( daysSet )
      _days = days;
    else
      _days.setBit( event->dtStart().date().dayOfWeek() );
    r->addMonthlyPos( monthly2Recurrency, _days );
  } else if ( type == "yearly2" ) {
    r->setYearly( 1 );
    r->addYearlyMonth( yearly2Month );
    QBitArray _days( 7 );
    if ( daysSet )
      _days = days;
    else
      _days.setBit( ( yearly2Day + 5 ) % 7 );
    r->addYearlyPos( yearly2Recurrency, _days );
  }
  r->setEndDate( end.date() );
  r->setExDates( deleteExceptions );
}
Esempio n. 22
0
void EditableDate::setDate(const KDateTime& date)
{
    m_label->setText(DateStringBuilder::getFullDate(date));
    m_dateTimeWidget->setDate(date.date());
}
Esempio n. 23
0
KDateTime Recurrence::getPreviousDateTime( const KDateTime &afterDateTime ) const
{
  KDateTime prevDT = afterDateTime;
  // prevent infinite loops, e.g. when an exrule extinguishes an rrule (e.g.
  // the exrule is identical to the rrule). If an occurrence is found, break
  // out of the loop by returning that KDateTime
  int loop = 0;
  while ( loop < 1000 ) {
    // Outline of the algo:
    //   1) Find the next date/time after preDateTime when the event could recur
    //     1.1) Use the next occurrence from the explicit RDATE lists
    //     1.2) Add the next recurrence for each of the RRULEs
    //   2) Take the earliest recurrence of these = KDateTime nextDT
    //   3) If that date/time is not excluded, either explicitly by an EXDATE or
    //      by an EXRULE, return nextDT as the next date/time of the recurrence
    //   4) If it's excluded, start all at 1), but starting at nextDT (instead
    //      of preDateTime). Loop at most 1000 times.
    ++loop;
    // First, get the next recurrence from the RDate lists
    DateTimeList dates;
    if ( prevDT > startDateTime() ) {
      dates << startDateTime();
    }

    int i = d->mRDateTimes.findLT( prevDT );
    if ( i >= 0 ) {
      dates << d->mRDateTimes[i];
    }

    KDateTime kdt( startDateTime() );
    for ( i = d->mRDates.count();  --i >= 0; ) {
      kdt.setDate( d->mRDates[i] );
      if ( kdt < prevDT ) {
        dates << kdt;
        break;
      }
    }

    // Add the previous occurrences from all RRULEs.
    int end;
    for ( i = 0, end = d->mRRules.count();  i < end;  ++i ) {
      KDateTime dt = d->mRRules[i]->getPreviousDate( prevDT );
      if ( dt.isValid() ) {
        dates << dt;
      }
    }

    // Take the last of these (all others can't be used later on)
    dates.sortUnique();
    if ( dates.isEmpty() ) {
      return KDateTime();
    }
    prevDT = dates.last();

    // Check if that date/time is excluded explicitly or by an exrule:
    if ( !d->mExDates.containsSorted( prevDT.date() ) &&
         !d->mExDateTimes.containsSorted( prevDT ) ) {
      bool allowed = true;
      for ( i = 0, end = d->mExRules.count();  i < end;  ++i ) {
        allowed = allowed && !( d->mExRules[i]->recursAt( prevDT ) );
      }
      if ( allowed ) {
        return prevDT;
      }
    }
  }

  // Couldn't find a valid occurrences in 1000 loops, something is wrong!
  return KDateTime();
}
Esempio n. 24
0
QDate Incidence::creationDate() {
    KDateTime createdDT = get_object()->created();
    return createdDT.date();
}
Esempio n. 25
0
TimeList Recurrence::recurTimesOn( const QDate &date, const KDateTime::Spec &timeSpec ) const
{
// kDebug() << "recurTimesOn(" << date << ")";
  int i, end;
  TimeList times;

  // The whole day is excepted
  if ( d->mExDates.containsSorted( date ) ) {
    return times;
  }

  // EXRULE takes precedence over RDATE entries, so for all-day events,
  // a matching excule also excludes the whole day automatically
  if ( allDay() ) {
    for ( i = 0, end = d->mExRules.count();  i < end;  ++i ) {
      if ( d->mExRules[i]->recursOn( date, timeSpec ) ) {
        return times;
      }
    }
  }

  KDateTime dt = startDateTime().toTimeSpec( timeSpec );
  if ( dt.date() == date ) {
    times << dt.time();
  }

  bool foundDate = false;
  for ( i = 0, end = d->mRDateTimes.count();  i < end;  ++i ) {
    dt = d->mRDateTimes[i].toTimeSpec( timeSpec );
    if ( dt.date() == date ) {
      times << dt.time();
      foundDate = true;
    } else if ( foundDate ) {
      break; // <= Assume that the rdatetime list is sorted
    }
  }
  for ( i = 0, end = d->mRRules.count();  i < end;  ++i ) {
    times += d->mRRules[i]->recurTimesOn( date, timeSpec );
  }
  times.sortUnique();

  foundDate = false;
  TimeList extimes;
  for ( i = 0, end = d->mExDateTimes.count();  i < end;  ++i ) {
    dt = d->mExDateTimes[i].toTimeSpec( timeSpec );
    if ( dt.date() == date ) {
      extimes << dt.time();
      foundDate = true;
    } else if ( foundDate ) {
      break;
    }
  }
  if ( !allDay() ) {     // we have already checked all-day times above
    for ( i = 0, end = d->mExRules.count();  i < end;  ++i ) {
      extimes += d->mExRules[i]->recurTimesOn( date, timeSpec );
    }
  }
  extimes.sortUnique();

  int st = 0;
  for ( i = 0, end = extimes.count();  i < end;  ++i ) {
    int j = times.removeSorted( extimes[i], st );
    if ( j >= 0 ) {
      st = j;
    }
  }
  return times;
}
/******************************************************************************
* Fetch the entered date/time.
* If 'checkExpired' is true and the entered value <= current time, an error occurs.
* If 'minsFromNow' is non-null, it is set to the number of minutes' delay selected,
* or to zero if a date/time was entered.
* In this case, if 'showErrorMessage' is true, output an error message.
* 'errorWidget' if non-null, is set to point to the widget containing the error.
* Reply = invalid date/time if error.
*/
KDateTime AlarmTimeWidget::getDateTime(int* minsFromNow, bool checkExpired, bool showErrorMessage, QWidget** errorWidget) const
{
	if (minsFromNow)
		*minsFromNow = 0;
	if (errorWidget)
		*errorWidget = 0;
	KDateTime now = KDateTime::currentUtcDateTime();
	now.setTime(QTime(now.time().hour(), now.time().minute(), 0));
	if (!mAtTimeRadio->isChecked())
	{
		if (!mDelayTimeEdit->isValid())
		{
			if (showErrorMessage)
				KMessageBox::sorry(const_cast<AlarmTimeWidget*>(this), i18nc("@info", "Invalid time"));
			if (errorWidget)
				*errorWidget = mDelayTimeEdit;
			return KDateTime();
		}
		int delayMins = mDelayTimeEdit->value();
		if (minsFromNow)
			*minsFromNow = delayMins;
		return now.addSecs(delayMins * 60).toTimeSpec(mTimeSpec);
	}
	else
	{
		bool dateOnly = mAnyTimeAllowed && mAnyTimeCheckBox && mAnyTimeCheckBox->isChecked();
		if (!mDateEdit->isValid()  ||  !mTimeEdit->isValid())
		{
			// The date and/or time is invalid
			if (!mDateEdit->isValid())
			{
				if (showErrorMessage)
					KMessageBox::sorry(const_cast<AlarmTimeWidget*>(this), i18nc("@info", "Invalid date"));
				if (errorWidget)
					*errorWidget = mDateEdit;
			}
			else
			{
				if (showErrorMessage)
					KMessageBox::sorry(const_cast<AlarmTimeWidget*>(this), i18nc("@info", "Invalid time"));
				if (errorWidget)
					*errorWidget = mTimeEdit;
			}
			return KDateTime();
		}

		KDateTime result;
		if (dateOnly)
		{
			result = KDateTime(mDateEdit->date(), mTimeSpec);
			if (checkExpired  &&  result.date() < now.date())
			{
				if (showErrorMessage)
					KMessageBox::sorry(const_cast<AlarmTimeWidget*>(this), i18nc("@info", "Alarm date has already expired"));
				if (errorWidget)
					*errorWidget = mDateEdit;
				return KDateTime();
			}
		}
		else
		{
			result = KDateTime(mDateEdit->date(), mTimeEdit->time(), mTimeSpec);
			if (checkExpired  &&  result <= now.addSecs(1))
			{
				if (showErrorMessage)
					KMessageBox::sorry(const_cast<AlarmTimeWidget*>(this), i18nc("@info", "Alarm time has already expired"));
				if (errorWidget)
					*errorWidget = mTimeEdit;
				return KDateTime();
			}
		}
		return result;
	}
}