Ejemplo n.º 1
0
void DDatePicker::Private::fillWeeksCombo()
{
    // every year can have a different number of weeks
    // it could be that we had 53,1..52 and now 1..53 which is the same number but different
    // so always fill with new values
    // We show all week numbers for all weeks between first day of year to last day of year
    // This of course can be a list like 53,1,2..52

    const QDate thisDate      = q->date();
    const int thisYear        = thisDate.year();
    QDate day(thisDate.year(), 1, 1);
    const QDate lastDayOfYear = QDate(thisDate.year() + 1, 1, 1).addDays(-1);

    selectWeek->clear();

    // Starting from the first day in the year, loop through the year a week at a time
    // adding an entry to the week combo for each week in the year

    for (; day.isValid() && day <= lastDayOfYear; day = day.addDays(7))
    {
        // Get the ISO week number for the current day and what year that week is in
        // e.g. 1st day of this year may fall in week 53 of previous year
        int weekYear       = thisYear;
        const int week     = day.weekNumber(&weekYear);
        QString weekString = i18n("Week %1", QString::number(week));

        // show that this is a week from a different year
        if (weekYear != thisYear)
        {
            weekString += QLatin1Char('*');
        }

        // when the week is selected, go to the same weekday as the one
        // that is currently selected in the date table
        QDate targetDate = day.addDays(thisDate.dayOfWeek() - day.dayOfWeek());
        selectWeek->addItem(weekString, targetDate);

        // make sure that the week of the lastDayOfYear is always inserted: in Chinese calendar
        // system, this is not always the case
        if (day < lastDayOfYear           &&
            day.daysTo(lastDayOfYear) < 7 &&
            lastDayOfYear.weekNumber() != day.weekNumber())
        {
            day = lastDayOfYear.addDays(-7);
        }
    }
}
void TransactionView::chooseDate(int idx)
{
    if(!transactionProxyModel)
        return;
    QDate current = QDate::currentDate();
    dateRangeWidget->setVisible(false);
    switch(dateWidget->itemData(idx).toInt())
    {
    case All:
        transactionProxyModel->setDateRange(
                TransactionFilterProxy::MIN_DATE,
                TransactionFilterProxy::MAX_DATE);
        break;
    case Today:
        transactionProxyModel->setDateRange(
                QDateTime(current),
                TransactionFilterProxy::MAX_DATE);
        break;
    case ThisWeek: {
        // Find last Monday
        QDate startOfWeek = current.addDays(-(current.dayOfWeek()-1));
        transactionProxyModel->setDateRange(
                QDateTime(startOfWeek),
                TransactionFilterProxy::MAX_DATE);

        } break;
    case ThisMonth:
        transactionProxyModel->setDateRange(
                QDateTime(QDate(current.year(), current.month(), 1)),
                TransactionFilterProxy::MAX_DATE);
        break;
    case LastMonth:
        transactionProxyModel->setDateRange(
                QDateTime(QDate(current.year(), current.month()-1, 1)),
                QDateTime(QDate(current.year(), current.month(), 1)));
        break;
    case ThisYear:
        transactionProxyModel->setDateRange(
                QDateTime(QDate(current.year(), 1, 1)),
                TransactionFilterProxy::MAX_DATE);
        break;
    case Range:
        dateRangeWidget->setVisible(true);
        dateRangeChanged();
        break;
    }
}
Ejemplo n.º 3
0
void WeeklyTimesheetConfigurationDialog::showReportPreviewDialog( QWidget* parent )
{
    QDate start, end;
    int index = m_ui->comboBoxWeek->currentIndex();
    if ( index == m_weekInfo.size() -1 ) {
        // manual selection
        QDate selectedDate = m_ui->dateEditDay->date();
        start = selectedDate.addDays( - selectedDate.dayOfWeek() + 1 );
        end = start.addDays( 7 );
    } else {
        start = m_weekInfo[index].timespan.first;
        end = m_weekInfo[index].timespan.second;
    }
    bool activeOnly = m_ui->checkBoxActiveOnly->isChecked();
    WeeklyTimeSheetReport* report = new WeeklyTimeSheetReport( parent );
    report->setReportProperties( start, end, m_rootTask, activeOnly );
    report->show();
}
Ejemplo n.º 4
0
/*!
 Replacement for localtime_r() which is not available on MinGW.

 We use this on all of Qt's platforms for portability.
 */
struct tm gmtimeQt(const QDateTime &input)
{
    tm result;

    const QDate date(input.date());
    result.tm_year = date.year() - 1900;
    result.tm_mon = date.month();
    result.tm_mday = date.day();
    result.tm_wday = date.dayOfWeek();
    result.tm_yday = date.dayOfYear();

    const QTime time(input.time());
    result.tm_sec = time.second();
    result.tm_min = time.minute();
    result.tm_hour = time.hour();

    return result;
}
Ejemplo n.º 5
0
bool
kMyMoneyDateTbl::setDate(const QDate& date_)
{
  bool changed=false;
  QDate temp;
  // -----
  if(!date_.isValid())
  {
    kdDebug() << "kMyMoneyDateTbl::setDate: refusing to set invalid date." << endl;
    return false;
  }

  if(date!=date_)
  {
    date=date_;
    changed=true;
  }

  temp.setYMD(date.year(), date.month(), 1);
  firstday=temp.dayOfWeek();

  if (firstday==1)
    firstday=8;

  numdays=date.daysInMonth();

  if (date.month()==1)
  { // set to december of previous year
    temp.setYMD(date.year()-1, 12, 1);
  } else { // set to previous month
    temp.setYMD(date.year(), date.month()-1, 1);
  }

  numDaysPrevMonth=temp.daysInMonth();

  if (changed)
  {
    repaintContents(false);
  }

  emit(dateChanged(date));
  return true;
}
Ejemplo n.º 6
0
/**
 * Checks to see if there is a away message that we should put up right now.
 * Once done starts a new clock.
 */
void AwaySchedule::checkToSeeIfWeShouldGoAway() {
    QDate d = QDate::currentDate();
    int day = d.dayOfWeek()-1;
    QTime t = QTime::currentTime();

    appointment *a = appointments.first();
    while( a ) {
        if( a->day == day ) {
            if( a->startHour <= t.hour() && a->endHour >= t.hour() ) {
                bool found = true;
                if( a->startHour == t.hour() ) {
                    if( a->startMinute <= t.minute() )
                        found = true;
                    else
                        found = false;
                }
                if( found == true ) {
                    if( a->endHour == t.hour() ) {
                        if( a->endMinute >= t.minute() )
                            found = true;
                        else
                            found = false;
                    }
                    if( found == true ) {
                        if(!onLine()) {
                            // We are not online
                            break;
                        }
                        else {
                            qDebug("We found it within the hour time.");
                            if( enabled )
                                setAwayNow(a->message);
                            break;
                        }
                    }
                }
            }
        }
        a = appointments.next();
    }
    QTimer::singleShot(  TIME_TO_CHECK_IN_SECONDS*1000, this, SLOT(checkToSeeIfWeShouldGoAway()));

}
Ejemplo n.º 7
0
void tst_QCalendarWidget::setWeekdayFormat()
{
    QCalendarWidget calendar;

    QTextCharFormat format;
    format.setFontItalic(true);
    format.setForeground(Qt::green);

    calendar.setWeekdayTextFormat(Qt::Wednesday, format);

    // check the format of the a given month
    for (int i = 1; i <= 31; ++i) {
        const QDate date(1984, 10, i);
        const Qt::DayOfWeek dayOfWeek = static_cast<Qt::DayOfWeek>(date.dayOfWeek());
        if (dayOfWeek == Qt::Wednesday)
            QCOMPARE(calendar.weekdayTextFormat(dayOfWeek), format);
        else
            QVERIFY(calendar.weekdayTextFormat(dayOfWeek) != format);
    }
}
/* Reads the text from the line edit. If the text is a keyword, the
 * word will be translated to a date. If the text is not a keyword, the
 * text will be interpreted as a date.
 * Returns true if the date text is blank or valid, false otherwise.
 */
