Пример #1
1
QDateTime datetimeFromNumber(double num, bool is1904)
{
    if (!is1904 && num > 60)
        num = num - 1;

    qint64 msecs = static_cast<qint64>(num * 1000*60*60*24.0 + 0.5);
    QDateTime epoch(is1904 ? QDate(1904, 1, 1): QDate(1899, 12, 31), QTime(0,0));

    QDateTime dt = epoch.addMSecs(msecs);

#if QT_VERSION >= 0x050200
    // Remove one hour to see whether the date is Daylight
    QDateTime dt2 = dt.addMSecs(-3600);
    if (dt2.isDaylightTime())
        return dt2;
#endif

    return dt;
}
Пример #2
0
static HistoryEntry formatEntry(QByteArray url, QByteArray title, qlonglong prdate)
{
    QDateTime dateTime = QDateTime::fromTime_t(prdate / 1000000);
    dateTime.addMSecs((prdate % 1000000) / 1000);
    HistoryEntry entry(url, dateTime, title);
    return entry;
}
Пример #3
0
/*
  Construct a QCa date time set to the same date/time as an EPICS time stamp
 */
QCaDateTime::QCaDateTime( unsigned long seconds, unsigned long nanoseconds )
{
    qint64 mSec;

    // First calculate mSecs and remaining nSecs
    // Down to the millisecond goes in the Qt base class structure,
    // the remaining nanoseconds are saved in this class
    //
    mSec = nanoseconds / 1000000;
    nSec = nanoseconds % 1000000;

#if (QT_VERSION >= QT_VERSION_CHECK(4, 8, 0))
    // Calc number of mSecs since the epoc.
    // Note, although the EPICS time stamp is in seconds since a base, the method which
    // takes seconds since a base time uses a different base, so an offset is added.
    //
    qint64 mSecsSinceEpoch;
    mSecsSinceEpoch = ((qint64) (seconds + EPICSQtEpocOffset)) * 1000 + mSec;
    setMSecsSinceEpoch (mSecsSinceEpoch);
#else
    // setMSecsSinceEpoch does not exist in older versions.
    //
    QDateTime temp;
    temp.setTime_t( seconds + EPICSQtEpocOffset );
    *this = temp.addMSecs (mSec);
#endif
}
Пример #4
0
void CAdBlock::setScte35StartTime(QDateTime firstAdStartTime)
{
  if (!m_adConfigs.empty())
  {
    CAdConfig firstAd = m_adConfigs.front();
    startB2bTimer(firstAdStartTime.addMSecs(QTime().msecsTo(firstAd.getTotalDuration())));
  }
}
Пример #5
0
QDateTime DataFile::sampleToDate(int sample)
{
	int timeOffset = round(sample/getSamplingFrequency()*1000);

	QDateTime date = getStartDate();
	date = date.addMSecs(timeOffset);

	return date;
}
Пример #6
0
//--------------------------------------------------------------------------------------------------
/// Get list of time step texts (dates)
//--------------------------------------------------------------------------------------------------
void RifEclipseOutputFileTools::timeSteps(ecl_file_type* ecl_file, std::vector<QDateTime>* timeSteps, std::vector<double>* daysSinceSimulationStart)
{
    if (!ecl_file) return;

    CVF_ASSERT(timeSteps && daysSinceSimulationStart);

    timeSteps->clear();
    daysSinceSimulationStart->clear();

    // Get the number of occurrences of the INTEHEAD keyword
    int numINTEHEAD = ecl_file_get_num_named_kw(ecl_file, INTEHEAD_KW);
    
    // Get the number of occurrences of the DOUBHEAD keyword
    int numDOUBHEAD = ecl_file_get_num_named_kw(ecl_file, DOUBHEAD_KW);

    std::vector<double> dayValues(numINTEHEAD, 0.0); // Init fraction to zero

    // Read out fraction of day if number of keywords are identical
    if (numINTEHEAD == numDOUBHEAD)
    {
        for (int i = 0; i < numDOUBHEAD; i++)
        {
            ecl_kw_type* kwDOUBHEAD = ecl_file_iget_named_kw(ecl_file, DOUBHEAD_KW, i);
            if (kwDOUBHEAD)
            {
                dayValues[i] = ecl_kw_iget_double(kwDOUBHEAD, DOUBHEAD_DAYS_INDEX);
            }
        }
    }

    std::set<QDateTime> existingTimesteps;

    for (int i = 0; i < numINTEHEAD; i++)
    {
        ecl_kw_type* kwINTEHEAD = ecl_file_iget_named_kw(ecl_file, INTEHEAD_KW, i);
        CVF_ASSERT(kwINTEHEAD);
        int day = 0;
        int month = 0;
        int year = 0;
        getDayMonthYear(kwINTEHEAD, &day, &month, &year);

        QDateTime reportDateTime = RiaQDateTimeTools::createUtcDateTime(QDate(year, month, day));
        CVF_ASSERT(reportDateTime.isValid());

        double dayValue = dayValues[i];
        double dayFraction = dayValue - cvf::Math::floor(dayValue);
        double milliseconds = dayFraction * 24.0 * 60.0 * 60.0 * 1000.0;

        reportDateTime = reportDateTime.addMSecs(milliseconds);
        if (existingTimesteps.insert(reportDateTime).second)
        {
            timeSteps->push_back(reportDateTime);
            daysSinceSimulationStart->push_back(dayValue);
        }
    }
}
Пример #7
0
  TEST(Time, Verify_46_Hack)
  {
    qint64 MSecsPerDay = 86400000;
    QDateTime epoch = QDateTime::fromString("1970-01-01T00:00:00.000", Qt::ISODate);
    epoch.setTimeSpec(Qt::UTC);

    Time &time = Time::GetInstance();
    time.UseRealTime();

    QDateTime now = time.CurrentTime();
    QDateTime now_46 = QDateTime::currentDateTime().toUTC();

    EXPECT_EQ(now_46.date(), now.date());
    EXPECT_TRUE(qAbs(now_46.time().msecsTo(now.time())) < 100);

    qint64 msecs = time.MSecsSinceEpoch();
    now = QDateTime::currentDateTime().toUTC();
    int days_46 = epoch.date().daysTo(now.date());
    int msecs_46 = epoch.time().msecsTo(now.time());
    qint64 total_msecs_46 = (days_46 * MSecsPerDay) + msecs_46;

    EXPECT_TRUE(qAbs(msecs - total_msecs_46) < 100);

    time.UseVirtualTime();

    now = time.CurrentTime();
    now_46 = epoch.addMSecs(time.MSecsSinceEpoch());
    EXPECT_EQ(now, now_46);

    for(int i = 0; i < 50; i++) {
      time.IncrementVirtualClock(Random::GetInstance().GetInt());
      now = time.CurrentTime();
      now_46 = epoch.addMSecs(time.MSecsSinceEpoch());
      EXPECT_EQ(now, now_46);
    }
  }
Пример #8
0
    void MapLogPlacemarkData::addData(const GeoObjectID &id, SinglePointDataPtr data)
    {
        if (!mData.contains(id))
        {
            QVector<SinglePointDataPtr> newHistory;
            newHistory.push_back(data);
            mData.insert(id, newHistory);
            return;
        }

        if (data->isCritical())
        {
            insert(id, data);
        }

        SinglePointDataPtr mostRecent = mData[id].last();

        QDateTime lastTime = mostRecent->time();
        QDateTime recently = lastTime.addMSecs(mostRecent->durationMs());
        QDateTime now = QDateTime::currentDateTime();
        qint64 timespan = recently.daysTo(now) * msecsInDay + recently.time().msecsTo(now.time());

        if (*data == *mostRecent)
        {   //ignore, but advance duration
            //qDebug("Data didn't change");
            mostRecent->advanceDurationMs(timespan);
            return;
        }

        if (timespan > mTimeResolution)
        {
            //qDebug("Data changed and fits in resolution, inserting");
            insert(id, data);
        }
        else
        {
            //qDebug("Data discarded");
            if (mExtraDataBehavior == MapLogPlacemarkData::Ignore)
            { //ignore data completely
                return;
            }
            else
            { //TODO compress data somehow (for now also ignore)
                return;
            }
        }
    }