bool AnnotationDialog::KDateEdit::readDate(QDate& result, QDate* end) const
{
    QString text = currentText();

    if (text.isEmpty()) {
        result = QDate();
    }
    else if (mKeywordMap.contains(text.toLower()))
    {
        QDate today = QDate::currentDate();
        int i = mKeywordMap[text.toLower()];
        if (i >= 100)
        {
            /* A day name has been entered. Convert to offset from today.
             * This uses some math tricks to figure out the offset in days
             * to the next date the given day of the week occurs. There
             * are two cases, that the new day is >= the current day, which means
             * the new day has not occurred yet or that the new day < the current day,
             * which means the new day is already passed (so we need to find the
             * day in the next week).
             */
            i -= 100;
            int currentDay = today.dayOfWeek();
            if (i >= currentDay)
                i -= currentDay;
            else
                i += 7 - currentDay;
        }
        result = today.addDays(i);
    }
    else
    {
        result = DB::ImageDate::parseDate( text, mIsStartEdit );
        if ( end )
            *end = DB::ImageDate::parseDate( text, false );
        return result.isValid();
    }

    return true;
}
Ejemplo n.º 9
0
// The following code is borrowed from QT 3.2 QDate::weekNumber()
// and slightly modified
int kMyMoneyDateTbl::weekNumber(const QDate& date, int *yearNumber) const
{
     if ( !date.isValid() )
        return 0;

    int dow = date.dayOfWeek();
    int doy = date.dayOfYear();
    int currYear = date.year();
    int jan1WeekDay = QDate( currYear, 1, 1 ).dayOfWeek();
    int yearNum;
    int weekNum;

    if ( doy <= (8 - jan1WeekDay) && jan1WeekDay > 4 ) {
        yearNum = currYear - 1;
        weekNum = 52;
        if ( jan1WeekDay == 5 ||
             (jan1WeekDay == 6 && QDate::leapYear(yearNum)) )
            weekNum++;
    } else {
        int totalDays = 365;
        if ( QDate::leapYear(currYear) )
            totalDays++;

        if ( (totalDays - doy < 4 - dow)
             || (jan1WeekDay == 7 && totalDays - doy < 3) ) {
            yearNum = currYear + 1;
            weekNum = 1;
        } else {
            int j = doy + ( 7 - dow ) + ( jan1WeekDay - 1 );
            yearNum = currYear;
            weekNum = j / 7;
            if ( jan1WeekDay > 4 )
                weekNum--;
        }
    }
    if ( yearNumber )
        *yearNumber = yearNum;
    return weekNum;

}
Ejemplo n.º 10
0
QVector<Event> EventPool::eventsByWeek( const QDate date )
{
    QDate firstOfRange = date;
    // @fixme: explicit week start
    firstOfRange = firstOfRange.addDays( 1 - firstOfRange.dayOfWeek() );
    QDate lastOfRange = firstOfRange.addDays( 6 );

    QVector<Event> events = m_eventMap.value( date.year() );
    // load other years, if we overlap a year-boundary
    if( firstOfRange.year() < date.year() )
        events.append( m_eventMap.value( firstOfRange.year() ) );
    if( lastOfRange.year() > date.year() )
        events.append( m_eventMap.value( lastOfRange.year() ) );

    QVector<Event> eventsWeeks;
    for( const Event e : events )
    {
        if( e.m_endDt.date() >= firstOfRange and e.m_startDt.date() <= lastOfRange )
            eventsWeeks.append( e );
    }
    return eventsWeeks;
}
Ejemplo n.º 11
0
QString QMailTimeStampPrivate::toString(QMailTimeStamp::OutputFormat format) const
{
    // We can't use QDateTime to provide day and month names, since they may get localized into UTF-8
    static const char Days[] = "MonTueWedThuFriSatSun";
    static const char Months[] = "JanFebMarAprMayJunJulAugSepOctNovDec";

    if (time.isNull() || !time.isValid())
        return QString();

    QString result;

    QDateTime originalTime = time.addSecs( utcOffset );
    QDate originalDate = originalTime.date();

    int hOffset = utcOffset / 3600;
    int mOffset = ( abs(utcOffset) - abs(hOffset * 3600) ) / 60;

    if (format == QMailTimeStamp::Rfc2822) {
        result = QString( originalTime.toString( "%1, d %2 yyyy hh:mm:ss %3" ) );
        result = result.arg( QString::fromAscii( Days + ( originalDate.dayOfWeek() - 1 ) * 3, 3 ) );
        result = result.arg( QString::fromAscii( Months + ( originalDate.month() - 1 ) * 3, 3 ) );
        result = result.arg( QString().sprintf( "%+.2d%.2d", hOffset, mOffset ) );
    } else if (format == QMailTimeStamp::Rfc3501) {
        result = QString( originalTime.toString( "dd-%1-yyyy hh:mm:ss %2" ) );
        result = result.arg( QString::fromAscii( Months + ( originalDate.month() - 1 ) * 3, 3 ) );
        result = result.arg( QString().sprintf( "%+.2d%.2d", hOffset, mOffset ) );

        // The day number should be space-padded
        if (result[0] == '0') {
            result[0] = ' ';
        }
    } else if (format == QMailTimeStamp::Rfc3339) {
        result = QString( originalTime.toString( "yyyy-MM-ddThh:mm:ss%1" ) );
        result = result.arg( utcOffset == 0 ? QString("Z") : QString().sprintf( "%+.2d:%.2d", hOffset, mOffset ) );
    }

    return result;
}
Ejemplo n.º 12
0
// Function: WEEKDAY
Value func_weekday(valVector args, ValueCalc *calc, FuncExtra *)
{
    Value v(calc->conv()->asDate(args[0]));
    if (v.isError()) return v;
    QDate date = v.asDate(calc->settings());
    int method = 1;
    if (args.count() == 2)
        method = calc->conv()->asInteger(args[1]).asInteger();

    if (method < 1 || method > 3)
        return Value::errorVALUE();

    int result = date.dayOfWeek();

    if (method == 3)
        --result;
    else if (method == 1) {
        ++result;
        if (result > 7) result = result % 7;
    }

    return Value(result);
}
Ejemplo n.º 13
0
void DateBookWeekLstHeader::setDate(const QDate &d) {
    int year,week,dayofweek;
    date=d;
    dayofweek=d.dayOfWeek();
    if(bStartOnMonday)
        dayofweek--;
    else if( dayofweek == 7 )
        /* we already have the right day -7 would lead to the same week */
        dayofweek = 0;

    date=date.addDays(-dayofweek);

    View::calcWeek(date,week,year,bStartOnMonday);
    QDate start=date;
    QDate stop=start.addDays(6);
    labelDate->setText( QString::number(start.day()) + "." +
            Calendar::nameOfMonth( start.month() ) + "-" +
            QString::number(stop.day()) + "." +
                                                Calendar::nameOfMonth( stop.month()) +" ("+
            tr("w")+":"+QString::number( week ) +")");
    date = d; // bugfix: 0001126 - date has to be the selected date, not monday!
    emit dateChanged(date);
}
Ejemplo n.º 14
0
QString Jalali::currentDayName()
{
    QDate currentDayName;
    currentDayName = QDate::currentDate ();

    QString dayName;
    switch ( currentDayName.dayOfWeek ()) {
    case 1: dayName = QString(trUtf8 ("دوشنبه"));
        break;
    case 2: dayName =  QString(trUtf8 ("سه‌شنبه"));
        break;
    case 3: dayName = QString(trUtf8 ("چهارشنبه"));
        break;
    case 4: dayName =  QString(trUtf8 ("پنج‌شنبه"));
        break;
    case 5: dayName = QString(trUtf8 ("جمعه"));
        break;
    case 6: dayName =  QString(trUtf8 ("شنبه"));
        break;
    case 7: dayName = QString(trUtf8 ("یکشنبه"));
        break;
    }
    return dayName;
}
Ejemplo n.º 15
0
void TimeAnalysisWidget::loadLowAndHighData(std::string filename)
{
    std::string basename = filename.substr(0, filename.find_last_of('.'));    
    _highPoints.load(basename + ".high");

    //_lowPoints.load(basename + ".low");
    //_lowPoints.load(basename + ".low_normalized_cols");
//    _lowPoints.load(basename + ".low_normalized_rows");
    _lowPoints.load(basename + ".low_standarised");
    //_lowPoints.load(basename + ".low_unnormalized");

    // adding default scalars
    Scalar *noneScalar = addScalar("None");
    noneScalar->labels().push_back("None");

    Scalar *dayScalar = addScalar("Day");
    for (int i=0; i<7; ++i)
        dayScalar->labels().push_back(QDate::longDayName(i+1).toStdString());

    Scalar *wend_wdayScalar = addScalar("Weekend/Weekdays");
    wend_wdayScalar->labels().push_back("Weekdays");
    wend_wdayScalar->labels().push_back("Weekends");

    for (int i=0; i<_lowPoints.numPoints(); ++i) {
        Point *lp = _lowPoints.data()[i];
        Point *hp = _highPoints.data()[i];

        QDate d = lp->getDate();

        lp->setScalarValue(noneScalar, 0);
        lp->setScalarValue(dayScalar, d.dayOfWeek()-1);
        lp->setScalarValue(wend_wdayScalar, d.dayOfWeek()==6||d.dayOfWeek()==7);

        hp->setScalarValue(noneScalar, 0);
        hp->setScalarValue(dayScalar, d.dayOfWeek());
        hp->setScalarValue(wend_wdayScalar, d.dayOfWeek()==6||d.dayOfWeek()==7);
    }
}
Ejemplo n.º 16
0
/* This writes a TNEF property to the file.
 *
 * A TNEF property has a 1 byte type (LVL_MESSAGE or LVL_ATTACHMENT),
 * a 4 byte type/tag, a 4 byte length, the data and finally the checksum.
 *
 * The checksum is a 16 byte int with all bytes in the data added.
 */