Пример #9
0
void ChatForm::onLoadHistory()
{
    LoadHistoryDialog dlg;

    if (dlg.exec())
    {
        QDateTime fromTime = dlg.getFromDate();
        QDateTime toTime = QDateTime::currentDateTime();

        if (fromTime > toTime)
            return;

        if (earliestMessage)
        {
            if (*earliestMessage < fromTime)
                return;
            if (*earliestMessage < toTime)
            {
                toTime = *earliestMessage;
                toTime = toTime.addMSecs(-1);
            }
        }

        auto msgs = HistoryKeeper::getInstance()->getChatHistory(HistoryKeeper::ctSingle, f->userId, fromTime, toTime);

        ToxID storedPrevId;
        std::swap(storedPrevId, previousId);
        QList<ChatActionPtr> historyMessages;

        for (const auto &it : msgs)
        {
            ChatActionPtr ca = genMessageActionAction(ToxID::fromString(it.sender), it.message, false, it.timestamp.toLocalTime());
            historyMessages.append(ca);
        }
        std::swap(storedPrevId, previousId);

        int savedSliderPos = chatWidget->verticalScrollBar()->maximum() - chatWidget->verticalScrollBar()->value();

        if (earliestMessage != nullptr)
            *earliestMessage = fromTime;

        chatWidget->insertMessagesTop(historyMessages);

        savedSliderPos = chatWidget->verticalScrollBar()->maximum() - savedSliderPos;
        chatWidget->verticalScrollBar()->setValue(savedSliderPos);
    }
}
Пример #10
0
void OpenIGTLinkProtocol::translate(const igtl::TransformMessage::Pointer body)
{
    //CX_LOG_DEBUG() << "Transform incoming to OpenIGTLinkProtocol";
    QString deviceName = body->GetDeviceName();

    IGTLinkConversion converter;
    Transform3D prMs = converter.decode(body);

    IGTLinkConversionBase baseConverter;
    QDateTime timestamp = baseConverter.decode_timestamp(body);

    if (mStreamSynchronizer)
    {
        mStreamSynchronizer->addTimestamp(timestamp);
        timestamp = timestamp.addMSecs(mStreamSynchronizer->getShift());
    }

    emit transform(deviceName, prMs, timestamp.toMSecsSinceEpoch());
}
Пример #11
0
void MarbleClockPrivate::timerTimeout()
{
    // calculate real period elapsed since last call
    QDateTime curenttime( QDateTime::currentDateTimeUtc() );
    int msecdelta = m_lasttime.msecsTo( curenttime );
    m_lasttime = curenttime;

    // update m_datetime at m_speed pace
    m_datetime = m_datetime.addMSecs( msecdelta * m_speed );

    // trigger round minute update (at m_speed pace)
    emit q->timeChanged();

    // sleeptime is the time to sleep until next round minute, at m_speed pace
    int sleeptime = ( m_updateInterval * 1000 - (qreal)(m_datetime.time().msec() + m_datetime.time().second() * 1000 ) ) / m_speed;
    if ( sleeptime < 1000 ) {
        // don't trigger more often than 1s
        sleeptime = 1000;
    }
    m_timer.start( sleeptime );

    //mDebug() << "MarbleClock: will sleep for " << sleeptime;
}
Пример #12
0
void Calendar::sendNotifications_Reminders()
{
    QDateTime now = QDateTime::currentDateTime();
    now = now.addSecs(-now.time().second());
    now = now.addMSecs(-now.time().msec());

    // Get the list of reminders that are dated at this minute and
    // erase them from reminder storage
    QList<Appointment> reminders;
    engageBufferLock("accessing/updating reminders list");
    QMap<QDateTime, Appointment>::iterator it = _aptCache->reminders()->find(now);

    // Collect all reminders dated to now
    while (it != _aptCache->reminders()->end() && it.key() == now) {
        reminders.push_back(*it);
        it = _aptCache->reminders()->erase(it);
    }
    releaseBufferLock("finished accessing reminders list");

    // Broadcast new reminders to observers
    if (reminders.count() > 0)
        emit newReminders(this, reminders);
}
Пример #13
0
void QGeoInfoThreadWinCE::setUpdateInterval(int interval)
{
    QMutexLocker locker(&mutex);

    if (interval == updatesInterval)
        return;

    int oldInterval = updatesInterval;
    updatesInterval = interval;

    if (updatesScheduled) {
        QDateTime now = currentDateTime();

        // The periodic update interval has been changed and updates are still ocurring.

        if (oldInterval != 0) {
            if (updatesInterval != 0) {
                // If we are changing fixed intervals we update the scheduled time for the next
                // periodic update, making sure that it is scheduled in the future.
                updatesNextTime = updatesNextTime.addMSecs(updatesInterval - oldInterval);
                while (msecsTo(now, updatesNextTime) < 0)
                    updatesNextTime = updatesNextTime.addMSecs(updatesInterval);
            } else {
                // If we now want to emit updates as the data arrives we invalidate the scheduled
                // time for the next update, just to be on the safe side.
                updatesNextTime = now;
            }
        } else {
            // If we were previously emitting updates as the data arrived we set the scheduled time
            // for the next periodic update.
            updatesNextTime = now.addMSecs(updatesInterval);
        }

        locker.unlock();
        wakeUp();
    }
}
Пример #14
0
//-----------------------------------------------------------------------------
MainView::MainView( ) :
    QQuickView( ),
    _propertiesList( new qan::PropertiesList( this ) )
{
    // Dynamic exemple code ------------
    Properties* p1 = new qan::Properties( this );

    p1->addProperty( "intProperty", QVariant::fromValue< int >( 40 ) );
    qDebug( ) << *p1;
    qDebug( ) << "--";
    QDateTime current = QDateTime::currentDateTimeUtc( );
    p1->setProperty( "intProperty", current, 41 );
    p1->setProperty( "intProperty", current.addMSecs( 1000 ), 42 );
    qDebug( ) << *p1;
    qDebug( ) << "--";
    //-----------------------------------

    // Static exemple code ------------
    MyProperties* mp = new MyProperties( this );
    qDebug( ) << *mp;
    //-----------------------------------

    Properties* p = new Properties( this );
    p->setObjectName( "MyQanProperties" );

    generateRandTimeValues< int >( *p, "intProperty", 15, 15000 ); // Generate random int value over 15s int the "int property"intProperty'
    p->addProperty( "intProperty", QVariant::fromValue< int >( 40 ) );
    qDebug( ) << *p;

    rootContext( )->setContextProperty( "qanPropertiesModel", p->getPropertiesModel( )  );
    rootContext( )->setContextProperty( "qanProperties", p );
    qan::PropertyGraphModel* graphModel = p->getPropertyGraphModel( "intProperty" );
    rootContext( )->setContextProperty( "qanPropertyGraphModel", graphModel );

    setSource( QUrl::fromLocalFile( "main.qml" ) );
}
Пример #15
0
QwtText CViewingPlotPicker::trackerTextF(const QPointF& pos) const
{
	const QDateTime DT2006(QDate(2006, 1, 1), QTime(0, 0, 0, 0));
    QString text;	

    switch (rubberBand())
    {
        case HLineRubberBand:
		{
			if (!m_timeModeY)
			{
				text.sprintf("%.4f", pos.y());
			}
			else
			{
				double v = pos.y();
				qint64 seconds = qint64(v);
				v -= seconds;
				int days = seconds/86400;
				QDateTime dt = DT2006.addDays(days);
				seconds %= 86400;
				dt = dt.addSecs(seconds);
				int milliseconds = int(ceil(v * 10000.0) / 10.0);
				dt = dt.addMSecs(milliseconds);
				text = dt.toString("yyyy-MM-dd hh:mm:ss.zzz");
			}

			break;
		}
        case VLineRubberBand:
		{
			if (!m_timeModeX)
			{
				text.sprintf("%.4f", pos.x());
			}
			else
			{
				double v = pos.x();
				qint64 seconds = qint64(v);
				v -= seconds;
				int days = seconds/86400;
				QDateTime dt = DT2006.addDays(days);
				seconds %= 86400;
				dt = dt.addSecs(seconds);
				int milliseconds = int(ceil(v * 10000)/10);
				dt = dt.addMSecs(milliseconds);
				text = dt.toString("yyyy-MM-dd hh:mm:ss.zzz");
			}
        
			break;
		}
        default:
		{
			if ((!m_timeModeX) && (!m_timeModeY))
			{
				text.sprintf("%.4f, %.4f", pos.x(), pos.y());
			}
			else
			{
				if (!m_timeModeX)
				{
					text.sprintf("%.4f", pos.x());
				}
				else
				{
					double v = pos.x();
					qint64 seconds = qint64(v);
					v -= seconds;
					int days = seconds/86400;
					QDateTime dt = DT2006.addDays(days);
					seconds %= 86400;
					dt = dt.addSecs(seconds);
					int milliseconds = int(ceil(v * 10000)/10);
					dt = dt.addMSecs(milliseconds);
					text = dt.toString("yyyy-MM-dd hh:mm:ss.zzz");
				}

				text += QObject::tr(", ");

				if (!m_timeModeY)
				{
					text += QString::number(pos.y(), 'f', 4);
				}
				else
				{
					double v = pos.y();
					qint64 seconds = qint64(v);
					v -= seconds;
					int days = seconds/86400;
					QDateTime dt = DT2006.addDays(days);
					seconds %= 86400;
					dt = dt.addSecs(seconds);
					int milliseconds = int(ceil(v * 10000)/10);
					dt = dt.addMSecs(milliseconds);
					text += dt.toString("yyyy-MM-dd hh:mm:ss.zzz");
				}
			}
		}
    }

    return QwtText(text);
}
Пример #16
0
void ChatForm::loadHistory(QDateTime since, bool processUndelivered)
{
    QDateTime now = historyBaselineDate.addMSecs(-1);

    if (since > now)
        return;

    if (!earliestMessage.isNull())
    {
        if (earliestMessage < since)
            return;

        if (earliestMessage < now)
        {
            now = earliestMessage;
            now = now.addMSecs(-1);
        }
    }

    auto msgs = HistoryKeeper::getInstance()->getChatHistory(HistoryKeeper::ctSingle, f->getToxID().publicKey, since, now);

    ToxId storedPrevId = previousId;
    ToxId prevId;

    QList<ChatLine::Ptr> historyMessages;

    QDate lastDate(1,0,0);
    for (const auto &it : msgs)
    {
        // Show the date every new day
        QDateTime msgDateTime = it.timestamp.toLocalTime();
        QDate msgDate = msgDateTime.date();

        if (msgDate > lastDate)
        {
            lastDate = msgDate;
            historyMessages.append(ChatMessage::createChatInfoMessage(msgDate.toString(Settings::getInstance().getDateFormat()), ChatMessage::INFO, QDateTime()));
        }

        // Show each messages
        ToxId authorId = ToxId(it.sender);
        QString authorStr = authorId.isActiveProfile() ? Core::getInstance()->getUsername() : resolveToxID(authorId);
        bool isAction = it.message.startsWith("/me ", Qt::CaseInsensitive);

        ChatMessage::Ptr msg = ChatMessage::createChatMessage(authorStr,
                                                              isAction ? it.message.right(it.message.length() - 4) : it.message,
                                                              isAction ? ChatMessage::ACTION : ChatMessage::NORMAL,
                                                              authorId.isActiveProfile(),
                                                              QDateTime());

        if (!isAction && (prevId == authorId) && (prevMsgDateTime.secsTo(msgDateTime) < getChatLog()->repNameAfter) )
            msg->hideSender();

        prevId = authorId;
        prevMsgDateTime = msgDateTime;

        if (it.isSent || !authorId.isActiveProfile())
        {
            msg->markAsSent(msgDateTime);
        }
        else
        {
            if (processUndelivered)
            {
                int rec;
                if (!isAction)
                    rec = Core::getInstance()->sendMessage(f->getFriendID(), msg->toString());
                else
                    rec = Core::getInstance()->sendAction(f->getFriendID(), msg->toString());

                getOfflineMsgEngine()->registerReceipt(rec, it.id, msg);
            }
        }
        historyMessages.append(msg);
    }

    previousId = storedPrevId;
    int savedSliderPos = chatWidget->verticalScrollBar()->maximum() - chatWidget->verticalScrollBar()->value();

    earliestMessage = since;

    chatWidget->insertChatlineOnTop(historyMessages);

    savedSliderPos = chatWidget->verticalScrollBar()->maximum() - savedSliderPos;
    chatWidget->verticalScrollBar()->setValue(savedSliderPos);
}
Пример #17
0
QString Timehelper::duration(QString depdate, QString deptime, QString arivdate, QString arivtime, bool delay) {
    depdate = convertdate(depdate);
    arivdate = convertdate(arivdate);

    QDate depdate2 = QDate::fromString(depdate, "yyyy-MM-dd");
    QTime deptime2 = QTime::fromString(deptime, "hh:mm");
    QDate arivdate2 = QDate::fromString(arivdate, "yyyy-MM-dd");
    QTime arivtime2 = QTime::fromString(arivtime, "hh:mm");

    bool minus = false;
    QDateTime epoch = QDateTime(QDate(1970,1,1),QTime(0,0),Qt::UTC);
    qint64 dep = QDateTime(depdate2, deptime2).toMSecsSinceEpoch();
    qint64 ariv = QDateTime(arivdate2, arivtime2).toMSecsSinceEpoch();
    minus = dep > ariv;
    if (dep == ariv) {
        if (!delay) {
            return "0min";
        } else {
            return "";
        }

    }
    qint64 diff2 = minus ? (dep - ariv) : (ariv - dep);
    //qDebug() << diff2;
    epoch = epoch.addMSecs(diff2);

    int days = epoch.toString("d").toInt() - 1;
    int hour = epoch.toString("h").toInt();
    int min = epoch.toString("m").toInt();

    //qDebug() << minus << days << "d" << hour << "h" << min << "min";
    //qDebug() << epoch.toString();

    QString answer = "";

    if (min > 0) {
        if (!delay) {
            answer.sprintf("%dmin", min);
        } else {
            answer.sprintf("%d", min);
        }
    }
    if (hour > 0) {
        QString hourstr = "";
        if (!delay) {
            hourstr.sprintf("%dh", hour);
        } else {
            if (min > 0) {
                hourstr.sprintf("%d:", hour);
            } else {
                hourstr.sprintf("%dh", hour);
            }
        }
        answer = hourstr + answer;
    }
    if (days > 0) {
        QString daystr = "";
        daystr.sprintf("%dd", days);
        answer = answer.append(daystr);
    }
    return minus ? "-" + answer : (delay ? "+" + answer : answer);
}
Пример #18
0
/*!
  Align a date/time value for a step size

  For Qt::Day alignments there is no "natural day 0" -
  instead the first day of the year is used to avoid jumping 
  major ticks positions when panning a scale. For other alignments
  ( f.e according to the first day of the month ) alignDate()
  has to be overloaded.

  \param dateTime Date/time value
  \param stepSize Step size
  \param intervalType Interval type
  \param up When true dateTime is ceiled - otherwise it is floored

  \return Aligned date/time value
 */