bool KTNEFWriter::writeProperty(QDataStream &stream, int &bytes, int tag)
{
    QMap<int, KTNEFProperty *> &properties = mData->properties.properties();
    QMap<int, KTNEFProperty *>::Iterator it = properties.find(tag);

    if(it == properties.end())
        return false;

    KTNEFProperty *property = *it;

    Q_UINT32 i;
    Q_UINT16 checksum = 0;
    QValueList<QVariant> list;
    QString s;
    QCString cs, cs2;
    QDateTime dt;
    QDate date;
    QTime time;
    switch(tag)
    {
        case attMSGSTATUS:
            // Q_UINT8
            i = property->value().toUInt() & 0xff;
            checksum = i;

            stream << (Q_UINT8)LVL_MESSAGE;
            stream << mergeTagAndType(tag, property->type());
            stream << (Q_UINT32)1;
            stream << (Q_UINT8)i;

            bytes += 10;
            break;

        case attMSGPRIORITY:
        case attREQUESTRES:
            // Q_UINT16
            i = property->value().toUInt() & 0xffff;
            addToChecksum(i, checksum);

            stream << (Q_UINT8)LVL_MESSAGE;
            stream << mergeTagAndType(tag, property->type());
            stream << (Q_UINT32)2;
            stream << (Q_UINT16)i;

            bytes += 11;
            break;

        case attTNEFVERSION:
            // Q_UINT32
            i = property->value().toUInt();
            addToChecksum(i, checksum);

            stream << (Q_UINT8)LVL_MESSAGE;
            stream << mergeTagAndType(tag, property->type());
            stream << (Q_UINT32)4;
            stream << (Q_UINT32)i;

            bytes += 13;
            break;

        case attOEMCODEPAGE:
            // 2 Q_UINT32
            list = property->value().toList();
            assert(list.count() == 2);

            stream << (Q_UINT8)LVL_MESSAGE;
            stream << mergeTagAndType(tag, property->type());
            stream << (Q_UINT32)8;

            i = list[0].toInt();
            addToChecksum(i, checksum);
            stream << (Q_UINT32)i;
            i = list[1].toInt();
            addToChecksum(i, checksum);
            stream << (Q_UINT32)i;

            bytes += 17;
            break;

        case attMSGCLASS:
        case attSUBJECT:
        case attBODY:
        case attMSGID:
            // QCString
            cs = property->value().toString().local8Bit();
            addToChecksum(cs, checksum);

            stream << (Q_UINT8)LVL_MESSAGE;
            stream << mergeTagAndType(tag, property->type());
            stream << (Q_UINT32)cs.length() + 1;
            writeCString(stream, cs);

            bytes += 9 + cs.length() + 1;
            break;

        case attFROM:
            // 2 QString encoded to a TRP structure
            list = property->value().toList();
            assert(list.count() == 2);

            cs = list[0].toString().local8Bit();                       // Name
            cs2 = (QString("smtp:") + list[1].toString()).local8Bit(); // Email address
            i = 18 + cs.length() + cs2.length(); // 2 * sizof(TRP) + strings + 2x'\0'

            stream << (Q_UINT8)LVL_MESSAGE;
            stream << mergeTagAndType(tag, property->type());
            stream << (Q_UINT32)i;

            // The stream has to be aligned to 4 bytes for the strings
            // TODO: Or does it? Looks like Outlook doesn't do this
            // bytes += 17;
            // Write the first TRP structure
            stream << (Q_UINT16)4;                 // trpidOneOff
            stream << (Q_UINT16)i;                 // totalsize
            stream << (Q_UINT16)(cs.length() + 1); // sizeof name
            stream << (Q_UINT16)(cs2.length() + 1); // sizeof address

            // if ( bytes % 4 != 0 )
            // Align the buffer

            // Write the strings
            writeCString(stream, cs);
            writeCString(stream, cs2);

            // Write the empty padding TRP structure (just zeroes)
            stream << (Q_UINT32)0 << (Q_UINT32)0;

            addToChecksum(4, checksum);
            addToChecksum(i, checksum);
            addToChecksum(cs.length() + 1, checksum);
            addToChecksum(cs2.length() + 1, checksum);
            addToChecksum(cs, checksum);
            addToChecksum(cs2, checksum);

            bytes += 10;
            break;

        case attDATESENT:
        case attDATERECD:
        case attDATEMODIFIED:
            // QDateTime
            dt = property->value().toDateTime();
            time = dt.time();
            date = dt.date();

            stream << (Q_UINT8)LVL_MESSAGE;
            stream << mergeTagAndType(tag, property->type());
            stream << (Q_UINT32)14;

            i = (Q_UINT16)date.year();
            addToChecksum(i, checksum);
            stream << (Q_UINT16)i;
            i = (Q_UINT16)date.month();
            addToChecksum(i, checksum);
            stream << (Q_UINT16)i;
            i = (Q_UINT16)date.day();
            addToChecksum(i, checksum);
            stream << (Q_UINT16)i;
            i = (Q_UINT16)time.hour();
            addToChecksum(i, checksum);
            stream << (Q_UINT16)i;
            i = (Q_UINT16)time.minute();
            addToChecksum(i, checksum);
            stream << (Q_UINT16)i;
            i = (Q_UINT16)time.second();
            addToChecksum(i, checksum);
            stream << (Q_UINT16)i;
            i = (Q_UINT16)date.dayOfWeek();
            addToChecksum(i, checksum);
            stream << (Q_UINT16)i;
            break;
        /*
          case attMSGSTATUS:
            {
              Q_UINT8 c;
              Q_UINT32 flag = 0;
              if ( c & fmsRead ) flag |= MSGFLAG_READ;
              if ( !( c & fmsModified ) ) flag |= MSGFLAG_UNMODIFIED;
              if ( c & fmsSubmitted ) flag |= MSGFLAG_SUBMIT;
              if ( c & fmsHasAttach ) flag |= MSGFLAG_HASATTACH;
              if ( c & fmsLocal ) flag |= MSGFLAG_UNSENT;
              d->stream_ >> c;

              i = property->value().toUInt();
              stream << (Q_UINT8)LVL_MESSAGE;
              stream << (Q_UINT32)type;
              stream << (Q_UINT32)2;
              stream << (Q_UINT8)i;
              addToChecksum( i, checksum );
              // from reader: d->message_->addProperty( 0x0E07, MAPI_TYPE_ULONG, flag );
            }
            kdDebug() << "Message Status" << " (length=" << i2 << ")" << endl;
            break;
        */

        default:
            kdDebug() << "Unknown TNEF tag: " << tag << endl;
            return false;
    }

    stream << (Q_UINT16)checksum;
    return true;
}
Ejemplo n.º 17
0
QString CrCalendar::generateRooms(CalendarData::RoomOrCoach what) {
    QString str;

    QString title;
    trainingRoomMap trainingMap;
    if(what == CalendarData::room) {
        title = "Školiaca miestnosť";
        trainingMap = _calendarData._trainingRooms;
    } else if(what == CalendarData::coach) {
        title = "Inštruktor";
        trainingMap = _calendarData._trainingCoach;
    }

    str += "<tr>";
    //str += "<td></td><td></td>";
    str += "<td colspan=\"4\" class=\""+Cell::getCssClassAsString(Cell::group_title)+"\">" + title +"</td>";
    //str += "<td> <div class=\""+Cell::getCssClassAsString(Cell::group_title)+"\">" + title +"</div></td>";
    //str += "<td></td>";

    str += "<td colspan=\" "+ QString::number(_dateFirst.daysTo(_dateLast)+1) +"\"></td>";

    str += "</tr>";


    int counter = 1;

    trainingRoomMap::iterator room = trainingMap.begin();
    while (room != trainingMap.end() ) {

        Cell cellTitle;
        Cell cell;
        cellTitle.addCssClass(Cell::room_title);
        cellTitle.addText(room->title());
        str += "<tr";

        if(counter % 3 == 0) {
            cell.addCssClass(Cell::tr_highlight);
        }

        if(room == --trainingMap.end()) {
            cell.addCssClass(Cell::tr_end);

        }
        str += cell.getCssClasses();
         str += ">";

        //add serial number
         str += "<td class=\""+Cell::getCssClassAsString(Cell::event_serial_number)+"\">"+ QString::number(counter) +"</td>";
         //add department
         str += "<td></td>\n";

         //add room title
         str += "<td><div "+ cellTitle.getCssClasses()+ ">";
         str += cellTitle.text();
         str += "</div></td>\n";

         //add color cell
         str += "<td class=\""+getClassNameOfRow(counter,what)+"\">&nbsp&nbsp</td>\n";

         //add rooms line
         for(QDate daysIterator = _dateFirst; daysIterator <= _dateLast; daysIterator = daysIterator.addDays(1)) {
             Cell cellBody;

             if(daysIterator.dayOfWeek() == Qt::Saturday
                 || daysIterator.dayOfWeek() == Qt::Sunday) {

                 cellBody.addCssClass(Cell::non_work_day);
             }

             if(room->isOccupied(daysIterator)) {
                 cellBody.addCssClass(Cell::event_day);
             }

             str += "<td ";

             if(cellBody.isClass(Cell::event_day)) {
                 str += cellBody.getCssClasses(getClassNameOfRow(counter,what));
             } else {
                 str += cellBody.getCssClasses();
             }
             str += " >";
             str += "</td>\n";
         }
         str += "</tr>\n";


        counter++;
        room++;
    }

    return str;
}
Ejemplo n.º 18
0
void CSV::createMainPage ()
{
  setCaption(tr("CSV Quotes"));

  QString s = "new";
  QString s2 = tr("New Rule");
  toolbar->addButton(s, newchart, s2);
  QObject::connect(toolbar->getButton(s), SIGNAL(clicked()), this, SLOT(newRule()));

  s = "edit";
  s2 = tr("Edit Rule");
  toolbar->addButton(s, edit, s2);
  QObject::connect(toolbar->getButton(s), SIGNAL(clicked()), this, SLOT(editRule()));

  s = "delete";
  s2 = tr("Delete Rule");
  toolbar->addButton(s, deleteitem, s2);
  QObject::connect(toolbar->getButton(s), SIGNAL(clicked()), this, SLOT(deleteRule()));

  QLabel *label = new QLabel(tr("Rule"), baseWidget);
  grid->addWidget(label, 0, 0);

  ruleCombo = new QComboBox(baseWidget);
  updateRules();
  grid->addWidget(ruleCombo, 0, 1);

  label = new QLabel(tr("Input"), baseWidget);
  grid->addWidget(label, 1, 0);

  QStringList l;
  file = new FileButton(baseWidget, l, lastPath);
  grid->addWidget(file, 1, 1);

  label = new QLabel(tr("Symbol"), baseWidget);
  grid->addWidget(label, 2, 0);

  symbol = new QLineEdit(baseWidget);
  grid->addWidget(symbol, 2, 1);

  label = new QLabel(tr("Auto Reload"), baseWidget);
  grid->addWidget(label, 3, 0);

  minutes = new QSpinBox(baseWidget);
  minutes->setMinValue(0);
  minutes->setMaxValue(99);
  minutes->setLineStep(1);
  QObject::connect(minutes, SIGNAL(valueChanged(int)), this, SLOT(reloadTimerChanged(int)));
  grid->addWidget(minutes, 3, 1);

  dateRange = new QCheckBox(tr("Select Date Range"), baseWidget);
  QObject::connect(dateRange, SIGNAL(toggled(bool)), this, SLOT(dateRangeChanged(bool)));
  grid->addWidget(dateRange, 5, 0);

  label = new QLabel(tr("Date Start"), baseWidget);
  grid->addWidget(label, 6, 0);

  sdate = new Q3DateEdit(QDate::currentDate(), baseWidget);
  sdate->setAutoAdvance(TRUE);
  sdate->setOrder(Q3DateEdit::YMD);
  grid->addWidget(sdate, 6, 1);

  label = new QLabel(tr("Date End"), baseWidget);
  grid->addWidget(label, 7, 0);

  edate = new Q3DateEdit(QDate::currentDate(), baseWidget);
  edate->setAutoAdvance(TRUE);
  edate->setOrder(Q3DateEdit::YMD);
  grid->addWidget(edate, 7, 1);

  // set the default end date
  QDate dt = QDate::currentDate();
  if (dt.dayOfWeek() == 6)
    dt = dt.addDays(-1);
  else
  {
    if (dt.dayOfWeek() == 7)
      dt = dt.addDays(-2);
  }
  edate->setDate(dt);
  sdate->setDate(dt);
}
Ejemplo n.º 19
0
void CalendarWidget::calculateAndDrawMonth(int j_y, int j_m, int j_d)
{
    monthPixmap = QPixmap(this->size());

    //Must be done.
    //`Qt::transparent` is equivalent to `QColor::fromRgb(0,0,0,0)` or `QColor::fromRgba(0)`.
    //We could also have used `palette().color(QPalette::Window)`.
    monthPixmap.fill(Qt::transparent);

    QPainter p(&monthPixmap);
    QPen blackPen(QColor(0, 0, 0));
    QPen grayPen(QColor(192, 192, 192));
    QPen blueThickPen(QColor(0, 0, 255), 2);

    p.setPen(blackPen);

    int hUnit = this->width() / 7;
    int vUnit = this->height() / 7;

    QString title = Ct::Date::PersianDate::nameOfMonth(j_m) + " " + QString::number(j_y);
    QRect titleRect(0, 0, this->width(), vUnit);
    titleRect.adjust(1, 1, -1, -1);
    p.fillRect(titleRect, QColor(64, 128, 255));
    QFont boldFont = this->font();
    boldFont.setBold(true);
    p.setFont(boldFont);
    p.drawText(titleRect, Qt::AlignCenter, title);

    for (int i = 0; i < 7; i++)
    {
        QRect cellRect((6 - i) * hUnit, vUnit, hUnit, vUnit);
        cellRect.adjust(1, 1, -1, -1);
        if (i == 6)
            p.fillRect(cellRect, QColor(96, 160, 255));
        else
            p.fillRect(cellRect, QColor(128, 192, 255));
        p.drawText(cellRect, Qt::AlignCenter, Ct::Date::PersianDate::nameOfPersianWeekDay(i + 1));

        for (int j = 0; j < 7; j++)
            datestamps[j][i] = 0;
    }

    QDate firstDayOfJalaliMonth;
    Ct::Date::PersianDate::JalaliToGregorian(firstDayOfJalaliMonth, j_y, j_m, 1);

    //Without the QTime of 12 P.M, we got problems on 26/27 Esfand 1391 = 16/17 March 2013:
    //  Both shows the same date! This was on Win7. On WinXP it was on the same month at different
    //  days and in linux I did not test.
    QDateTime dateStamp(firstDayOfJalaliMonth, QTime(12, 0, 0));

    int hPos = 0;
    int vPos = 2;

    int mapWeekStartDayFromMondayToSaturday[] = { 0, 3, 4, 5, 6, 7, 1, 2 };
    int PersianWeekStartDay = mapWeekStartDayFromMondayToSaturday[firstDayOfJalaliMonth.dayOfWeek()];
    hPos = PersianWeekStartDay - 1;

    int modFridays = (8 - PersianWeekStartDay) % 7;

    int jalaliMonthDayCount = Ct::Date::PersianDate::numberOfDaysInJalaliMonth(j_y, j_m);

    QFont smallEnglishFont("Tahoma", 8, QFont::Bold);
    for (int i = 1; i <= jalaliMonthDayCount; i++)
    {
        QRect cellRect((6 - hPos) * hUnit, vPos * vUnit, hUnit, vUnit);
        cellRect.adjust(1, 1, -1, -1);
        if (i % 7 == modFridays)
            p.fillRect(cellRect, QColor(128, 192, 255));
        else
            p.fillRect(cellRect, Qt::white);
        if (i == j_d) //Today
        {
            p.setPen(blueThickPen);
            p.drawRect(cellRect);
        }

        //Draw the Gregorian number FIRST so that it goes lower than the Persian day in high-DPI.
        if (settings.showGregorianDates)
        {
            p.setPen(grayPen);
            p.setFont(smallEnglishFont);

            QString dayText = "";
            //In case either Persian or Gregorian day is 1, we add the short month name (MMM). Since
            //  in Persian locale the month name is localized, we also add space before it to have
            //  some right margin.
            if (i == 1 || dateStamp.date().day() == 1)
                dayText = " " + dateStamp.date().toString("MMM") + " ";
            //We add space after the day because some right margin is always useful! Of course this space
            //  is used if a localized month name wasn't added to the day number.
            dayText += QString::number(dateStamp.date().day()) + " ";

            p.drawText(cellRect, Qt::AlignRight | Qt::AlignBottom, dayText);
        }

        p.setPen(blackPen);
        p.setFont(this->font());
        p.drawText(cellRect, Qt::AlignCenter, QString::number(i));

        //FIRST save the datestamps
        datestamps[(6 - hPos)][vPos] = dateStamp.toMSecsSinceEpoch();
        dateStamp = dateStamp.addDays(1);

        //THEN 'increase' hPos/vPos
        hPos++;
        if (hPos == 7)
        {
            hPos = 0;
            vPos++;

            if (vPos == 7)
                vPos = 2; //Draw the excess 30th and 31th day in the top row.
        }
    }
}
Ejemplo n.º 20
0
void Calender::setupView(int y, int m)
{
    CalenderDay *cDay = NULL;
    QColor white(255, 255, 255);
    QColor gray(240, 240, 240);
    QString dayNrStr;
    QDate *date = new QDate(y, m, 1);

    int i, j, k, squareNr, dayNr, row, col;

    char *days[] = {
      "Monday",
      "Tuesday",
      "Wednesday",
      "Thursday",
      "Friday",
      "Saturday",
      "Sunday"
    };

    i = 0;
    k = 0;
    j = 7;
    squareNr = 1;
    dayNr = 1;
    nrOfDays = date->daysInMonth();
    firstDay = date->dayOfWeek();
    year = y;
    month = m;
    
    if (weekStarts == SUNDAY) {
      horizontalHeader()->setLabel(0, tr(days[6]));
      firstDay += 1;
      i = 1;
    }

    for (; i < j; i++, k++) {
      horizontalHeader()->setLabel(i, tr(days[k]));
    }
 
    for (row = 0; row < numRows(); row++) {
      for (col = 0; col < numCols(); col++) {
 if ((squareNr >= firstDay) && (dayNr <= nrOfDays)) {
   if ((dayLeadingZero == true) && (dayNr <= 9)) {
     dayNrStr += "0";
   }
   dayNrStr += QString::number(dayNr);
   cDay = new CalenderDay(this, QTableItem::Never, white, dayNrStr);
   dayNrStr = "";
   cDay->setDayNr(dayNr++);
   
   setItem(row, col, cDay);
 } else {
   cDay = new CalenderDay(this, QTableItem::Never, gray);
   setItem(row, col, cDay);
 }
 //setRowHeight(row, 80);    //Inte nödv. då col och rows är stretchatble
 ++squareNr;
      }
    }
}
Ejemplo n.º 21
0
void 
DateSettingsEdit::setDateSettings()
{
    if (active) return;

    // first lets disable everything
    active = true;
    fromDateEdit->setEnabled(false);
    toDateEdit->setEnabled(false);
    startDateEdit->setEnabled(false);
    thisperiod->setEnabled(false);
    prevperiod->setEnabled(false);
    lastn->setEnabled(false);
    lastnx->setEnabled(false);

    // the date selection types have changed
    if (radioSelected->isChecked()) {

        // current selection
        emit useStandardRange();

    } else if (radioCustom->isChecked()) {

        // between x and y
        fromDateEdit->setEnabled(true);
        toDateEdit->setEnabled(true);

        // set date range using custom values
        emit useCustomRange(DateRange(fromDateEdit->date(), toDateEdit->date()));

    } else if (radioToday->isChecked()) {

        // current selected thru to today
        emit useThruToday();

    } else if (radioLast->isChecked()) {

        // last n 'weeks etc'
        lastn->setEnabled(true);
        lastnx->setEnabled(true);

        QDate from;
        QDate today = QDate::currentDate();

        // calculate range up to today...
        switch(lastnx->currentIndex()) {
            case 0 : // days
                from = today.addDays(lastn->value() * -1);
                break;

            case 1 :  // weeks
                from = today.addDays(lastn->value() * -7);
                break;

            case 2 :  // months
                from = today.addMonths(lastn->value() * -1);
                break;

            case 3 : // years
                from = today.addYears(lastn->value() * -1);
                break;
        }

        emit useCustomRange(DateRange(from, today));

    } else if (radioFrom->isChecked()) {

        // from date - today
        startDateEdit->setEnabled(true);
        emit useCustomRange(DateRange(startDateEdit->date(), QDate::currentDate()));

    } else if (radioThis->isChecked()) {

        thisperiod->setEnabled(true);
        prevperiod->setEnabled(true);

        QDate today = QDate::currentDate();
        QDate from, to;

        switch(thisperiod->currentIndex()) {

        case 0 : // weeks
            {
                int dow = today.dayOfWeek(); // 1-7, where 1=monday
                from = today.addDays(-1 * (dow-1));
                to = from.addDays(6);
                // prevperiods
                from = from.addDays(prevperiod->value() * -7);
                to = to.addDays(prevperiod->value() * -7);
            }
            break;

        case 1 : // months
            from = QDate(today.year(), today.month(), 1);
            to = from.addMonths(1).addDays(-1);
            from = from.addMonths(prevperiod->value() * -1);
            to = to.addMonths(prevperiod->value() * -1);
            break;

        case 2 : // years
            from = QDate(today.year(), 1, 1);
            to = from.addYears(1).addDays(-1);
            from = from.addYears(prevperiod->value() * -1);
            to = to.addYears(prevperiod->value() * -1);
            break;

        }
        emit useCustomRange(DateRange(from, to));
    }
    active = false;
}
Ejemplo n.º 22
0
// Function: WORKDAY
//
// - negative days count backwards
// - if holidays is not an array it is only added to days (neg. are not allowed)
//
Value func_workday(valVector args, ValueCalc *calc, FuncExtra *e)
{
    Value v(calc->conv()->asDate(args[0]));

    if (v.isError()) return v;
    QDate startdate = v.asDate(calc->settings());

    if (!startdate.isValid())
        return Value::errorVALUE();

    //
    // vars
    //
    int days = calc->conv()->asInteger(args[1]).asInteger();

    QDate date0 = calc->settings()->referenceDate();   // referenceDate
    QDate enddate = startdate;                    // enddate
    valVector holidays;                           // stores holidays
    int sign = 1;                                 // sign 1 = forward, -1 = backward

    if (days < 0) {
        // change sign and set count to ccw
        days = days * -1;
        sign = -1;
    }

    //
    // check for holidays
    //
    if (args.count() > 2) {
        if (args[2].type() == Value::Array) { // parameter is array
            unsigned int row1, col1, rows, cols;

            row1 = e->ranges[2].row1;
            col1 = e->ranges[2].col1;
            rows = e->ranges[2].row2 - row1 + 1;
            cols = e->ranges[2].col2 - col1 + 1;

            Value holiargs = args[2];

            for (unsigned r = 0; r < rows; ++r) {
                for (unsigned c = 0; c < cols; ++c) {
                    // only append if element is a valid date
                    if (!holiargs.element(c + col1, r + row1).isEmpty()) {
                        Value v(calc->conv()->asDate(holiargs.element(c + col1, r + row1)));
                        if (v.isError())
                            return Value::errorVALUE();

                        if (v.asDate(calc->settings()).isValid())
                            holidays.append(v);
                    }
                } // cols
            }   // rows
        } else {
            // no array parameter
            if (args[2].isString()) {
                // isString
                Value v(calc->conv()->asDate(args[2]));
                if (v.isError())
                    return Value::errorVALUE();

                if (v.asDate(calc->settings()).isValid())
                    holidays.append(v);
            } else {
                // isNumber
                int hdays = calc->conv()->asInteger(args[2]).asInteger();

                if (hdays < 0)
                    return Value::errorVALUE();
                days = days + hdays;
            }
        }
    }

    //
    // count days
    //
    while (days) {
        // exclude weekends and holidays
        do {
            enddate = enddate.addDays(1 * sign);
        } while (enddate.dayOfWeek() > 5 || holidays.contains(Value(date0.daysTo(enddate))));

        days--;
    }

    return Value(enddate, calc->settings());
}
EmploiDuTemps::EmploiDuTemps(QDate d, QWidget *parent) :
    QDialog(parent), lundi(d),
    ui(new Ui::EmploiDuTemps)
{
    ui->setupUi(this);
    ui->stackedWidget->setHidden(true);

    ui->labelNumero->setText(QDate::shortDayName(d.dayOfWeek())+d.toString(Qt::SystemLocaleShortDate)+" au "+QDate::shortDayName(d.addDays(6).dayOfWeek())+d.addDays(6).toString(Qt::SystemLocaleShortDate));

    ui->tableWidget->setColumnCount(7);
    QStringList jours(QDate::shortDayName(d.dayOfWeek())+d.toString(Qt::SystemLocaleShortDate));
        for (unsigned int i=1; i<7; i++) {
            jours.append((QDate::shortDayName(d.addDays(i).dayOfWeek()))+(d.addDays(i)).toString(Qt::SystemLocaleShortDate));
        }
    ui->tableWidget->setHorizontalHeaderLabels(jours);
    ui->tableWidget->verticalHeader()->setHidden(true);

    unsigned int nbRow =0;
    ui->tableWidget->setRowCount(nbRow);



    QDate jour1(d.year(), d.month(), d.day());
    QDate jour7=d.addDays(7);
    unsigned int prog = 0;


    QBrush coulEvt (QColor(191,117,255));
    QBrush coulTache (QColor(85,255,127));

    for (QDate jour=jour1; jour<jour7; jour = jour.addDays(1)){
            unsigned int nb=0;
            for(QMap<QDateTime, Programmation*>::const_iterator it = ProgrammationManager::getInstance().getProgrammations().cbegin();
                it != ProgrammationManager::getInstance().getProgrammations().cend();
                it++){
                if(it.key().date()== jour){
                    //afficher
                    QTableWidgetItem* item = new QTableWidgetItem;
                    if(it.value()->getEvenement()!=0){
                        item->setWhatsThis(it.value()->getEvenement()->getNom());
                        item->setText((*it)->getTime().toString("HH:mm")+" : "+(*it)->getEvenement()->getNom()+"\n\ndurée : "+(*it)->getDuree().stringDuree()+"\n\n");
                        item->setBackground(coulEvt);
                        prog++;
                    }
                    else if (it.value()->getTache()!=0){
                        item->setWhatsThis(it.value()->getTache()->getId());
                        item->setText((*it)->getTime().toString("HH:mm")+" : "+(*it)->getTache()->getId()+"\n\ndurée : "+(*it)->getDuree().stringDuree()+" \n\n");
                        item->setBackground(coulTache);
                        prog++;
                    }
                    if(nb>=nbRow){
                        nbRow+=5;
                        ui->tableWidget->setRowCount(nbRow);
                    }
                    ui->tableWidget->setItem(nb,(jour.dayOfWeek()-1),item);

                    nb++;
                }
            }

        }


    ui->tableWidget->resizeRowsToContents();
    if(prog==0)
        QMessageBox::information(this, "Message", "Il n'y a pas encore de programmation pour la semaine choisie.");



    QObject::connect(ui->pushButtonFermer, SIGNAL(clicked()),this,SLOT(close()));
    QObject::connect(ui->pushButtonChange, SIGNAL(clicked()),this,SLOT(changeEdt()));
    QObject::connect(ui->tableWidget, SIGNAL(cellClicked(int,int)),this,SLOT(afficheInfos(int, int)));

}
Ejemplo n.º 24
0
/**
 * @brief vygeneruje pracovne aktivity. Nazov pracovnej aktivity je v bunkach.
 * Neberie do uvahy aktive dni => vsetky su aktivne
 * @return
 */
QString CrCalendar::generateWorkActivity() {

    QString returnStr;
    listOfListOfEvents::iterator listOfListIterator;

    for(listOfListIterator = _calendarData._listOfWorkAction.begin(); listOfListIterator != _calendarData._listOfWorkAction.end(); ++listOfListIterator) {
        returnStr += "<tr>";
        returnStr += "<td></td>";
        returnStr += "<td></td>";
        returnStr += "<td></td>";
        returnStr += "<td></td>";

        QDate dayIterator;
        QList<CrEvent>::iterator eventIterator = listOfListIterator->begin();
        //prva udalost

        int colspan = 0;
        for(dayIterator = _dateFirst; dayIterator <= _dateLast; dayIterator = dayIterator.addDays(1)) {

			//qDebug() << QString("%1: %2").arg(eventIterator->title()).arg(eventIterator->dateBegin().toString("dd.MM.yyyy"));

            if( eventIterator != listOfListIterator->end()
                    && dayIterator >= eventIterator->dateBegin()
                    && dayIterator <= eventIterator->dateEnd()) {
                //iteracia cez udalost
                colspan++;

                //posledny den udalosti
                if(dayIterator == eventIterator->dateEnd()
                        || dayIterator == _dateLast) {
                    returnStr += "<td colspan=\""+ QString::number(colspan) +"\"";
                    returnStr += " class=\""+ eventIterator->getClassNameOfId();
                    returnStr += " "+ Cell::getCssClassAsString(Cell::workActivity_cell)+ "\">";
                    returnStr += eventIterator->title();
                    returnStr += "</td>";

                    colspan = 0;
                    eventIterator++;
                }

            //prazdny den
            } else {
                Cell cell;
                if(dayIterator.dayOfWeek() == Qt::Saturday
                    || dayIterator.dayOfWeek() == Qt::Sunday) {

                    cell.addCssClass(Cell::non_work_day);
                }

                returnStr += "<td ";
                returnStr += cell.getCssClasses();
                returnStr += "></td>\n";
            }
        }
        returnStr += "</tr>";

    }

    return returnStr;


}
Ejemplo n.º 25
0
//Open XML file clicked
void TaskList_Main::openClickAction(QString inName, bool clearLists){
    if(inName.trimmed().isEmpty())
        inName = QFileDialog::getOpenFileName(this, tr("Open List File"),
                                                  QDir::currentPath(),
                                                  tr("LIST Files (*.xml)"));
    if(inName.isEmpty())
        return;

    //Open file stream
    QFile in(inName);
    if(!in.open(QFile::ReadOnly| QFile::Text)){
        QMessageBox::warning(this, tr("Open List"),
                             tr("Cannot open file %1:\n%2")
                             .arg(inName).arg(in.errorString()));
        return;
    }

    //If not a template, clear listing
    if(clearLists){
        while(listPane->mainList->count() != 0)
            delListClick();
    }

    //Create the XML document to read in
    QDomDocument doc;
    QString errorMsg;
    int errorLine, errorColumn;
    if(doc.setContent(&in, &errorMsg, &errorLine, &errorColumn)){
        if(parseXML(doc) < 0){
            while(listPane->mainList->count() != 0)
                delListClick();
        }
    }
    else{
        errorMsg.append(" line ");
        errorMsg.append(QString::number(errorLine));
        errorMsg.append(" col ");
        errorMsg.append(QString::number(errorColumn));

        QMessageBox msgBox;
        msgBox.setText(errorMsg.toAscii().data());
        msgBox.setWindowTitle("Erorr parsing XML");
        msgBox.exec();
    }

    //Handle whether it came from template rsc. or from
    //actual user file
    qDebug(inName.toAscii().data());
    if(!inName.contains(":/tmp/xml/"))
        myFileName = inName;
    //If task_week item, sync up next dates for tasks
    else if(inName.contains(":/tmp/xml/task_groceries.xml")){
        QDate currDate = QDate::currentDate();
        qDebug(currDate.toString().toAscii().data());

        QListWidgetItem *listPtr = listPane->mainList->currentItem();
        my_listwidget *taskPtr = notePane->listMap[listPtr];

        for(int task = 0; task < taskPtr->count(); ++task){
            taskPtr->item(task)->setData(34, QVariant(currDate));
            optionPane->itemSelectDataIn(*taskPtr->item(task));
        }

    }
    else if(inName.contains(":/tmp/xml/task_week.xml")){
        QDate currDate = QDate::currentDate();
        qDebug(currDate.toString().toAscii().data());
        while(currDate.dayOfWeek() != 1){
            qDebug("add day");
            currDate = currDate.addDays(1);
            qDebug(currDate.toString().toAscii().data());
        }
        for(int day = listPane->mainList->count()-7; day < listPane->mainList->count(); ++day){
            QListWidgetItem *listPtr = listPane->mainList->item(day);
            my_listwidget *dayPtr = notePane->listMap[listPtr];

            QString newTitle = currDate.toString();
            listPtr->setText(newTitle);

            for(int task = 0; task < dayPtr->count(); ++task){
                dayPtr->item(task)->setData(34, QVariant(currDate));
                optionPane->itemSelectDataIn(*dayPtr->item(task));
            }
            currDate = currDate.addDays(1);
        }
    }
}
Ejemplo n.º 26
0
QString convertTimeDate(const QString &mac_format, const QDateTime &datetime)
{
    QDate date = datetime.date();
    QTime time = datetime.time();
    QString str;
    if (mac_format.contains('%'))
    {
        const QChar *chars = mac_format.constData();
        bool is_percent = false;
        int length = 0;
        bool error = false;
        while ((*chars).unicode() && !error)
        {
            if (is_percent)
            {
                is_percent = false;
                switch ((*chars).unicode())
                {
                case L'%':
                    str += *chars;
                    break;
                case L'a':
                    appendStr(str, QDate::shortDayName(date.dayOfWeek()), length);
                    break;
                case L'A':
                    appendStr(str, QDate::longDayName(date.dayOfWeek()), length);
                    break;
                case L'b':
                    appendStr(str, QDate::shortMonthName(date.day()), length);
                    break;
                case L'B':
                    appendStr(str, QDate::longMonthName(date.day()), length);
                    break;
                case L'c':
                    appendStr(str, QLocale::system().toString(datetime), length);
                    break;
                case L'd':
                    appendInt(str, date.day(), length > 0 ? length : 2);
                    break;
                case L'e':
                    appendInt(str, date.day(), length);
                    break;
                case L'F':
                    appendInt(str, time.msec(), length > 0 ? length : 3);
                    break;
                case L'H':
                    appendInt(str, time.hour(), length > 0 ? length : 2);
                    break;
                case L'I':
                    appendInt(str, time.hour() % 12, length > 0 ? length : 2);
                    break;
                case L'j':
                    appendInt(str, date.dayOfYear(), length > 0 ? length : 3);
                    break;
                case L'm':
                    appendInt(str, date.month(), length > 0 ? length : 2);
                    break;
                case L'M':
                    appendInt(str, time.minute(), length > 0 ? length : 2);
                    break;
                case L'p':
                    appendStr(str, time.hour() < 12 ? "AM" : "PM", length);
                    break;
                case L'S':
                    appendInt(str, time.second(), length > 0 ? length : 2);
                    break;
                case L'w':
                    appendInt(str, date.dayOfWeek(), length);
                    break;
                case L'x':
                    appendStr(str, QLocale::system().toString(date), length);
                    break;
                case L'X':
                    appendStr(str, QLocale::system().toString(time), length);
                    break;
                case L'y':
                    appendInt(str, date.year() % 100, length > 0 ? length : 2);
                    break;
                case L'Y':
                    appendInt(str, date.year(), length > 0 ? length : 4);
                    break;
                case L'Z':
                    // It should be localized, isn't it?..
                    appendStr(str, SystemInfo::instance()->timezone(), length);
                    break;
                case L'z':
                {
                    int offset = SystemInfo::instance()->timezoneOffset();
                    appendInt(str, (offset/60)*100 + offset%60, length > 0 ? length : 4);
                    break;
                }
                default:
                    if ((*chars).isDigit())
                    {
                        is_percent = true;
                        length *= 10;
                        length += (*chars).digitValue();
                    }
                    else
                        error = true;
                }
            }
            else if (*chars == '%')
            {
                length = 0;
                is_percent = true;
            }
            else
                str += *chars;
            chars++;
        }
        if (!error)
            return str;

        str.clear();
    }

    WeekDate week_date(date);
    QChar last;
    QChar cur;
    int length = 0;
    bool quote = false;
    const QChar *chars = mac_format.constData();
    forever
    {
        cur = *chars;
        if (cur == '\'')
        {
            if (*(chars+1) == '\'')
            {
                chars++;
                str += cur;
            }
            else
            {
                if (!quote)
                    finishStr(str, week_date, date, time, last, length);
                quote = !quote;
            }
            length = 0;
        }
        else if (quote)
            str += cur;
        else
        {
            if (cur == last)
                length++;
            else
            {
                finishStr(str, week_date, date, time, last, length);
                length = 1;
            }
        }
        if (!chars->unicode())
            break;

        last = cur;
        chars++;
    }
    return str;
}
Ejemplo n.º 27
0
// http://unicode.org/reports/tr35/tr35-6.html#Date_Format_Patterns
static void finishStr(QString &str, const WeekDate &week_date, const QDate &date, const QTime &time, QChar c, int length)
{
    if (length <= 0)
        return;

    switch (c.unicode())
    {
    case L'G':
    {
        bool ad = date.year() > 0;
        if (length < 4)
            str += ad ? "AD" : "BC";
        else if (length == 4)
            str += ad ? "Anno Domini" : "Before Christ";
        else
            str += ad ? "A" : "B";
        break;
    }
    case L'y':
        if (length == 2)
            appendInt(str, date.year() % 100, 2);
        else
            appendInt(str, date.year(), length);
        break;
    case L'Y':
        appendInt(str, week_date.year(), length);
        break;
    case L'u':
    {
        int year = date.year();
        if (year < 0)
            year++;
        appendInt(str, date.year(), length);
        break;
    }
    case L'q':
    case L'Q':
    {
        int q = (date.month() + 2) / 3;
        if (length < 3)
            appendInt(str, q, length);
        else if (length == 3)
        {
            str += 'Q';
            str += QString::number(q);
        }
        else
        {
            switch (q)
            {
            case 1:
                str += qApp->translate("AdiumTimeFormatter", "1st quarter");
                break;
            case 2:
                str += qApp->translate("AdiumTimeFormatter", "2nd quarter");
                break;
            case 3:
                str += qApp->translate("AdiumTimeFormatter", "3rd quarter");
                break;
            case 4:
                str += qApp->translate("AdiumTimeFormatter", "4th quarter");
                break;
            default:
                break;
            }
        }
        break;
    }
    case L'M':
    case L'L':
        if (length < 3)
            appendInt(str, date.month(), length);
        else if (length == 3)
            str += QDate::shortMonthName(date.month());
        else if (length == 4)
            str += QDate::longMonthName(date.month());
        else
            str += QDate::shortMonthName(date.month()).at(0);
        break;
    case L'w':
        TRIM_LENGTH(2);
        appendInt(str, length, week_date.week());
        break;
    case L'W':
        while (length-- > 0)
            str += QString::number((date.day() + 6) / 7);
        break;
    case L'd':
        TRIM_LENGTH(2);
        appendInt(str, date.day(), length);
        break;
    case L'D':
        TRIM_LENGTH(3);
        appendInt(str, date.dayOfYear(), length);
        break;
    case L'F':
        while (length-- > 0)
            str += QString::number(1);
        break;
    case L'g':
        appendInt(str, date.toJulianDay(), length);
        break;
    case L'c':
    case L'e':
        if (length < 3)
        {
            appendInt(str, date.dayOfWeek(), length);
            break;
        }
    case L'E':
        if (length < 4)
            str += QDate::shortDayName(date.dayOfWeek());
        else if (length == 4)
            str += QDate::longDayName(date.dayOfWeek());
        else
            str += QDate::shortDayName(date.dayOfWeek()).at(0);
        break;
    case L'a':
        str += time.hour() < 12 ? "AM" : "PM";
        break;
    case L'H':
        TRIM_LENGTH(2);
        appendInt(str, time.hour(), length);
        break;
    case L'h':
        TRIM_LENGTH(2);
        appendInt(str, time.hour() % 12, length);
        break;
    case L'K':
        TRIM_LENGTH(2);
        appendInt(str, time.hour() - 1, length);
        break;
    case L'k':
        TRIM_LENGTH(2);
        appendInt(str, time.hour() % 12 - 1, length);
        break;
    case L'm':
        TRIM_LENGTH(2);
        appendInt(str, time.minute(), length);
        break;
    case L's':
        TRIM_LENGTH(2);
        appendInt(str, time.second(), length);
        break;
    case L'S':
        str += QString::number(time.msec() / 1000.0, 'f', length).section('.', 1);
        break;
    case L'A':
        appendInt(str, QTime(0,0).msecsTo(time), length);
        break;
    case L'v':
    // I don't understand the difference
    case L'z':
        if (length < 4)
            str += SystemInfo::instance()->timezone();
        else
            // There should be localized name, but I don't know how get it
            str += SystemInfo::instance()->timezone();
        break;
    case L'Z':
    {
        if (length == 4)
            str += "GMT";
        int offset = SystemInfo::instance()->timezoneOffset();
        if (offset < 0)
            str += '+';
        else
            str += '-';
        appendInt(str, qAbs((offset/60)*100 + offset%60), 4);
        break;
    }
    default:
        while (length-- > 0)
            str += c;
        break;
    }
}
Ejemplo n.º 28
0
static bool isWorkDay( const QDate& date )
{
    return date.dayOfWeek() != Qt::Saturday && date.dayOfWeek() != Qt::Sunday;
}
Ejemplo n.º 29
0
QDate CalendarCourse::adjustFirstWeek(QDate &start)
{
    if (start.dayOfWeek() == Qt::Saturday || start.dayOfWeek() == Qt::Sunday)//skip weekends
        start = start.addDays((Qt::Sunday - start.dayOfWeek()) + 1);
    return start.addDays(Qt::Sunday - start.dayOfWeek());
}
Ejemplo n.º 30
0
//
// Manage the seasons array
//
void
Seasons::readSeasons()
{
    QFile seasonFile(home.absolutePath() + "/seasons.xml");
    QXmlInputSource source( &seasonFile );
    QXmlSimpleReader xmlReader;
    SeasonParser handler;
    xmlReader.setContentHandler(&handler);
    xmlReader.setErrorHandler(&handler);
    xmlReader.parse( source );
    seasons = handler.getSeasons();

    Season season;
    QDate today = QDate::currentDate();
    QDate eom = QDate(today.year(), today.month(), today.daysInMonth());

    // add Default Date Ranges
    season.setName(tr("All Dates"));
    season.setType(Season::temporary);
    season.setStart(QDate::currentDate().addYears(-50));
    season.setEnd(QDate::currentDate().addYears(50));
    season.setId(QUuid("{00000000-0000-0000-0000-000000000001}"));
    seasons.append(season);

    season.setName(tr("This Year"));
    season.setType(Season::temporary);
    season.setStart(QDate(today.year(), 1,1));
    season.setEnd(QDate(today.year(), 12, 31));
    season.setId(QUuid("{00000000-0000-0000-0000-000000000002}"));
    seasons.append(season);

    season.setName(tr("This Month"));
    season.setType(Season::temporary);
    season.setStart(QDate(today.year(), today.month(),1));
    season.setEnd(eom);
    season.setId(QUuid("{00000000-0000-0000-0000-000000000003}"));
    seasons.append(season);

    season.setName(tr("This Week"));
    season.setType(Season::temporary);
    // from Mon-Sun
    QDate wstart = QDate::currentDate();
    wstart = wstart.addDays(Qt::Monday - wstart.dayOfWeek());
    QDate wend = wstart.addDays(6); // first day + 6 more
    season.setStart(wstart);
    season.setEnd(wend);
    season.setId(QUuid("{00000000-0000-0000-0000-000000000004}"));
    seasons.append(season);

    season.setName(tr("Last 7 days"));
    season.setType(Season::temporary);
    season.setStart(today.addDays(-6)); // today plus previous 6
    season.setEnd(today);
    season.setId(QUuid("{00000000-0000-0000-0000-000000000005}"));
    seasons.append(season);

    season.setName(tr("Last 14 days"));
    season.setType(Season::temporary);
    season.setStart(today.addDays(-13));
    season.setEnd(today);
    season.setId(QUuid("{00000000-0000-0000-0000-000000000006}"));
    seasons.append(season);

    season.setName(tr("Last 21 days"));
    season.setType(Season::temporary);
    season.setStart(today.addDays(-20));
    season.setEnd(today);
    season.setId(QUuid("{00000000-0000-0000-0000-000000000011}"));
    seasons.append(season);

    season.setName(tr("Last 28 days"));
    season.setType(Season::temporary);
    season.setStart(today.addDays(-27));
    season.setEnd(today);
    season.setId(QUuid("{00000000-0000-0000-0000-000000000007}"));
    seasons.append(season);

    season.setName(tr("Last 2 months"));
    season.setType(Season::temporary);
    season.setEnd(today);
    season.setStart(today.addMonths(-2));
    season.setId(QUuid("{00000000-0000-0000-0000-000000000008}"));
    seasons.append(season);

    season.setName(tr("Last 3 months"));
    season.setType(Season::temporary);
    season.setEnd(today);
    season.setStart(today.addMonths(-3));
    season.setId(QUuid("{00000000-0000-0000-0000-000000000011}"));
    seasons.append(season);

    season.setName(tr("Last 6 months"));
    season.setType(Season::temporary);
    season.setEnd(today);
    season.setStart(today.addMonths(-6));
    season.setId(QUuid("{00000000-0000-0000-0000-000000000009}"));
    seasons.append(season);

    season.setName(tr("Last 12 months"));
    season.setType(Season::temporary);
    season.setEnd(today);
    season.setStart(today.addMonths(-12));
    season.setId(QUuid("{00000000-0000-0000-0000-000000000010}"));
    seasons.append(season);

    seasonsChanged(); // signal!
}