QDateTime QwtDateScaleEngine::alignDate( 
    const QDateTime &dateTime, double stepSize, 
    QwtDate::IntervalType intervalType, bool up ) const
{
    // what about: (year == 1582 && month == 10 && day > 4 && day < 15) ??

    QDateTime dt = dateTime;

    if ( dateTime.timeSpec() == Qt::OffsetFromUTC )
    {
        dt.setUtcOffset( 0 );
    }

    switch( intervalType )
    {
        case QwtDate::Millisecond:
        {
            const int ms = qwtAlignValue( 
                dt.time().msec(), stepSize, up ) ;

            dt = QwtDate::floor( dateTime, QwtDate::Second );
            dt = dt.addMSecs( ms );

            break;
        }
        case QwtDate::Second:
        {
            int second = dt.time().second();
            if ( up )
            {
                if ( dt.time().msec() > 0 )
                    second++;
            }

            const int s = qwtAlignValue( second, stepSize, up );

            dt = QwtDate::floor( dt, QwtDate::Minute );
            dt = dt.addSecs( s );

            break;
        }
        case QwtDate::Minute:
        {
            int minute = dt.time().minute();
            if ( up )
            {
                if ( dt.time().msec() > 0 || dt.time().second() > 0 )
                    minute++;
            }

            const int m = qwtAlignValue( minute, stepSize, up );

            dt = QwtDate::floor( dt, QwtDate::Hour );
            dt = dt.addSecs( m * 60 );

            break;
        }
        case QwtDate::Hour:
        {
            int hour = dt.time().hour();
            if ( up )
            {
                if ( dt.time().msec() > 0 || dt.time().second() > 0
                    || dt.time().minute() > 0 )
                {
                    hour++;
                }
            }
            const int h = qwtAlignValue( hour, stepSize, up );

            dt = QwtDate::floor( dt, QwtDate::Day );
            dt = dt.addSecs( h * 3600 );

            break;
        }
        case QwtDate::Day:
        {
            // What date do we expect f.e. from an alignment of 5 days ??
            // Aligning them to the beginning of the year avoids at least
            // jumping major ticks when panning

            int day = dt.date().dayOfYear();
            if ( up )
            {
                if ( dt.time() > QTime( 0, 0 ) )
                    day++;
            }

            const int d = qwtAlignValue( day, stepSize, up );

            dt = QwtDate::floor( dt, QwtDate::Year );
            dt = dt.addDays( d - 1 );

            break;
        }
        case QwtDate::Week:
        {
            const QDate date = QwtDate::dateOfWeek0(
                dt.date().year(), d_data->week0Type );

            int numWeeks = date.daysTo( dt.date() ) / 7;
            if ( up )
            {
                if ( dt.time() > QTime( 0, 0 ) ||
                    date.daysTo( dt.date() ) % 7 )
                {
                    numWeeks++;
                }
            }

            const int d = qwtAlignValue( numWeeks, stepSize, up ) * 7;

            dt = QwtDate::floor( dt, QwtDate::Day );
            dt.setDate( date );
            dt = dt.addDays( d );

            break;
        }
        case QwtDate::Month:
        {
            int month = dt.date().month();
            if ( up )
            {
                if ( dt.date().day() > 1 ||
                    dt.time() > QTime( 0, 0 ) )
                {
                    month++;
                }
            }

            const int m = qwtAlignValue( month - 1, stepSize, up );

            dt = QwtDate::floor( dt, QwtDate::Year );
            dt = dt.addMonths( m );

            break;
        }
        case QwtDate::Year:
        {
            int year = dateTime.date().year();
            if ( up )
            {
                if ( dateTime.date().dayOfYear() > 1 ||
                    dt.time() > QTime( 0, 0 ) )
                {
                    year++;
                }
            }

            const int y = qwtAlignValue( year, stepSize, up );

            dt = QwtDate::floor( dt, QwtDate::Day );
            if ( y == 0 )
            {
                // there is no year 0 in the Julian calendar
                dt.setDate( QDate( stepSize, 1, 1 ).addYears( -stepSize ) );
            }
            else
            {
                dt.setDate( QDate( y, 1, 1 ) );
            }

            break;
        }
    }

    if ( dateTime.timeSpec() == Qt::OffsetFromUTC )
    {
        dt.setUtcOffset( dateTime.utcOffset() );
    }

    return dt;
}
Пример #19
0
static QwtScaleDiv qwtDivideToSeconds( 
    const QDateTime &minDate, const QDateTime &maxDate,
    double stepSize, int maxMinSteps,
    QwtDate::IntervalType intervalType ) 
{
    // calculate the min step size
    double minStepSize = 0;

    if ( maxMinSteps > 1 ) 
    {
        minStepSize = qwtDivideMajorStep( stepSize, 
            maxMinSteps, intervalType );
    }

    bool daylightSaving = false;
    if ( minDate.timeSpec() == Qt::LocalTime )
    {
        daylightSaving = intervalType > QwtDate::Hour;
        if ( intervalType == QwtDate::Hour )
        {
            daylightSaving = stepSize > 1;
        }
    }

    const double s = qwtMsecsForType( intervalType ) / 1000;
    const int secondsMajor = static_cast<int>( stepSize * s );
    const double secondsMinor = minStepSize * s;
    
    // UTC excludes daylight savings. So from the difference
    // of a date and its UTC counterpart we can find out
    // the daylight saving hours

    const double utcOffset = QwtDate::utcOffset( minDate );
    double dstOff = 0;

    QList<double> majorTicks;
    QList<double> mediumTicks;
    QList<double> minorTicks;

    for ( QDateTime dt = minDate; dt <= maxDate; 
        dt = dt.addSecs( secondsMajor ) )
    {
        if ( !dt.isValid() )
            break;

        double majorValue = QwtDate::toDouble( dt );

        if ( daylightSaving )
        {
            const double offset = utcOffset - QwtDate::utcOffset( dt );
            majorValue += offset * 1000.0;

            if ( offset > dstOff )
            {
                // we add some minor ticks for the DST hour,
                // otherwise the ticks will be unaligned: 0, 2, 3, 5 ...
                minorTicks += qwtDstTicks( 
                    dt, secondsMajor, qRound( secondsMinor ) );
            }

            dstOff = offset;
        }

        if ( majorTicks.isEmpty() || majorTicks.last() != majorValue )
            majorTicks += majorValue;

        if ( secondsMinor > 0.0 )
        {
            const int numMinorSteps = qFloor( secondsMajor / secondsMinor );

            for ( int i = 1; i < numMinorSteps; i++ )
            {
                const QDateTime mt = dt.addMSecs( 
                    qRound64( i * secondsMinor * 1000 ) );

                double minorValue = QwtDate::toDouble( mt );
                if ( daylightSaving )
                {
                    const double offset = utcOffset - QwtDate::utcOffset( mt );
                    minorValue += offset * 1000.0;
                }

                if ( minorTicks.isEmpty() || minorTicks.last() != minorValue )
                {
                    const bool isMedium = ( numMinorSteps % 2 == 0 ) 
                        && ( i != 1 ) && ( i == numMinorSteps / 2 );

                    if ( isMedium )
                        mediumTicks += minorValue;
                    else
                        minorTicks += minorValue;
                }
            }
        }
    }

    QwtScaleDiv scaleDiv;

    scaleDiv.setInterval( QwtDate::toDouble( minDate ),
        QwtDate::toDouble( maxDate ) );

    scaleDiv.setTicks( QwtScaleDiv::MajorTick, majorTicks );
    scaleDiv.setTicks( QwtScaleDiv::MediumTick, mediumTicks );
    scaleDiv.setTicks( QwtScaleDiv::MinorTick, minorTicks );

    return scaleDiv;
}
Пример #20
0
/*!
  Resets the SQL representation of the SIM Card for this storage.  This
  includes removing any contacts that can be stored completely on the SIM,
  resetting the mapping of contact id to SIM card index, and in the case
  of the "SM" storage type, resetting the information on the available
  indexes to store contact phone numbers.

  A contact that can be stored completely on the sim is defined as
  one that is equal to a contact that has copied only the original contacts phone numbers, unique identity, and first name.

  \sa storage()
*/
void QContactSimSyncer::resetSqlState()
{
    qLog(SimPhoneBook) << mSimType << "::resetSqlState()";

    if (mSimType == "SM") {
        simValueSpace = new QValueSpaceObject("/SIM/Contacts");
        simValueSpace->setAttribute("Loaded", false);
    } else
        simValueSpace = 0;

    QDateTime syncTime = QTimeZone::current().toUtc(QDateTime::currentDateTime());
    syncTime = syncTime.addMSecs(-syncTime.time().msec());

    if (mAccess->startTransaction(syncTime)) {
        QPreparedSqlQuery q(QPimSqlIO::database());

        qLog(SimPhoneBook) << mSimType << "::resetSqlState() - get cardid";

        q.prepare("SELECT cardid FROM currentsimcard WHERE storage = :simtype");
        q.bindValue(":simtype", mSimType);
        q.exec();
        if (!q.next()) {
            qLog(SimPhoneBook) << mSimType << "::resetSqlState() - no card found";
            // already cleared the card.
            if (mAccess->commitTransaction())
                return;
        } else {
            QString lastActiveCard = q.value(0).toString();
            qLog(SimPhoneBook) << mSimType << "::resetSqlState() - clear" << lastActiveCard;

            q.prepare("SELECT recid, simlabelidmap.label FROM contacts JOIN simlabelidmap ON sqlid = recid WHERE cardid = :c AND storage = :s");
            q.bindValue(":s", mSimType);
            q.bindValue(":c", lastActiveCard);

            q.exec();
            QList<QUniqueId> removeTargets;
            while(q.next()) {
                QContact existing, compare;
                QUniqueId recid = QUniqueId::fromUInt(q.value(0).toUInt());
                QString label = q.value(1).toString();
                existing = mAccess->contact(recid);
                qLog(SimPhoneBook) << mSimType << "::resetSqlState() - check if" << recid.toString() << "should be removed";
                if (QContactSimContext::simLabel(existing) != label) {
                    qLog(SimPhoneBook) << mSimType << "::resetSqlState() - label mis-match" << QContactSimContext::simLabel(existing) << label;
                    // truncated label, don't remove or will lose info.
                    continue;
                }
                compare.setUid(existing.uid());
                compare.setFirstName(existing.firstName());
                compare.setLastName(existing.lastName());
                compare.setPhoneNumbers(existing.phoneNumbers());
                compare.setDefaultPhoneNumber(existing.defaultPhoneNumber());
                if (compare == existing) { // e.g. is only data that fits on the sim.
                    removeTargets.append(QUniqueId::fromUInt(q.value(0).toUInt()));
                    qLog(SimPhoneBook) << mSimType << "::resetSqlState() - remove contact" << q.value(0).toUInt();
                } else {
                    qLog(SimPhoneBook) << mSimType << "::resetSqlState() - contact == mismatch";
                }
            }

            if (mAccess->removeContacts(removeTargets))
            {
                qLog(SimPhoneBook) << mSimType << "::resetSqlState() - remove current simcard for storage";
                q.clearErrors();
                q.prepare("DELETE FROM currentsimcard WHERE storage = :simtype");
                q.bindValue(":simtype", mSimType);
                q.exec();

                qLog(SimPhoneBook) << mSimType << "::resetSqlState() - remove idmap for storage";
                q.prepare("DELETE FROM simcardidmap WHERE cardid = :c AND storage = :simtype");
                q.bindValue(":simtype", mSimType);
                q.bindValue(":c", lastActiveCard);
                q.exec();

                // only remove 'forgotten' records.
                qLog(SimPhoneBook) << mSimType << "::resetSqlState() - remove label idmap for storage";
                q.prepare("DELETE FROM simlabelidmap WHERE sqlid = :r");
                foreach (QUniqueId id, removeTargets) {
                    q.bindValue(":r", id.toUInt());
                    q.exec();
                }

                if (q.errorCount() == 0 && mAccess->commitTransaction())
                    return;
            }
Пример #21
0
QDateTime Double2DateTimeFilter::dateTimeAt(int row) const {
	if (!d_inputs.value(0)) return QDateTime();
	double input_value = d_inputs.value(0)->valueAt(row);
	QDateTime result;
	// This gets a little messy, since QDate can't represent the reference date of JDN.
	// Thus, we manually interpret invalid dates as JDN reference.
	switch (m_unit_interval) {
		case Year:
			if (m_date_time_0.isValid())
				result = m_date_time_0.addYears(int(floor(input_value)));
			else {
				result.setDate(QDate(int(floor(input_value))+4713, 1, 1));
				result.setTime(QTime(12,0,0,0));
			}
			return result.addMSecs(qRound64((input_value - int(floor(input_value))) *
						result.date().daysInYear() * 86400000.0));
		case Month:
			if (m_date_time_0.isValid())
				result = m_date_time_0.addMonths(int(floor(input_value)));
			else {
				result.setDate(QDate(int(floor(input_value))/12+4713, int(floor(input_value))%12+1, 1));
				result.setTime(QTime(12,0,0,0));
			}
			return result.addMSecs(qRound64((input_value - int(floor(input_value))) *
						result.date().daysInMonth() * 86400000.0));
		case Day:
			if (m_date_time_0.isValid())
				result = m_date_time_0.addDays(int(floor(input_value)));
			else {
				result.setDate(QDate::fromJulianDay(int(floor(input_value))));
				result.setTime(QTime(12,0,0,0));
			}
			return result.addMSecs(qRound64((input_value - int(floor(input_value))) * 86400000.0));
		case Hour:
			if (m_date_time_0.isValid())
				return m_date_time_0.addMSecs(qRound64(input_value * 3600000.0));
			else {
				result.setDate(QDate::fromJulianDay(int(floor(input_value)) / 24));
				result.setTime(QTime(12,0,0,0));
				result.addSecs((int(floor(input_value)) % 24) * 3600);
				return result.addMSecs(qRound64((input_value - int(floor(input_value))) * 3600000.0));
			}
		case Minute:
			if (m_date_time_0.isValid())
				return m_date_time_0.addMSecs(qRound64(input_value * 60000.0));
			else {
				result.setDate(QDate::fromJulianDay(int(floor(input_value)) / (24 * 60)));
				result.setTime(QTime(12,0,0,0));
				result.addSecs((int(floor(input_value)) % (24 * 60)) * 60);
				return result.addMSecs(qRound64((input_value - int(floor(input_value))) * 60000.0));
			}
		case Second:
			if (m_date_time_0.isValid())
				return m_date_time_0.addMSecs(qRound64(input_value * 1000.0));
			else {
				result.setDate(QDate::fromJulianDay(int(floor(input_value)) / (24 * 60 * 60)));
				result.setTime(QTime(12,0,0,0));
				result.addSecs(int(floor(input_value)) % (24 * 60 * 60));
				return result.addMSecs(qRound64((input_value - int(floor(input_value))) * 1000.0));
			}
		case Millisecond:
			if (m_date_time_0.isValid())
				return m_date_time_0.addMSecs(qRound64(input_value));
			else {
				result.setDate(QDate::fromJulianDay(int(floor(input_value)) / (24 * 60 * 60)));
				result.setTime(QTime(12,0,0,0));
				result.addSecs(int(floor(input_value)) % (24 * 60 * 60));
				return result.addMSecs(qRound64((input_value - int(floor(input_value))) * 1000.0));
			}
	}
}
Пример #22
0
QDateTime ValueParser::readTime(const QString& intstr, bool withSeconds, bool* ok) const
{
    QString str = intstr.simplified().toLower();
    QString format = m_settings->locale()->timeFormat().simplified();
    if (!withSeconds) {
        int n = format.indexOf("%S");
        format = format.left(n - 1);
    }

    QDateTime result;
    int hour = 0;
    int minute = 0;
    int second = 0;
    int msecs = 0;
    bool g_12h = false;
    bool pm = false;
    bool negative = false;
    uint strpos = 0;
    uint formatpos = 0;

    const uint l  = format.length();
    const uint sl = str.length();

    while (l > formatpos || sl > strpos) {
        if (!(l > formatpos && sl > strpos))
            goto error;

        QChar c(format.at(formatpos++));

        if (c != '%') {
            if (c.isSpace())
                ++strpos;
            else if (c != str.at(strpos++))
                goto error;
            continue;
        }

        // remove space at the beginning
        if (sl > strpos && str.at(strpos).isSpace())
            ++strpos;

        c = format.at(formatpos++);
        switch (c.toLatin1()) {
        case 'p': {
            QString s(ki18n("pm").toString(m_settings->locale()).toLower());
            int len = s.length();
            if (str.mid(strpos, len) == s) {
                pm = true;
                strpos += len;
            } else {
                s = ki18n("am").toString(m_settings->locale()).toLower();
                len = s.length();
                if (str.mid(strpos, len) == s) {
                    pm = false;
                    strpos += len;
                } else
                    goto error;
            }
        }
        break;

        case 'k':
        case 'H':
            g_12h = false;
            if (str.at(strpos) == '-') {
                negative = true;
                if (sl <= ++strpos)
                    goto error;
            }
            hour = readInt(str, strpos);
            if (hour < 0)
                goto error;

            break;

        case 'l':
        case 'I':
            g_12h = true;
            if (str.at(strpos) == '-') {
                negative = true;
                if (sl <= ++strpos)
                    goto error;
            }
            hour = readInt(str, strpos);
            if (hour < 1 || hour > 12)
                goto error;

            break;

        case 'M':
            minute = readInt(str, strpos);
            if (minute < 0 || minute > 59)
                goto error;

            break;

        case 'S':
            if (!withSeconds)
                break;
            second = readInt(str, strpos);
            if (second < 0 || second > 59)
                goto error;
            if (strpos < sl && str.indexOf(m_settings->locale()->decimalSymbol()) == (int)strpos) {
                strpos += m_settings->locale()->decimalSymbol().length();
                msecs = readInt(str, strpos);
                if (msecs < 0 || msecs > 999)
                    goto error;
            }

            break;
        }
    }

    if (g_12h) {
        hour %= 12;
        if (pm) hour += 12;
    }

    if (ok)
        *ok = true;
    result = QDateTime(m_settings->referenceDate(), QTime(0, 0), Qt::UTC);
    msecs += (((hour * 60 + minute) * 60 + second) * 1000);
    result = result.addMSecs(negative ? -msecs : msecs);
    return result;

error:
    if (ok)
        *ok = false;
    // return invalid date if it didn't work
    return QDateTime(m_settings->referenceDate(), QTime(-1, -1, -1), Qt::UTC);
}
Пример #23
0
QDateTime SER_Header::qdatetime(const SER_Timestamp& timestamp)
{
  static const QDateTime reference{{1, 1, 1}, {0,0,0}};
  return reference.addMSecs(timestamp / 10000);
}
void tst_QNmeaPositionInfoSource::startUpdates_withTimeout()
{
    QNmeaPositionInfoSource source(m_mode);
    QNmeaPositionInfoSourceProxyFactory factory;
    QNmeaPositionInfoSourceProxy *proxy = static_cast<QNmeaPositionInfoSourceProxy*>(factory.createProxy(&source));

    QSignalSpy spyUpdate(proxy->source(), SIGNAL(positionUpdated(QGeoPositionInfo)));
    QSignalSpy spyTimeout(proxy->source(), SIGNAL(updateTimeout()));

    proxy->source()->setUpdateInterval(1000);
    proxy->source()->startUpdates();

    QDateTime dt = QDateTime::currentDateTime().toUTC();

    if (m_mode == QNmeaPositionInfoSource::SimulationMode) {
        // the first sentence primes the simulation
        proxy->feedBytes(QLocationTestUtils::createRmcSentence(dt).toLatin1());
        proxy->feedBytes(QLocationTestUtils::createRmcSentence(dt.addMSecs(10)).toLatin1());
        proxy->feedBytes(QLocationTestUtils::createRmcSentence(dt.addMSecs(1100)).toLatin1());
        proxy->feedBytes(QLocationTestUtils::createRmcSentence(dt.addMSecs(2200)).toLatin1());
        proxy->feedBytes(QLocationTestUtils::createRmcSentence(dt.addSecs(9)).toLatin1());

        QTime t;
        t.start();

        for (int j = 1; j < 4; ++j) {
            QTRY_COMPARE(spyUpdate.count(), j);
            QCOMPARE(spyTimeout.count(), 0);
            int time = t.elapsed();
            QVERIFY((time > j*1000 - 300) && (time < j*1000 + 300));
        }

        spyUpdate.clear();

        QTRY_VERIFY_WITH_TIMEOUT((spyUpdate.count() == 0) && (spyTimeout.count() == 1), 7500);
        spyTimeout.clear();

        QTRY_VERIFY_WITH_TIMEOUT((spyUpdate.count() == 1) && (spyTimeout.count() == 0), 7500);

    } else {
        // dt + 900
        QTRY_VERIFY(spyUpdate.count() == 0 && spyTimeout.count() == 0);

        proxy->feedBytes(QLocationTestUtils::createRmcSentence(dt.addSecs(1)).toLatin1());
        // dt + 1200
        QTRY_VERIFY(spyUpdate.count() == 1 && spyTimeout.count() == 0);
        spyUpdate.clear();

        // dt + 1900
        QTRY_VERIFY(spyUpdate.count() == 0 && spyTimeout.count() == 0);
        proxy->feedBytes(QLocationTestUtils::createRmcSentence(dt.addSecs(2)).toLatin1());

        // dt + 2200
        QTRY_VERIFY(spyUpdate.count() == 1 && spyTimeout.count() == 0);
        spyUpdate.clear();

        // dt + 2900
        QTRY_VERIFY(spyUpdate.count() == 0 && spyTimeout.count() == 0);
        proxy->feedBytes(QLocationTestUtils::createRmcSentence(dt.addSecs(3)).toLatin1());

        // dt + 3200
        QTRY_VERIFY(spyUpdate.count() == 1 && spyTimeout.count() == 0);
        spyUpdate.clear();

        // dt + 6900
        QTRY_VERIFY(spyUpdate.count() == 0 && spyTimeout.count() == 1);
        spyTimeout.clear();
        proxy->feedBytes(QLocationTestUtils::createRmcSentence(dt.addSecs(7)).toLatin1());

        // dt + 7200
        QTRY_VERIFY(spyUpdate.count() == 1 && spyTimeout.count() == 0);
        spyUpdate.clear();
    }
}
Пример #25
0
void ConfigurationParser::readFiles(DataLayer *layer)
{
    Q_ASSERT(isStartElement()
             && name() == "files");
    
    QDateTime startDate;
    int start = 0;
    QDateTime endDate;
    int end = 0;
    int digits = 0;
    QString scheme;
    int skip = 0;
    
    while(!atEnd()) {
        readNext();
        
        if(isEndElement()) {
            break;
        }
        
        if(isStartElement()) {
            if(name() == "start") {
                QXmlStreamAttributes att = attributes();
                startDate.setTime(QTime::fromString(att.value("time").toString(), Qt::ISODate));
                startDate.setDate(QDate::fromString(att.value("date").toString(), Qt::ISODate));
                start = readCharacters().toInt();
            }
            else if(name() == "end") {
                QXmlStreamAttributes att = attributes();
                endDate.setTime(QTime::fromString(att.value("time").toString(), Qt::ISODate));
                endDate.setDate(QDate::fromString(att.value("date").toString(), Qt::ISODate));
                end = readCharacters().toInt();
            }
            else if(name() == "scheme") {
                QXmlStreamAttributes att = attributes();
                digits = att.value("digits").toString().toInt();
                if(att.hasAttribute("skip")) {
                    skip = att.value("skip").toString().toInt();
                }
                scheme = readCharacters();
            }
            else {
                readUnknownElement();
            }
        }
    }
    
    if(startDate.isValid() && endDate.isValid()) {
        qint64 spanMSecs = endDate.toMSecsSinceEpoch() - startDate.toMSecsSinceEpoch();
        int count = end - start;
        qint64 diffMSecs = spanMSecs / count;
        
        for(int i = start; i < end; i += 1 + skip) {
            QDateTime fileTime = startDate.addMSecs(diffMSecs * (i - start));
            qDebug() << "Time [" << i << "]:" << fileTime.toString();
            QString fileName = scheme.arg(i, digits, 10, QChar('0'));
            
            layer->setFileName(fileTime, fileName);
        }
    }
}
/** Load an OEM file and convert it to an STA Space Scenario.
  *
  * Not all features of the OEM format are supported by the OemImporter
  * class. An oem file that uses an unsupported feature will fail to load;
  * details of the problem are available via the errorMessage() method.
  *
  * The current implementation has the following limitations:
  *   - TIME_STANDARD must be TDB
  *   - REF_FRAME must be EME2000 or ECLIP2000
  *   - CENTER_NAME must be an object with an ephemeris
  *
  * \return a pointer to a complete space scenario, or NULL if
  * there was an error loading the scenario.
  */
SpaceScenario*
OemImporter::loadScenario()
{
    readHeader();
    SpaceScenario* scenario = new SpaceScenario();
    scenario->setName("New scenario");

    QSharedPointer<ScenarioSC> sc(new ScenarioSC());
    scenario->AbstractParticipant().append(sc);

    ScenarioExternalType* trajectory;

    bool skip = false;
    QString line;

    QString objectName;
    StaBody* center = NULL;
    sta::CoordinateSystemType coordSys = sta::COORDSYS_INVALID;

    QRegExp whiteSpaceRegExp("\\s+");


    // This is the state machine for parsing OEM files. Roughly, the structure
    // of an OEM file is:
    //    Header
    //
    //    Metadata
    //    Ephemeris data
    //    Metadata
    //    Ephemeris data
    //    ...
    //
    // Where the metadata and ephemeris data blocks alternate; any number
    // of metadata/ephemeris data pairs may appear in the file. For full
    // details see Recommended Standard CCSDS 502.0-B-2.
    while (m_parserState != Oem_End && m_parserState != Oem_Error)
    {
        if (skip)
        {
            skip = false;
        }
        else
        {
            line = m_stream->readLine().trimmed();
            m_lineNumber++;
        }

        if (m_stream->atEnd())
        {
            m_parserState = Oem_End;
        }
        else if (line.isEmpty())
        {
            // Nothing to do
        }
        else
        {
            switch (m_parserState)
            {
            case Oem_Begin:
                {
                    OemKeyValue kv = ParseKeyValue(line);
                    if (kv.key == "CCSDS_OEM_VERS")
                    {
                        m_parserState = Oem_AfterVersion;
                    }
                    else
                    {
                        raiseError("Version expected in header");
                    }
                }
                break;

            case Oem_AfterVersion:
                if (line.startsWith("COMMENT"))
                {
                    // Skip and do nothing
                }
                else
                {
                    OemKeyValue kv = ParseKeyValue(line);
                    if (kv.key == "CREATION_DATE")
                    {
                        m_parserState = Oem_AfterCreationDate;
                    }
                    else
                    {
                        raiseError("Creation date expected in header");
                    }
                }
                break;

            case Oem_AfterCreationDate:
                {
                    OemKeyValue kv = ParseKeyValue(line);
                    if (kv.key == "ORIGINATOR")
                    {
                        m_parserState = Oem_AfterHeader;
                    }
                    else
                    {
                        raiseError("Creation date expected in header");
                    }
                }
                break;

            case Oem_AfterHeader:
                if (line.startsWith("COMMENT"))
                {
                    // Skip and do nothing
                }
                else if (line == "META_START")
                {
                    m_parserState = Oem_MetaStart;
                }
                else
                {
                    raiseError("Metadata block expected");
                }
                break;

            case Oem_MetaStart:
                {
                    OemKeyValue kv = ParseKeyValue(line);
                    if (kv.key == "OBJECT_NAME")
                    {
                        m_parserState = Oem_AfterObjectName;
                        objectName = kv.value;
                    }
                    else
                    {
                        raiseError("Object name expected");
                    }
                }
                break;

            case Oem_AfterObjectName:
                {
                    OemKeyValue kv = ParseKeyValue(line);
                    if (kv.key == "OBJECT_ID")
                    {
                        m_parserState = Oem_AfterObjectId;
                    }
                    else
                    {
                        raiseError("Object ID expected");
                    }
                }
                break;

            case Oem_AfterObjectId:
                {
                    OemKeyValue kv = ParseKeyValue(line);
                    if (kv.key == "CENTER_NAME")
                    {
                        m_parserState = Oem_AfterCenterName;
                        center = STA_SOLAR_SYSTEM->lookup(kv.value);
                        if (!center)
                        {
                            raiseError("Unknown central body " + kv.value);
                        }
                    }
                    else
                    {
                        raiseError("Center name expected");
                    }
                }
                break;

            case Oem_AfterCenterName:
                {
                    OemKeyValue kv = ParseKeyValue(line);
                    if (kv.key == "REF_FRAME")
                    {
                        m_parserState = Oem_AfterRefFrame;
                        if (kv.value == "EME2000")
                        {
                            coordSys = sta::COORDSYS_EME_J2000;
                        }
                        else if (kv.value == "ECLIP2000")
                        {
                            coordSys = sta::COORDSYS_ECLIPTIC_J2000;
                        }
                        else
                        {
                            raiseError("Unsupported reference frame " + kv.value);
                        }
                    }
                    else
                    {
                        raiseError("Reference frame expected");
                    }
                }
                break;

            case Oem_AfterRefFrame:
                {
                    OemKeyValue kv = ParseKeyValue(line);
                    if (kv.key == "REF_FRAME_EPOCH")
                    {
                    }
                    else
                    {
                        skip = true;
                    }
                    m_parserState = Oem_AfterRefFrameEpoch;
                }
                break;

            case Oem_AfterRefFrameEpoch:
                {
                    OemKeyValue kv = ParseKeyValue(line);
                    if (kv.key == "TIME_SYSTEM")
                    {
                        m_parserState = Oem_AfterTimeSystem;
                        if (kv.value != "TDB")
                        {
                            raiseError("Unsupported time system " + kv.value);
                        }
                    }
                    else
                    {
                        raiseError("Time system expected");
                    }
                }
                break;

            case Oem_AfterTimeSystem:
                {
                    OemKeyValue kv = ParseKeyValue(line);
                    if (kv.key == "START_TIME")
                    {
                        m_parserState = Oem_AfterStartTime;
                    }
                    else
                    {
                        raiseError("Start time expected");
                    }
                }
                break;

            case Oem_AfterStartTime:
                {
                    OemKeyValue kv = ParseKeyValue(line);
                    if (kv.key == "USEABLE_START_TIME")
                    {
                    }
                    else
                    {
                        skip = true;
                    }
                    m_parserState = Oem_AfterUseableStartTime;
                }
                break;

            case Oem_AfterUseableStartTime:
                {
                    OemKeyValue kv = ParseKeyValue(line);
                    if (kv.key == "USEABLE_STOP_TIME")
                    {
                    }
                    else
                    {
                        skip = true;
                    }
                    m_parserState = Oem_AfterUseableStopTime;
                }
                break;

            case Oem_AfterUseableStopTime:
                {
                    OemKeyValue kv = ParseKeyValue(line);
                    if (kv.key == "STOP_TIME")
                    {
                        m_parserState = Oem_AfterStopTime;
                    }
                    else
                    {
                        raiseError("Stop time expected");
                    }
                }
                break;

            case Oem_AfterStopTime:
                {
                    OemKeyValue kv = ParseKeyValue(line);
                    if (kv.key == "INTERPOLATION")
                    {
                    }
                    else
                    {
                        skip = true;
                    }
                    m_parserState = Oem_AfterInterpolation;
                }
                break;

            case Oem_AfterInterpolation:
                {
                    OemKeyValue kv = ParseKeyValue(line);
                    if (kv.key == "INTERPOLATION_DEGREE")
                    {
                    }
                    else
                    {
                        skip = true;
                    }
                    m_parserState = Oem_AfterInterpolationDegree;
                }
                break;

            case Oem_AfterInterpolationDegree:
                if (line == "META_STOP")
                {
                    m_parserState = Oem_AfterMetaStop;
                    trajectory = new ScenarioExternalType();

                    int trajectoryIndex = sc->SCMission()->TrajectoryPlan()->AbstractTrajectory().size();

                    trajectory->CentralBody()->setName(center->name());
                    trajectory->setCoordinateSystem(sta::CoordinateSystem(coordSys).name());
                    trajectory->ElementIdentifier()->setName(QString("%1 - %2").arg(objectName).arg(trajectoryIndex + 1));
                    trajectory->ElementIdentifier()->setColorName("Yellow");

                    sc->SCMission()->TrajectoryPlan()->AbstractTrajectory().append(QSharedPointer<ScenarioAbstractTrajectoryType>(trajectory));
                }
                else
                {
                    raiseError("End of metadata (META_STOP) expected");
                }
                break;

            case Oem_AfterMetaStop:
                if (line.startsWith("COMMENT"))
                {
                    // Ignore the comment
                }
                else
                {
                    skip = true;
                    m_parserState = Oem_EphemerisData;
                }
                break;

            case Oem_EphemerisData:
                if (line == "META_START")
                {
                    m_parserState = Oem_MetaStart;
                }
                else
                {
                    // Parse the ephemeris line
                    QStringList values = line.split(whiteSpaceRegExp);
                    if (values.size() != 7)
                    {
                        raiseError("Bad or unsupported ephemeris data record");
                    }
                    else
                    {
                        QDateTime dateTime;
                        int secondsDecimal = values[0].lastIndexOf('.');
                        if (secondsDecimal > 0)
                        {
                            bool msecOk = false;
                            double sec = values[0].right(values[0].length() - secondsDecimal).toDouble(&msecOk);
                            if (msecOk)
                            {
                                dateTime = QDateTime::fromString(values[0].left(secondsDecimal), Qt::ISODate);
                                dateTime.setTimeSpec(Qt::UTC);
                                int msec = (int) (sec * 1000.0);
                                dateTime = dateTime.addMSecs((int) (sec * 1000.0));
                            }
                        }
                        else
                        {
                            dateTime = QDateTime::fromString(values[0], Qt::ISODate);
                        }

                        if (!dateTime.isValid())
                        {
                            raiseError(QString("Bad time value in ephemeris data (%1)").arg(values[0]));
                        }
                        else
                        {
                            bool stateValid = true;
                            double state[6];
                            for (int i = 0; i < 6; ++i)
                            {
                                bool ok = false;
                                state[i] = values[i + 1].toDouble(&ok);
                                if (!ok)
                                {
                                    stateValid = false;
                                }
                            }

                            if (!stateValid)
                            {
                                raiseError("Non-number in ephemeris data");
                            }
                            else
                            {
                                trajectory->TimeTags().append(dateTime);
                                for (int i = 0; i < 6; ++i)
                                {
                                    trajectory->States() << state[i];
                                }
                            }
                        }
                    }
                }
                break;

            default:
                m_parserState = Oem_Error;
                break;
            }
        }
    }

    // Validate trajectory by making sure that there are no overlapping segments or gaps
    if (sc)
    {
        for (int i = 1; i < sc->SCMission()->TrajectoryPlan()->AbstractTrajectory().size(); ++i)
        {
            ScenarioExternalType* prev = dynamic_cast<ScenarioExternalType*>(sc->SCMission()->TrajectoryPlan()->AbstractTrajectory().at(i - 1).data());
            ScenarioExternalType* curr = dynamic_cast<ScenarioExternalType*>(sc->SCMission()->TrajectoryPlan()->AbstractTrajectory().at(i).data());
            if (prev && curr && !prev->TimeTags().isEmpty() && !curr->TimeTags().isEmpty())
            {
                QDateTime prevEnd = prev->TimeTags().last();
                QDateTime currStart = curr->TimeTags().first();
                if (currStart < prevEnd)
                {
                    raiseError(QString("Ephemeris segments %1 and %2 overlap.").arg(i - 1).arg(i));
                }
                else if (currStart > prevEnd)
                {
                    raiseError(QString("Gap between ephemeris segments %1 and %2.").arg(i - 1).arg(i));
                }
            }
        }
    }

    if (m_parserState == Oem_Error)
    {
        qDebug() << "Error while importing OEM file: " << errorMessage();
        delete scenario;
        scenario = NULL;
    }
    else
    {
        scenario->setName(objectName);
        sc->setName(objectName);
        sc->ElementIdentifier()->setName(objectName);
    }

    return scenario;
}
Пример #27
0
bool Store::parseStream()
{
    Protocol::ModifyItemsCommand cmd(m_command);

    //parseCommand();

    DataStore *store = connection()->storageBackend();
    Transaction transaction(store);
    ExternalPartStorageTransaction storageTrx;
    // Set the same modification time for each item.
    QDateTime modificationtime = QDateTime::currentDateTimeUtc();
    if (DbType::type(store->database()) != DbType::Sqlite) {
        // Remove milliseconds from the modificationtime. PSQL and MySQL don't
        // support milliseconds in DATETIME column, so FETCHed Items will report
        // time without milliseconds, while this command would return answer
        // with milliseconds
        modificationtime = modificationtime.addMSecs(-modificationtime.time().msec());
    }

    // retrieve selected items
    SelectQueryBuilder<PimItem> qb;
    ItemQueryHelper::scopeToQuery(cmd.items(), connection()->context(), qb);
    if (!qb.exec()) {
        return failureResponse("Unable to retrieve items");
    }
    PimItem::List pimItems = qb.result();
    if (pimItems.isEmpty()) {
        return failureResponse("No items found");
    }

    for (int i = 0; i < pimItems.size(); ++i) {
        if (cmd.oldRevision() > -1) {
            // check for conflicts if a resources tries to overwrite an item with dirty payload
            const PimItem &pimItem = pimItems.at(i);
            if (connection()->isOwnerResource(pimItem)) {
                if (pimItem.dirty()) {
                    const QString error = QStringLiteral("[LRCONFLICT] Resource %1 tries to modify item %2 (%3) (in collection %4) with dirty payload, aborting STORE.");
                    return failureResponse(
                        error.arg(pimItem.collection().resource().name())
                             .arg(pimItem.id())
                             .arg(pimItem.remoteId()).arg(pimItem.collectionId()));
                }
            }

            // check and update revisions
            if (pimItems.at(i).rev() != (int) cmd.oldRevision()) {
                return failureResponse("[LLCONFLICT] Item was modified elsewhere, aborting STORE.");
            }
        }
    }

    PimItem &item = pimItems.first();

    QSet<QByteArray> changes;
    qint64 partSizes = 0;
    qint64 size = 0;

    bool flagsChanged = false;
    bool tagsChanged = false;

    if (cmd.modifiedParts() & Protocol::ModifyItemsCommand::AddedFlags) {
        if (!addFlags(pimItems, cmd.addedFlags(), flagsChanged)) {
            return failureResponse("Unable to add item flags");
        }
    }

    if (cmd.modifiedParts() & Protocol::ModifyItemsCommand::RemovedFlags) {
        if (!deleteFlags(pimItems, cmd.removedFlags(), flagsChanged)) {
            return failureResponse("Unable to remove item flags");
        }
    }

    if (cmd.modifiedParts() & Protocol::ModifyItemsCommand::Flags) {
        if (!replaceFlags(pimItems, cmd.flags(), flagsChanged)) {
            return failureResponse("Unable to reset flags");
        }
    }

    if (flagsChanged) {
        changes << AKONADI_PARAM_FLAGS;
    }

    if (cmd.modifiedParts() & Protocol::ModifyItemsCommand::AddedTags) {
        if (!addTags(pimItems, cmd.addedTags(), tagsChanged)) {
            return failureResponse("Unable to add item tags");
        }
    }

    if (cmd.modifiedParts() & Protocol::ModifyItemsCommand::RemovedTags) {
        if (!deleteTags(pimItems, cmd.removedTags(), tagsChanged)) {
            return failureResponse("Unabel to remove item tags");
        }
    }

    if (cmd.modifiedParts() & Protocol::ModifyItemsCommand::Tags) {
        if (!replaceTags(pimItems, cmd.tags(), tagsChanged)) {
            return failureResponse("Unable to reset item tags");
        }
    }

    if (tagsChanged) {
        changes << AKONADI_PARAM_TAGS;
    }

    if (item.isValid() && cmd.modifiedParts() & Protocol::ModifyItemsCommand::RemoteID) {
        if (item.remoteId() != cmd.remoteId()) {
            if (!connection()->isOwnerResource(item)) {
                return failureResponse("Only resources can modify remote identifiers");
            }
            item.setRemoteId(cmd.remoteId());
            changes << AKONADI_PARAM_REMOTEID;
        }
    }

    if (item.isValid() && cmd.modifiedParts() & Protocol::ModifyItemsCommand::GID) {
        if (item.gid() != cmd.gid()) {
            item.setGid(cmd.gid());
        }
        changes << AKONADI_PARAM_GID;
    }

    if (item.isValid() && cmd.modifiedParts() & Protocol::ModifyItemsCommand::RemoteRevision) {
        if (item.remoteRevision() != cmd.remoteRevision()) {
            if (!connection()->isOwnerResource(item)) {
                return failureResponse("Only resources can modify remote revisions");
            }
            item.setRemoteRevision(cmd.remoteRevision());
            changes << AKONADI_PARAM_REMOTEREVISION;
        }
    }

    if (item.isValid() && !cmd.dirty()) {
        item.setDirty(false);
    }

    if (item.isValid() && cmd.modifiedParts() & Protocol::ModifyItemsCommand::Size) {
        size = cmd.itemSize();
        changes << AKONADI_PARAM_SIZE;
    }

    if (item.isValid() && cmd.modifiedParts() & Protocol::ModifyItemsCommand::RemovedParts) {
        if (!cmd.removedParts().isEmpty()) {
            if (!store->removeItemParts(item, cmd.removedParts())) {
                return failureResponse("Unable to remove item parts");
            }
            Q_FOREACH (const QByteArray &part, cmd.removedParts()) {
                changes.insert(part);
            }
        }
    }

    if (item.isValid() && cmd.modifiedParts() & Protocol::ModifyItemsCommand::Parts) {
        PartStreamer streamer(connection(), item, this);
        connect(&streamer, &PartStreamer::responseAvailable,
                this, static_cast<void(Handler::*)(const Protocol::Command &)>(&Handler::sendResponse));
        Q_FOREACH (const QByteArray &partName, cmd.parts()) {
            qint64 partSize = 0;
            if (!streamer.stream(true, partName, partSize)) {
                return failureResponse(streamer.error());
            }

            changes.insert(partName);
            partSizes += partSize;
        }
    }
Пример #28
0
QDateTime operator+( const QDateTime &start, QgsInterval interval )
{
  return start.addMSecs( static_cast<qint64>( interval.seconds() * 1000.0 ) );
}
Пример #29
0
void ChatForm::loadHistory(QDateTime since, bool processUndelivered)
{
    QDateTime now = QDateTime::currentDateTime();

    if (since > now)
        return;

    if (earliestMessage)
    {
        if (*earliestMessage < since)
            return;
        if (*earliestMessage < now)
        {
            now = *earliestMessage;
            now = now.addMSecs(-1);
        }
    }

    auto msgs = HistoryKeeper::getInstance()->getChatHistory(HistoryKeeper::ctSingle, f->getToxID().publicKey, since, now);

    ToxID storedPrevId;
    std::swap(storedPrevId, previousId);
    QList<ChatActionPtr> historyMessages;

    QDate lastDate(1,0,0);
    for (const auto &it : msgs)
    {
        // Show the date every new day
        QDateTime msgDateTime = it.timestamp.toLocalTime();
        QDate msgDate = msgDateTime.date();
        if (msgDate > lastDate)
        {
            lastDate = msgDate;
            historyMessages.append(genSystemInfoAction(msgDate.toString(),"",QDateTime()));
        }

        // Show each messages
        ToxID msgSender = ToxID::fromString(it.sender);
        MessageActionPtr ca = genMessageActionAction(msgSender, it.message, false, msgDateTime);
        if (it.isSent || !msgSender.isMine())
        {
            ca->markAsSent();
        } else {
            if (processUndelivered)
            {
                int rec;
                if (ca->isAction())
                    rec = Core::getInstance()->sendAction(f->getFriendID(), ca->getRawMessage());
                else
                    rec = Core::getInstance()->sendMessage(f->getFriendID(), ca->getRawMessage());
                registerReceipt(rec, it.id, ca);
            }
        }
        historyMessages.append(ca);
    }
    std::swap(storedPrevId, previousId);

    int savedSliderPos = chatWidget->verticalScrollBar()->maximum() - chatWidget->verticalScrollBar()->value();

    if (earliestMessage != nullptr)
        *earliestMessage = since;

    chatWidget->insertMessagesTop(historyMessages);

    savedSliderPos = chatWidget->verticalScrollBar()->maximum() - savedSliderPos;
    chatWidget->verticalScrollBar()->setValue(savedSliderPos);
}
Пример #30
0
/*!
    \fn Convert::dateTime(const QString& mSeconds)
 */
QDateTime Convert::dateTime(const QString& mSeconds) {
    static QDateTime zeroTime(QDate(1970,1,1), QTime(0,0), Qt::UTC);
    return zeroTime.addMSecs(mSeconds.toULongLong());
}