コード例 #1
0
vCardProperty vCardProperty::createBirthday(const QDateTime& birthday, const vCardParamList& params)
{
    return vCardProperty(VC_BIRTHDAY, birthday.toString("yyyy-MM-ddThh:mm:ssZ"), params);
}
コード例 #2
0
DateTime::Ptr DateTime::fromDateTime(const QDateTime &dt)
{
    Q_ASSERT(dt.isValid());
    return DateTime::Ptr(new DateTime(dt));
}
コード例 #3
0
ファイル: bitcoingui.cpp プロジェクト: dyljp/rosecoin
void BitcoinGUI::setNumBlocks(int count, int nTotalBlocks)
{
    // don't show / hide progressBar and it's label if we have no connection(s) to the network
    if (!clientModel || clientModel->getNumConnections() == 0)
    {
        progressBarLabel->setVisible(false);
        progressBar->setVisible(false);

        return;
    }

    QString tooltip;

    if(count < nTotalBlocks)
    {
        int nRemainingBlocks = nTotalBlocks - count;
        float nPercentageDone = count / (nTotalBlocks * 0.01f);

        if (clientModel->getStatusBarWarnings() == "")
        {
            progressBarLabel->setText(tr("Synchronizing with network..."));
            progressBarLabel->setVisible(true);
            progressBar->setFormat(tr("~%n block(s) remaining", "", nRemainingBlocks));
            progressBar->setMaximum(nTotalBlocks);
            progressBar->setValue(count);
            progressBar->setVisible(true);
        }
        else
        {
            progressBarLabel->setText(clientModel->getStatusBarWarnings());
            progressBarLabel->setVisible(true);
            progressBar->setVisible(false);
        }
        tooltip = tr("Downloaded %1 of %2 blocks of transaction history (%3% done).").arg(count).arg(nTotalBlocks).arg(nPercentageDone, 0, 'f', 2);
    }
    else
    {
        if (clientModel->getStatusBarWarnings() == "")
            progressBarLabel->setVisible(false);
        else
        {
            progressBarLabel->setText(clientModel->getStatusBarWarnings());
            progressBarLabel->setVisible(true);
        }
        progressBar->setVisible(false);
        tooltip = tr("Downloaded %1 blocks of transaction history.").arg(count);
    }

    tooltip = tr("Current difficult %1.").arg(clientModel->GetDifficulty()) + QString("<br>") + tooltip;

    QDateTime now = QDateTime::currentDateTime();
    QDateTime lastBlockDate = clientModel->getLastBlockDate();
    int secs = lastBlockDate.secsTo(now);
    QString text;

    // Represent time from last generated block in human readable text
    if(secs <= 0)
    {
        // Fully up to date. Leave text empty.
    }
    else if(secs < 60)
    {
        text = tr("%n second(s) ago","",secs);
    }
    else if(secs < 60*60)
    {
        text = tr("%n minute(s) ago","",secs/60);
    }
    else if(secs < 24*60*60)
    {
        text = tr("%n hour(s) ago","",secs/(60*60));
    }
    else
    {
        text = tr("%n day(s) ago","",secs/(60*60*24));
    }

    // Set icon state: spinning if catching up, tick otherwise
    if(secs < 90*60 && count >= nTotalBlocks)
    {
        tooltip = tr("Up to date") + QString(".<br>") + tooltip;
        labelBlocksIcon->setPixmap(QIcon(":/icons/synced").pixmap(STATUSBAR_ICONSIZE, STATUSBAR_ICONSIZE));

        overviewPage->showOutOfSyncWarning(false);
    }
    else
    {
        tooltip = tr("Catching up...") + QString("<br>") + tooltip;
        labelBlocksIcon->setMovie(syncIconMovie);
        syncIconMovie->start();

        overviewPage->showOutOfSyncWarning(true);
    }

    if(!text.isEmpty())
    {
        tooltip += QString("<br>");
        tooltip += tr("Last received block was generated %1.").arg(text);
    }

    // Don't word-wrap this (fixed-width) tooltip
    tooltip = QString("<nobr>") + tooltip + QString("</nobr>");

    labelBlocksIcon->setToolTip(tooltip);
    progressBarLabel->setToolTip(tooltip);
    progressBar->setToolTip(tooltip);
}
コード例 #4
0
static QString toString( const QDateTime &dateTime )
{
  return dateTime.toString();
}
コード例 #5
0
/* get the list of Neighbours from the RsIface.  */
void NetworkDialog::insertConnect()
{
	if (!rsPeers)
	{
		return;
	}

	std::list<std::string> neighs;
	std::list<std::string>::iterator it;
	rsPeers->getOthersList(neighs);

	/* get a link to the table */
        QTreeWidget *connectWidget = ui.connecttreeWidget;
	QTreeWidgetItem *oldSelect = getCurrentNeighbour();
	QTreeWidgetItem *newSelect = NULL;
	std::string oldId;
	if (oldSelect)
	{
		oldId = (oldSelect -> text(9)).toStdString();
	}

        QList<QTreeWidgetItem *> items;
	for(it = neighs.begin(); it != neighs.end(); it++)
	{
		RsPeerDetails detail;
		if (!rsPeers->getPeerDetails(*it, detail))
		{
			continue; /* BAD */
		}

		/* make a widget per friend */
           	QTreeWidgetItem *item = new QTreeWidgetItem((QTreeWidget*)0);

		/* add all the labels */
		
	        /* (0) Status Icon */
		item -> setText(0, "");

		/* (1) Accept/Deny */
		if (detail.state & RS_PEER_STATE_FRIEND)
			item -> setText(1, tr("Trusted"));
		else
			item -> setText(1, tr("Denied"));

		if (rsPeers->isTrustingMe(detail.id) || detail.lastConnect>0)
			item -> setText(2, tr("Is trusting me"));
		else
			item -> setText(2, tr("Unknown"));

		/* (3) Last Connect */
		{
			std::ostringstream out;
			// Show anouncement if a friend never was connected.
			if (detail.lastConnect==0 ) 
				item -> setText(3, tr("Never seen"));
			else 
			{
				// Dont Show a timestamp in RS calculate the day
				QDateTime datum = QDateTime::fromTime_t(detail.lastConnect);
				// out << datum.toString(Qt::LocalDate);
				QString stime = datum.toString(Qt::LocalDate);
				item -> setText(3, stime);
			}
		}
		
        	/* (4) Person */
		item -> setText(4, QString::fromStdString(detail.name));
		
		/* (5) Peer Address */
		{
			std::ostringstream out;
			if(detail.state & RS_PEER_STATE_FRIEND) {
				out << detail.localAddr << ":";
				out << detail.localPort << "/";
				out << detail.extAddr << ":";
				out << detail.extPort;
			} else {
				// No Trust => no IP Information
				out << "0.0.0.0:0/0.0.0.0:0";
			}
                	item -> setText(5, QString::fromStdString(out.str()));
		}

		/* Others */
		item -> setText(6, QString::fromStdString(detail.org));
		item -> setText(7, QString::fromStdString(detail.location));
		item -> setText(8, QString::fromStdString(detail.email));

		{
			item -> setText(9, QString::fromStdString(detail.id));
			if ((oldSelect) && (oldId == detail.id))
			{
				newSelect = item;
			}
		}

		//item -> setText(10, QString::fromStdString(detail.authcode));

		/**
		* Determinated the Background Color
		*/
		QColor backgrndcolor;
		
		if (detail.state & RS_PEER_STATE_FRIEND)
		{
			item -> setIcon(0,(QIcon(IMAGE_AUTHED)));
			backgrndcolor=Qt::green;
		}
		else
		{
			if (rsPeers->isTrustingMe(detail.id))
			{
				backgrndcolor=Qt::magenta;
				item -> setIcon(0,(QIcon(IMAGE_TRUSTED)));
				for(int k=0;k<8;++k)
					item -> setToolTip(k,QString::fromStdString(detail.name) + QString(tr(" is trusting you. \nRight-click and select 'make friend' to be able to connect."))) ;
			}
			else if (detail.trustLvl > RS_TRUST_LVL_MARGINAL)
			{
				backgrndcolor=Qt::cyan;
				item -> setIcon(0,(QIcon(IMAGE_DENIED)));
			}
			else if (detail.lastConnect < 10000) /* 3 hours? */
			{
				backgrndcolor=Qt::yellow;
				item -> setIcon(0,(QIcon(IMAGE_DENIED)));
			}
			else
			{
				backgrndcolor=Qt::gray;
				item -> setIcon(0,(QIcon(IMAGE_DENIED)));
			}
		}

		// Color each Background column in the Network Tab except the first one => 1-9
		// whith the determinated color
		for(int i = 1; i <10; i++)
			item -> setBackground(i,QBrush(backgrndcolor));

		/* add to the list */
		items.append(item);
	}

	// add self to network.
	RsPeerDetails pd ;
	if(rsPeers->getPeerDetails(rsPeers->getOwnId(),pd)) 
	{
		QTreeWidgetItem *self_item = new QTreeWidgetItem((QTreeWidget*)0);

		self_item->setText(1,"N/A");
		self_item->setText(2,"N/A");
		self_item->setText(3,"N/A");
		self_item->setText(4,QString::fromStdString(pd.name) + " (yourself)") ;

		std::ostringstream out;
		out << pd.localAddr << ":" << pd.localPort << "/" << pd.extAddr << ":" << pd.extPort;
		self_item->setText(5, QString::fromStdString(out.str()));
		self_item->setText(6, QString::fromStdString(pd.org));
		self_item->setText(7, QString::fromStdString(pd.location));
		self_item->setText(8, QString::fromStdString(pd.email));
		self_item->setText(9, QString::fromStdString(pd.id));

		// Color each Background column in the Network Tab except the first one => 1-9
		for(int i=1;i<10;++i)
		{
			self_item->setBackground(i,QBrush(Qt::green));
		}
		self_item->setIcon(0,(QIcon(IMAGE_AUTHED)));
		items.append(self_item);
	}

	/* remove old items ??? */
	connectWidget->clear();
	connectWidget->setColumnCount(10);	

	/* add the items in! */
	connectWidget->insertTopLevelItems(0, items);
	if (newSelect)
	{
		connectWidget->setCurrentItem(newSelect);
	}

	connectWidget->update(); /* update display */
}
コード例 #6
0
ファイル: mainwindow.cpp プロジェクト: uh-adapsys/accompany
void MainWindow::fillSensorStateTable()
{
    if (!checkDates()) return;

    QString seqQuery;

    // get the latest row from the existing sensorStateHistory into a temporary table

    seqQuery  = "DROP TEMPORARY TABLE IF EXISTS tempState";

 //   qDebug() << seqQuery;

    query.clear();

    if (!query.exec(seqQuery))
    {
        QMessageBox msgBox;
        msgBox.setIcon(QMessageBox::Warning);

        msgBox.setText("Cannot drop temporary table tempState!");
        msgBox.exec();
        return;
    }

    seqQuery  = "select max(lastUpdate) from SensorStateHistory";

 //   qDebug() << seqQuery;

    query.clear();

    if (!query.exec(seqQuery))
    {
        QMessageBox msgBox;
        msgBox.setIcon(QMessageBox::Warning);

        msgBox.setText("Cannot select from sensorStateHistory!");
        msgBox.exec();
        return;
    }

    // insert the lateset row from sensorStateHistory to temp table

    QDateTime lastDate;

    while (query.next())
    {
        lastDate = query.value(0).toDateTime();

    }


    qDebug()<<"Latest date on sensorStateHistory is: " << lastDate.toString("yyyy-MM-dd hh:mm:ss");

    seqQuery  = "CREATE TEMPORARY TABLE tempState ( select * from SensorStateHistory where lastUpdate =  '";
    seqQuery += lastDate.toString("yyyy-MM-dd hh:mm:ss") + "')";


 //   qDebug() << seqQuery;

    query.clear();

    if (!query.exec(seqQuery))
    {
        QMessageBox msgBox;
        msgBox.setIcon(QMessageBox::Warning);

        msgBox.setText("Cannot create temporary table tempState!");
        msgBox.exec();

        qDebug()<<query.lastError();
        qDebug()<<query.executedQuery();


        return;
    }


    // get the current values from behaviourLog


    if (lv == "BATCH" || "BATCHNORM")
    {
        seqQuery  = "select timestamp,sensorId,status,trainingNumber from " + behTable + " where sensorID < 61 ORDER BY trainingNumber, timestamp";
    }
    else
    {
        seqQuery  = "select timestamp,sensorId,status,trainingNumber from " + behTable + " where sensorID < 61 and timestamp between '";
        seqQuery += ui->dateFrom->dateTime().toString("yyyy-MM-dd hh:mm:ss");
        seqQuery += "' and '";
        seqQuery += ui->dateTo->dateTime().toString("yyyy-MM-dd hh:mm:ss") + "' ORDER BY timestamp";
    }
    qDebug() << seqQuery;


    query.clear();

    if (!query.exec(seqQuery))
    {
        QMessageBox msgBox;
        msgBox.setIcon(QMessageBox::Warning);


        msgBox.setText("Cannot select from SensorLog table!");
        msgBox.exec();
        return;

    }



    int numRowsRead = query.numRowsAffected();
    int numRowsProcessed = 0;
    int numRowsInserted = 0;



    while (query.next())

    {

        if (numRowsProcessed%50 == 0)
        {
            qDebug()<<"Processed " << numRowsProcessed << " rows...";

        }



         qDebug()<<query.value(0).toDateTime().toString("yyyy-MM-dd hh:mm:ss");
        qDebug()<< query.value(1).toString();
        qDebug()<< query.value(2).toString();
        qDebug()<< query.value(3).toString();

        qDebug()<< lastDate.toString("yyyy-MM-dd hh:mm:ss");

        // update the temp table and insert to db

        if (query.value(0).toDateTime() == lastDate)  // dates the same, update row with sensor values
        {

            qDebug()<<"Same - updating temp table";

             if (!updateTempTable())
             {
                 QMessageBox msgBox;
                 msgBox.setIcon(QMessageBox::Warning);
                 msgBox.setText("Problem updating temp table!");
                 msgBox.exec();
                 return;
             }

            numRowsProcessed++;
        }

        if (query.value(0).toDateTime() > lastDate) // new event, insert a new stateHistory row
        {

            qDebug() << "Greater";

            if (numRowsProcessed > 0)   // insert the current row on temp to stateHistory
            {
       //         qDebug()<< "insert current temp to stateHistory";

                seqQuery  = "insert INTO SensorStateHistory select * from tempState";

      //         qDebug() << seqQuery;

                QSqlQuery insertQuery;

                insertQuery.clear();

                if (!insertQuery.exec(seqQuery))
                {
                    QMessageBox msgBox;
                    msgBox.setIcon(QMessageBox::Warning);

                    msgBox.setText("Cannot insert into sensorStateHistory!");
                    msgBox.exec();
                    msgBox.setText(insertQuery.lastError().text());
                    msgBox.exec();
                    qDebug()<<insertQuery.lastError();
                    qDebug()<<insertQuery.executedQuery();
                    return;
                }

                numRowsInserted++;

            }

            // now update it

            if (!updateTempTable())
            {
                QMessageBox msgBox;
                msgBox.setIcon(QMessageBox::Warning);
                msgBox.setText("Problem updating temp table!");
                msgBox.exec();
                return;
            }


            numRowsProcessed++;

//            QDateTime latestDate   = query.value(0).toDateTime();

//            int days = lastDate.daysTo ( latestDate ) ;

//            QTime when = QTime ( 0, 0, 0, 0 ) ;

//            when = when.addSecs ( lastDate.addDays(days).secsTo( latestDate ) ) ;

     //       qDebug()  << latestDate.toString( "M/d/yyyy h:mm:ss AP" )
     //             << " - "
     //             << lastDate.toString( "M/d/yyyy h:mm:ss AP" )
     //             << " = "
     //             << days << when.toString( ".HH:mm:ss" ) ;

            lastDate = query.value(0).toDateTime();
        }

    }

    // final row

    if (numRowsProcessed > 0)   // insert the current row on temp to stateHistory
    {
  //      qDebug()<< "insert final temp to stateHistory";

  //      seqQuery  = "insert INTO SensorStateHistory select * from tempState";

  //      qDebug() << seqQuery;

        QSqlQuery insertQuery;

        insertQuery.clear();

        if (!insertQuery.exec(seqQuery))
        {
            QMessageBox msgBox;
            msgBox.setIcon(QMessageBox::Warning);

            msgBox.setText("Cannot insert into sensorStateHistory!");
            msgBox.exec();
            msgBox.setText(insertQuery.lastError().text());
            msgBox.exec();
            qDebug()<<insertQuery.lastError();
            qDebug()<<insertQuery.executedQuery();
            return;
        }

        numRowsInserted++;
    }


    qDebug()<<"Rows Read: " << numRowsRead << "Rows Procesed: " << numRowsProcessed << "Rows inserted: " << numRowsInserted;


}
コード例 #7
0
ファイル: event.cpp プロジェクト: opieproject/opie
static Event parseVObject( VObject *obj )
{
    Event e;

    bool haveAlarm = FALSE;
    bool haveStart = FALSE;
    bool haveEnd = FALSE;
    QDateTime alarmTime;
    Event::SoundTypeChoice soundType = Event::Silent;

    VObjectIterator it;
    initPropIterator( &it, obj );
    while( moreIteration( &it ) ) {
        VObject *o = nextVObject( &it );
        QCString name = vObjectName( o );
        QCString value = vObjectStringZValue( o );
        if ( name == VCDTstartProp ) {
            e.setStart( TimeConversion::fromISO8601( value ) );
            haveStart = TRUE;
        }
        else if ( name == VCDTendProp ) {
            e.setEnd( TimeConversion::fromISO8601( value ) );
            haveEnd = TRUE;
        }
        else if ( name == "X-Qtopia-NOTES" ) {
            e.setNotes( value );
        }
        else if ( name == VCDescriptionProp ) {
            e.setDescription( value );
        }
        else if ( name == VCLocationProp ) {
            e.setLocation( value );
        }
        else if ( name == VCAudioContentProp ) {
            haveAlarm = TRUE;
            VObjectIterator nit;
            initPropIterator( &nit, o );
            while( moreIteration( &nit ) ) {
                VObject *o = nextVObject( &nit );
                QCString name = vObjectName( o );
                QCString value = vObjectStringZValue( o );
                if ( name == VCRunTimeProp )
                    alarmTime = TimeConversion::fromISO8601( value );
                else if ( name == VCAudioContentProp ) {
                    if ( value == "silent" )
                        soundType = Event::Silent;
                    else
                        soundType = Event::Loud;
                }
            }
        }
        else if ( name == "X-Qtopia-TIMEZONE") {
            e.setTimeZone( value );
        }
        else if ( name == "X-Qtopia-AllDay" ) {
            e.setType( Event::AllDay );
        }
#if 0
        else {
            printf("Name: %s, value=%s\n", name.data(), vObjectStringZValue( o ) );
            VObjectIterator nit;
            initPropIterator( &nit, o );
            while( moreIteration( &nit ) ) {
                VObject *o = nextVObject( &nit );
                QCString name = vObjectName( o );
                QString value = vObjectStringZValue( o );
                printf(" subprop: %s = %s\n", name.data(), value.latin1() );
            }
        }
#endif
    }

    if ( !haveStart && !haveEnd )
        e.setStart( QDateTime::currentDateTime() );

    if ( !haveEnd ) {
        e.setType( Event::AllDay );
        e.setEnd( e.start() );
    }

    if ( haveAlarm ) {
        int minutes = alarmTime.secsTo( e.start() ) / 60;
        e.setAlarm( TRUE, minutes, soundType );
    }
    return e;
}
コード例 #8
0
static QVariant qtValue(CFPropertyListRef cfvalue)
{
    if (!cfvalue)
        return QVariant();

    CFTypeID typeId = CFGetTypeID(cfvalue);

    /*
        Sorted grossly from most to least frequent type.
    */
    if (typeId == CFStringGetTypeID()) {
        return QSettingsPrivate::stringToVariant(QCFString::toQString(static_cast<CFStringRef>(cfvalue)));
    } else if (typeId == CFNumberGetTypeID()) {
        CFNumberRef cfnumber = static_cast<CFNumberRef>(cfvalue);
        if (CFNumberIsFloatType(cfnumber)) {
            double d;
            CFNumberGetValue(cfnumber, kCFNumberDoubleType, &d);
            return d;
        } else {
            int i;
            qint64 ll;

            if (CFNumberGetValue(cfnumber, kCFNumberIntType, &i))
                return i;
            CFNumberGetValue(cfnumber, kCFNumberLongLongType, &ll);
            return ll;
        }
    } else if (typeId == CFArrayGetTypeID()) {
        CFArrayRef cfarray = static_cast<CFArrayRef>(cfvalue);
        QList<QVariant> list;
        CFIndex size = CFArrayGetCount(cfarray);
        bool metNonString = false;
        for (CFIndex i = 0; i < size; ++i) {
            QVariant value = qtValue(CFArrayGetValueAtIndex(cfarray, i));
            if (value.type() != QVariant::String)
                metNonString = true;
            list << value;
        }
        if (metNonString)
            return list;
        else
            return QVariant(list).toStringList();
    } else if (typeId == CFBooleanGetTypeID()) {
        return (bool)CFBooleanGetValue(static_cast<CFBooleanRef>(cfvalue));
    } else if (typeId == CFDataGetTypeID()) {
        CFDataRef cfdata = static_cast<CFDataRef>(cfvalue);
        return QByteArray(reinterpret_cast<const char *>(CFDataGetBytePtr(cfdata)),
                          CFDataGetLength(cfdata));
    } else if (typeId == CFDictionaryGetTypeID()) {
        CFDictionaryRef cfdict = static_cast<CFDictionaryRef>(cfvalue);
        CFTypeID arrayTypeId = CFArrayGetTypeID();
        int size = (int)CFDictionaryGetCount(cfdict);
        QVarLengthArray<CFPropertyListRef> keys(size);
        QVarLengthArray<CFPropertyListRef> values(size);
        CFDictionaryGetKeysAndValues(cfdict, keys.data(), values.data());

        QMultiMap<QString, QVariant> map;
        for (int i = 0; i < size; ++i) {
            QString key = QCFString::toQString(static_cast<CFStringRef>(keys[i]));

            if (CFGetTypeID(values[i]) == arrayTypeId) {
                CFArrayRef cfarray = static_cast<CFArrayRef>(values[i]);
                CFIndex arraySize = CFArrayGetCount(cfarray);
                for (CFIndex j = arraySize - 1; j >= 0; --j)
                    map.insert(key, qtValue(CFArrayGetValueAtIndex(cfarray, j)));
            } else {
                map.insert(key, qtValue(values[i]));
            }
        }
        return map;
    } else if (typeId == CFDateGetTypeID()) {
        QDateTime dt;
        dt.setTime_t((uint)kCFAbsoluteTimeIntervalSince1970);
        return dt.addSecs((int)CFDateGetAbsoluteTime(static_cast<CFDateRef>(cfvalue)));
    }
    return QVariant();
}
コード例 #9
0
QString MsgViewBase::messageText(Message *msg, bool bUnread)
{
    QString options;
    QString info;
    QString status;

    const char *icon = "message";
    const CommandDef *def = CorePlugin::m_plugin->messageTypes.find(msg->type());
    if (def)
        icon = def->icon;
    bool bDirection = false;
    if (msg->type() == MessageStatus){
        icon = "empty";
        StatusMessage *sm = static_cast<StatusMessage*>(msg);
        Client *client = NULL;
        string clientStr;
        if (msg->client())
            clientStr = msg->client();
        int n = clientStr.find_last_of('.');
        if (n >= 0){
            clientStr = clientStr.substr(0, n);
        }else{
            clientStr = "";
        }
        if (!clientStr.empty()){
            for (unsigned i = 0; i < getContacts()->nClients(); i++){
                string n = getContacts()->getClient(i)->name();
                if (n.length() < clientStr.length())
                    continue;
                n = n.substr(0, clientStr.length());
                if (clientStr == n){
                    client = getContacts()->getClient(i);
                    break;
                }
            }
        }
        if ((client == NULL) && getContacts()->nClients())
            client = getContacts()->getClient(0);
        if (client){
            for (def = client->protocol()->statusList(); def->text; def++){
                if (def->id == sm->getStatus()){
                    icon = def->icon;
                    status = i18n(def->text);
                    break;
                }
            }
        }
        options += " direction=\"2\"";
        bDirection = true;
    }else{
        MessageDef *m_def = (MessageDef*)(def->param);
        if (m_def->flags & MESSAGE_INFO){
            options += " direction=\"2\"";
            bDirection = true;
        }
    }
    info = QString("<icon>%1</icon>") .arg(icon);

    QString contactName;
    if (msg->getFlags() & MESSAGE_RECEIVED){
        if (!bDirection)
            options += " direction=\"1\"";
        Contact *contact = getContacts()->contact(msg->contact());
        if (contact){
            contactName = contact->getName();
            if (contactName.isEmpty()){
                Client *client = NULL;
                ClientDataIterator it(contact->clientData);
                void *data;
                while ((data = ++it) != NULL){
                    if (it.client()->dataName(data) == msg->client()){
                        client = it.client();
                        break;
                    }
                }
            }
        }
        if (!bUnread){
            for (list<msg_id>::iterator it = CorePlugin::m_plugin->unread.begin(); it != CorePlugin::m_plugin->unread.end(); ++it){
                msg_id &m = (*it);
                if ((m.id == msg->id()) &&
                        (m.contact == msg->contact()) &&
                        (m.client == msg->client())){
                    bUnread = true;
                    break;
                }
            }
        }
        if (bUnread)
            options += " unread=\"1\"";
    }else{
        if (!bDirection)
            options += " direction=\"0\"";
        contactName = getContacts()->owner()->getName();
    }
    if (contactName.isEmpty())
        contactName = "???";
    info += QString("<from>%1</from>") .arg(quoteString(contactName));
    QString id = QString::number(msg->id());
    id += ",";
    if (msg->getBackground() != msg->getForeground())
        id += QString::number(msg->getBackground() & 0xFFFFFF);
    string client_str;
    if (msg->client())
        client_str = msg->client();
    if (!client_str.empty()){
        id += ",";
        id += quoteString(client_str.c_str());
    }
    if (m_cut.size()){
        id += ",";
        id += QString::number(m_cut.size());
    }
    info += "<id>";
    info += id;
    info += "</id>";

    QString icons;
    if (msg->getFlags() & MESSAGE_SECURE)
        options += " encrypted=\"1\"";
    if (msg->getFlags() & MESSAGE_URGENT)
        options += " urgent=\"1\"";
    if (msg->getFlags() & MESSAGE_LIST)
        options += " list=\"1\"";

    QString s;
    QDateTime t;
    t.setTime_t(msg->getTime());
    info += s.sprintf("<time><date>%%1</date><hour>%02u</hour><minute>%02u</minute><second>%02u</second></time>",
                      t.time().hour(), t.time().minute(), t.time().second()) .arg(formatDate(msg->getTime()));

    s = "<?xml version=\"1.0\"?><message";
    s += options;
    s += ">";
    s += info;

    QString msgText;
    if (msg->type() != MessageStatus){
        msgText = msg->presentation();
        if (msgText.isEmpty()){
            unsigned type = msg->baseType();
            CommandDef *cmd = CorePlugin::m_plugin->messageTypes.find(type);
            if (cmd){
                MessageDef *def = (MessageDef*)(cmd->param);
                msgText = i18n(def->singular, def->plural, 1);
                int n = msgText.find("1 ");
                if (n == 0){
                    msgText = msgText.mid(2);
                }else if (n > 0){
                    msgText = msgText.left(n);
                }
                msgText = QString("<p>") + msgText + "</p>";
            }
            QString text = msg->getRichText();
            msgText += text;
        }
    }else{
        msgText = status;
    }

    Event e(EventEncodeText, &msgText);
    e.process();
    msgText = parseText(msgText, CorePlugin::m_plugin->getOwnColors(), CorePlugin::m_plugin->getUseSmiles());
    msgText = QString(MSG_BEGIN) + msgText;
    s += "<body>";
    s += quoteString(msgText);
    s += "</body>";
    s += "</message>";
    XSL *p = xsl;
    if (p == NULL)
        p = CorePlugin::m_plugin->historyXSL;
    QString anchor = MSG_ANCHOR;
    anchor += id;
    anchor += "\">";
    QString res = p->process(s);
    if (res.left(3) == "<p>"){
        res = QString("<p>") + anchor + res.mid(3);
    }else{
        res = anchor + res;
    }
    return res;
}
コード例 #10
0
ファイル: optionsdialog.cpp プロジェクト: ShadowIce/textroom
void OptionsDialog::reaSettings()
{
#ifdef Q_OS_WIN32
	QSettings settings(QDir::homePath()+tr("/Application Data/")+qApp->applicationName()+".ini", QSettings::IniFormat);
#else

	QSettings settings;
#endif

	QDateTime today = QDateTime::currentDateTime();
	QString todaytext = today.toString("yyyyMMdd");
	QStringList fontS;
	QFont font;
	QFont defaultFont;

	fontS << settings.value("Font/FileName_Settings", ui.statusbarFontComboBox->currentFont() ).toString()
		<< settings.value("Font/Statistics_Settings", ui.statusbarFontComboBox->currentFont() ).toString()
		<< settings.value("Font/DefaultFont", ui.fontComboBox->currentFont() ).toString();
	
	font.fromString(fontS.at(0));
	ui.statusbarFontComboBox->setCurrentFont( font );
	ui.statusbarBoldCheckBox->setChecked( font.bold() );
	ui.statusbarItalicCheckBox->setChecked( font.italic() );
	ui.statusbarSpinBox->setValue( font.pointSize() );
	
	defaultFont.fromString(fontS.at(2));
	ui.fontComboBox->setCurrentFont( defaultFont );
	ui.fontSizeSpinBox->setValue( defaultFont.pointSize() );
	
	ui.loadOnStartCheckBox->setChecked( settings.value( "RecentFiles/OpenLastFile", true ).toBool() );
	ui.saveCursorCheckBox->setChecked( settings.value( "RecentFiles/SavePosition", true ).toBool() );
	if ( !ui.loadOnStartCheckBox->isChecked() )
		ui.saveCursorCheckBox->setEnabled( false );
	
	ui.editorWidthSpinBox->setMaximum( settings.value("MaxEditorWidth", 1024).toInt());
	ui.editorTopSpaceSpinBox->setMaximum(settings.value("MaxEditorTopSpace", 768).toInt());
	ui.editorBottomSpaceSpinBox->setMaximum(settings.value("MaxEditorBottomSpace", 1000).toInt());
	ui.wordCountSpinBox->setValue( settings.value("WordCount", 0).toInt());
	ui.pageCountSpinBox->setValue( settings.value("PageCountFormula", 250).toInt());
	ui.fullScreenCheckBox->setChecked( settings.value("WindowState/ShowFullScreen", true).toBool() );
	ui.splashScreenCheckBox->setChecked( settings.value("WindowState/ShowSplashScreen", true).toBool() );
	ui.autoSaveCheckBox->setChecked( settings.value("AutoSave", false).toBool() );
	ui.flowModeCheckBox->setChecked( settings.value("FlowMode", false).toBool() );
	ui.scrollBarCheckBox->setChecked( settings.value("ScrollBar", true).toBool() );
	ui.pageCountCheckBox->setChecked( settings.value("PageCount", false).toBool() );
	ui.soundCheckBox->setChecked( settings.value("Sound", true).toBool() );
	QString datetext = settings.value("Deadline", todaytext).toString();
	QDate date;
	QDate dateselected = date.fromString(datetext, "yyyyMMdd");
	ui.calendarWidget->setSelectedDate(dateselected);
	ui.editorWidthSpinBox->setValue( settings.value	("EditorWidth", 800).toInt());  
	ui.editorTopSpaceSpinBox->setValue( settings.value("EditorTopSpace", 0).toInt());
	ui.editorBottomSpaceSpinBox->setValue( settings.value("EditorBottomSpace", 0).toInt());
	ui.spinBox->setValue( settings.value("TimedWriting", 0 ).toInt());
	ui.dateFormat->setText( settings.value("DateFormat", "dd MMMM yyyy dddd").toString());
	ui.timeFormat->setText( settings.value("TimeFormat", "HH:MM").toString());
	
	QPalette palette;
	
	palette.setColor(ui.pbFontColor->backgroundRole(),
		fcolor = settings.value("Colors/FontColor", "#808080" ).toString());
	ui.pbFontColor->setPalette(palette);	

	palette.setColor(ui.pbStatusBarColor->backgroundRole(),
		scolor = settings.value("Colors/StatusColor", "#202020" ).toString());
	ui.pbStatusBarColor->setPalette(palette);

	
	palette.setColor(ui.pbEditorBackColor->backgroundRole(),
		bgcolor = settings.value("Colors/Background", "black" ).toString());
	ui.pbEditorBackColor->setPalette(palette);
	
	palette.setColor(ui.pbStatusBarBgColor->backgroundRole(),
		sbcolor = settings.value("Colors/StatusBg", "#808080").toString());
	ui.pbStatusBarBgColor->setPalette(palette);


}
コード例 #11
0
static QCFType<CFPropertyListRef> macValue(const QVariant &value)
{
    CFPropertyListRef result = 0;

    switch (value.type()) {
    case QVariant::ByteArray:
        {
            QByteArray ba = value.toByteArray();
            result = CFDataCreate(kCFAllocatorDefault, reinterpret_cast<const UInt8 *>(ba.data()),
                                  CFIndex(ba.size()));
        }
        break;
    // should be same as below (look for LIST)
    case QVariant::List:
    case QVariant::StringList:
    case QVariant::Polygon:
        result = macList(value.toList());
        break;
    case QVariant::Map:
        {
            /*
                QMap<QString, QVariant> is potentially a multimap,
                whereas CFDictionary is a single-valued map. To allow
                for multiple values with the same key, we store
                multiple values in a CFArray. To avoid ambiguities,
                we also wrap lists in a CFArray singleton.
            */
            QMap<QString, QVariant> map = value.toMap();
            QMap<QString, QVariant>::const_iterator i = map.constBegin();

            int maxUniqueKeys = map.size();
            int numUniqueKeys = 0;
            QVarLengthArray<QCFType<CFPropertyListRef> > cfkeys(maxUniqueKeys);
            QVarLengthArray<QCFType<CFPropertyListRef> > cfvalues(maxUniqueKeys);

            while (i != map.constEnd()) {
                const QString &key = i.key();
                QList<QVariant> values;

                do {
                    values << i.value();
                    ++i;
                } while (i != map.constEnd() && i.key() == key);

                bool singleton = (values.count() == 1);
                if (singleton) {
                    switch (values.first().type()) {
                    // should be same as above (look for LIST)
                    case QVariant::List:
                    case QVariant::StringList:
                    case QVariant::Polygon:
                        singleton = false;
                    default:
                        ;
                    }
                }

                cfkeys[numUniqueKeys] = QCFString::toCFStringRef(key);
                cfvalues[numUniqueKeys] = singleton ? macValue(values.first()) : macList(values);
                ++numUniqueKeys;
            }

            result = CFDictionaryCreate(kCFAllocatorDefault,
                                        reinterpret_cast<const void **>(cfkeys.data()),
                                        reinterpret_cast<const void **>(cfvalues.data()),
                                        CFIndex(numUniqueKeys),
                                        &kCFTypeDictionaryKeyCallBacks,
                                        &kCFTypeDictionaryValueCallBacks);
        }
        break;
    case QVariant::DateTime:
        {
            /*
                CFDate, unlike QDateTime, doesn't store timezone information.
            */
            QDateTime dt = value.toDateTime();
            if (dt.timeSpec() == Qt::LocalTime) {
                QDateTime reference;
                reference.setTime_t((uint)kCFAbsoluteTimeIntervalSince1970);
                result = CFDateCreate(kCFAllocatorDefault, CFAbsoluteTime(reference.secsTo(dt)));
            } else {
                goto string_case;
            }
        }
        break;
    case QVariant::Bool:
        result = value.toBool() ? kCFBooleanTrue : kCFBooleanFalse;
        break;
    case QVariant::Int:
    case QVariant::UInt:
        {
            int n = value.toInt();
            result = CFNumberCreate(kCFAllocatorDefault, kCFNumberIntType, &n);
        }
        break;
    case QVariant::Double:
        {
            double n = value.toDouble();
            result = CFNumberCreate(kCFAllocatorDefault, kCFNumberDoubleType, &n);
        }
        break;
    case QVariant::LongLong:
    case QVariant::ULongLong:
        {
            qint64 n = value.toLongLong();
            result = CFNumberCreate(0, kCFNumberLongLongType, &n);
        }
        break;
    case QVariant::String:
    string_case:
    default:
        result = QCFString::toCFStringRef(QSettingsPrivate::variantToString(value));
    }
    return result;
}
コード例 #12
0
ファイル: ZipDirIterator.cpp プロジェクト: abelayer/AbZip
bool ZipDirSortItemComparator::operator()(const ZipDirSortItem &n1, const ZipDirSortItem &n2) const
{
    const ZipDirSortItem* f1 = &n1;
    const ZipDirSortItem* f2 = &n2;

    qint64 r = 0;

    if ( options.testFlag( AbZip::SortByTime ) )
    {
        QDateTime firstModified = f1->item.lastModifiedDate;
        QDateTime secondModified = f2->item.lastModifiedDate;

        // QDateTime by default will do all sorts of conversions on these to
        // find timezones, which is incredibly expensive. As we aren't
        // presenting these to the user, we don't care (at all) about the
        // local timezone, so force them to UTC to avoid that conversion.
        firstModified.setTimeSpec(Qt::UTC);
        secondModified.setTimeSpec(Qt::UTC);

        r = firstModified.msecsTo(secondModified);
    }
    else if ( options.testFlag( AbZip::SortByCompressedSize ) )
    {
        r = f2->item.compressedSize - f1->item.compressedSize;
    }
    else if ( options.testFlag( AbZip::SortByUncompressedSize ) )
    {
        r = f2->item.uncompressedSize - f1->item.uncompressedSize;
    }
    else if ( options.testFlag( AbZip::SortByType ) )
    {
        if ( options.testFlag( AbZip::CaseSensitive ) )
        {
            f1->suffix = ZipUtils::getFileSuffix( f1->item.filePath );
            f2->suffix = ZipUtils::getFileSuffix( f2->item.filePath );
        }
        else
        {
            f1->suffix = ZipUtils::getFileSuffix( f1->item.filePath ).toLower();
            f2->suffix = ZipUtils::getFileSuffix( f2->item.filePath ).toLower();
        }
        r = f1->suffix.compare(f2->suffix);
    }
    else
    {
        if ( options.testFlag( AbZip::CaseSensitive ) )
        {
            f1->filename = ZipUtils::getFileName( f1->item.filePath );
            f2->filename = ZipUtils::getFileName( f2->item.filePath );
        }
        else
        {
            f1->filename = ZipUtils::getFileName( f1->item.filePath ).toLower();
            f2->filename = ZipUtils::getFileName( f2->item.filePath ).toLower();
        }

        r = f1->filename.compare(f2->filename);
    }

    if ( options.testFlag( AbZip::SortReversed) )
        return r > 0;

    return r < 0;
}
コード例 #13
0
ファイル: message.cpp プロジェクト: BackupTheBerlios/qtlen
void Message::addSystemMessage( const QString &msg, const QDateTime &dt )
{
	message->setText( "<font color=\"#ff0000\" size=\"5\">" + tr( "System message" ) + "</font>" + msg );
	datetimeEdit->setText( dt.toString( "dd.MM.yyyy hh:mm:ss" ) );
}
コード例 #14
0
ファイル: message.cpp プロジェクト: BackupTheBerlios/qtlen
void Message::addMessage( const QString &msg, const QDateTime &dt )
{
	message->setText( msg );
	datetimeEdit->setText( dt.toString( "dd.MM.yyyy hh:mm:ss" ) );
}
コード例 #15
0
ファイル: guildshell.cpp プロジェクト: xbackupx/showeqx
void GuildShell::guildMemberList(const uint8_t* data, size_t len)
{
    // clear out any existing member data
    emit cleared();
    m_members.clear();

    m_maxNameLength = 0;

    // construct a netstream object on the data
    NetStream gml(data, len);

    // read the player name from the front of the stream
    QString player = gml.readText();

    // read the player count from the stream
    uint32_t count;
    count = gml.readUInt32();

#ifdef GUILDSHELL_DIAG
    seqDebug("Guild has %d members:", count);
#endif

    GuildMember* member;

#ifdef GUILDSHELL_DIAG
    QDateTime dt;
#endif // GUILDSHELL_DIAG

    // iterate over the data until we reach the end of it
    while (!gml.end())
    {
        // create a new guildmember initializing it from the NetStream
        member = new GuildMember(gml);

        // insert the new member into the dictionary
        m_members.insert(member->name(), member);

        // check for new longest member name
        if (member->name().length() > m_maxNameLength)
            m_maxNameLength = member->name().length();

        emit added(member);

#ifdef GUILDSHELL_DIAG
        dt.setTime_t(member->lastOn());
        seqDebug("%-64s\t%d\t%s\t%d\t%s\t'%s'\t%s:%d",
                 (const char*)member->name(),
                 member->level(),
                 (const char*)classString(member->classVal()),
                 member->guildRank(),
                 (const char*)dt.toString(),
                 (const char*)member->publicNote(),
                 (const char*)m_zoneMgr->zoneNameFromID(member->zoneId()),
                 member->zoneInstance());
#endif
    }

    emit loaded();

#ifdef GUILDSHELL_DIAG
    seqDebug("Finished processing %d guildmates. %d chars in longest name.",
             m_members.count(), m_maxNameLength);
#endif // 
}
コード例 #16
0
ファイル: lxqtclock.cpp プロジェクト: MoonLightDE/lxqt-panel
void LxQtClock::restartTimer(const QDateTime &now)
{
    if (mClockTimer->isActive())
        mClockTimer->stop();
    int updateInterval = mClockTimer->interval();
    int delay = static_cast<int>((updateInterval + 100 /* ms after time change */ - ((now.time().msec() + now.time().second() * 1000) % updateInterval)) % updateInterval);
    QTimer::singleShot(delay, this, SLOT(updateTime()));
    QTimer::singleShot(delay, mClockTimer, SLOT(start()));
}
コード例 #17
0
void CryptotargetGUI::setNumBlocks(int count)
{
    // Prevent orphan statusbar messages (e.g. hover Quit in main menu, wait until chain-sync starts -> garbelled text)
    statusBar()->clearMessage();

    // Acquire current block source
    enum BlockSource blockSource = clientModel->getBlockSource();
    switch (blockSource) {
        case BLOCK_SOURCE_NETWORK:
            progressBarLabel->setText(tr("Synchronizing with network..."));
            break;
        case BLOCK_SOURCE_DISK:
            progressBarLabel->setText(tr("Importing blocks from disk..."));
            break;
        case BLOCK_SOURCE_REINDEX:
            progressBarLabel->setText(tr("Reindexing blocks on disk..."));
            break;
        case BLOCK_SOURCE_NONE:
            // Case: not Importing, not Reindexing and no network connection
            progressBarLabel->setText(tr("No block source available..."));
            break;
    }

    QString tooltip;

    QDateTime lastBlockDate = clientModel->getLastBlockDate();
    QDateTime currentDate = QDateTime::currentDateTime();
    int secs = lastBlockDate.secsTo(currentDate);

    tooltip = tr("Processed %1 blocks of transaction history.").arg(count);

    // Set icon state: spinning if catching up, tick otherwise
    if(secs < 90*60)
    {
        tooltip = tr("Up to date") + QString(".<br>") + tooltip;
        labelBlocksIcon->setPixmap(QIcon(":/icons/synced").pixmap(STATUSBAR_ICONSIZE, STATUSBAR_ICONSIZE));

#ifdef ENABLE_WALLET
        if(walletFrame)
            walletFrame->showOutOfSyncWarning(false);
#endif

        progressBarLabel->setVisible(false);
        progressBar->setVisible(false);
    }
    else
    {
        // Represent time from last generated block in human readable text
        QString timeBehindText;
        const int HOUR_IN_SECONDS = 60*60;
        const int DAY_IN_SECONDS = 24*60*60;
        const int WEEK_IN_SECONDS = 7*24*60*60;
        const int YEAR_IN_SECONDS = 31556952; // Average length of year in Gregorian calendar
        if(secs < 2*DAY_IN_SECONDS)
        {
            timeBehindText = tr("%n hour(s)","",secs/HOUR_IN_SECONDS);
        }
        else if(secs < 2*WEEK_IN_SECONDS)
        {
            timeBehindText = tr("%n day(s)","",secs/DAY_IN_SECONDS);
        }
        else if(secs < YEAR_IN_SECONDS)
        {
            timeBehindText = tr("%n week(s)","",secs/WEEK_IN_SECONDS);
        }
        else
        {
            int years = secs / YEAR_IN_SECONDS;
            int remainder = secs % YEAR_IN_SECONDS;
            timeBehindText = tr("%1 and %2").arg(tr("%n year(s)", "", years)).arg(tr("%n week(s)","", remainder/WEEK_IN_SECONDS));
        }

        progressBarLabel->setVisible(true);
        progressBar->setFormat(tr("%1 behind").arg(timeBehindText));
        progressBar->setMaximum(1000000000);
        progressBar->setValue(clientModel->getVerificationProgress() * 1000000000.0 + 0.5);
        progressBar->setVisible(true);

        tooltip = tr("Catching up...") + QString("<br>") + tooltip;
        if(count != prevBlocks)
        {
            labelBlocksIcon->setPixmap(QIcon(QString(
                ":/movies/spinner-%1").arg(spinnerFrame, 3, 10, QChar('0')))
                .pixmap(STATUSBAR_ICONSIZE, STATUSBAR_ICONSIZE));
            spinnerFrame = (spinnerFrame + 1) % SPINNER_FRAMES;
        }
        prevBlocks = count;

#ifdef ENABLE_WALLET
        if(walletFrame)
            walletFrame->showOutOfSyncWarning(true);
#endif

        tooltip += QString("<br>");
        tooltip += tr("Last received block was generated %1 ago.").arg(timeBehindText);
        tooltip += QString("<br>");
        tooltip += tr("Transactions after this will not yet be visible.");
    }

    // Don't word-wrap this (fixed-width) tooltip
    tooltip = QString("<nobr>") + tooltip + QString("</nobr>");

    labelBlocksIcon->setToolTip(tooltip);
    progressBarLabel->setToolTip(tooltip);
    progressBar->setToolTip(tooltip);
}
コード例 #18
0
void StatisticWindow::rebuild(QDate from, QDate to)
{
    QDateTime statStart(from);
    QDateTime statEnd(to.addDays(1));

    //prepare containers
    m_Uncategorized.TotalTime = 0;
    m_Uncategorized.NormalValue = 0;
    m_Uncategorized.Name = tr("Uncategorized");
    m_Uncategorized.Color = Qt::gray;
    m_Categories.resize(m_DataManager->categoriesCount());
    for (int i = 0; i<m_Categories.size(); i++){
        m_Categories[i].TotalTime = 0;
        m_Categories[i].NormalValue = 0;
        m_Categories[i].Name = m_DataManager->categories(i)->name;
        m_Categories[i].Color = m_DataManager->categories(i)->color;
    }

    m_Applications.resize(m_DataManager->applicationsCount());
    for (int i = 0; i<m_Applications.size(); i++){
        m_Applications[i].TotalTime = 0;
        m_Applications[i].NormalValue = 0;
        m_Applications[i].Name = m_DataManager->applications(i)->name;
        m_Applications[i].Color = Qt::white;
    }

    //calculation
    int TotalTime = 0;
    for (int i = 0; i<m_Applications.size(); i++){
        const sAppInfo* app = m_DataManager->applications(i);
        for (int j = 0; j<app->periods.size(); j++){
            QDateTime start = app->periods[j].start;
            QDateTime end = app->periods[j].start.addSecs(app->periods[j].length);
            if (end>statStart && start<statEnd){
                if (start<statStart)
                    start = statStart;
                if (end>statEnd)
                    end = statEnd;
                int duration = start.secsTo(end);
                TotalTime+=duration;
                m_Applications[i].TotalTime+=duration;
                int cat = app->categories[app->periods[j].profileIndex];
                if (cat==-1)
                    m_Uncategorized.TotalTime+=duration;
                else
                    m_Categories[cat].TotalTime+=duration;
            }
            if (start>statEnd || end>statEnd)
                break;
        }
    }

    //calculate normalized values
    if (TotalTime>0){
        m_Uncategorized.NormalValue = (float)m_Uncategorized.TotalTime/TotalTime;
        for (int i = 0; i<m_Categories.size(); i++)
            m_Categories[i].NormalValue = (float)m_Categories[i].TotalTime/TotalTime;

        for (int i = 0; i<m_Applications.size(); i++)
            m_Applications[i].NormalValue = (float)m_Applications[i].TotalTime/TotalTime;
    }

    qSort( m_Categories.begin(), m_Categories.end(), lessThan );

    ui->widgetDiagram->setTotalTime(TotalTime);
    ui->widgetDiagram->update();


    //fill applications widget
    ui->treeWidgetApplications->setSortingEnabled(false);
    ui->treeWidgetApplications->clear();
    for (int i = 0; i<m_Applications.size(); i++){
        QTreeWidgetItem* item = new QTreeWidgetItem();
        item->setText(0,m_Applications[i].Name);
        item->setData(0,Qt::UserRole,i);
        item->setText(1,DurationToString(m_Applications[i].TotalTime));
        item->setText(2,fixSize(QString::number(m_Applications[i].NormalValue*100,'f',2),5)+"%");
        ui->treeWidgetApplications->addTopLevelItem(item);
    }
    ui->treeWidgetApplications->setSortingEnabled(true);
}
コード例 #19
0
ファイル: mainwindow.cpp プロジェクト: uh-adapsys/accompany
void MainWindow::on_inflatePushButton_clicked()
{


     QSqlQuery delQuery;
     delQuery.exec("delete from NormBehaviourLog");


    QString seqQuery;

    if (lv == "BATCHNORM" || lv == "BATCH")
    {
        seqQuery  = "select timestamp,sensorId,status,trainingNumber from BehaviourLog where sensorID < 61 ORDER BY trainingNumber, timestamp";
    }
    else
    {
       seqQuery  = "select timestamp,sensorId,status,trainingNumber from BehaviourLog where sensorID < 61 and timestamp between '";
       seqQuery += ui->dateFrom->dateTime().toString("yyyy-MM-dd hh:mm:ss");
       seqQuery += "' and '";
       seqQuery += ui->dateTo->dateTime().toString("yyyy-MM-dd hh:mm:ss") + "' ORDER BY timestamp";
    }
    qDebug() << seqQuery;


    query.clear();

    if (!query.exec(seqQuery))
    {
        qDebug() << seqQuery;

        QMessageBox msgBox;
        msgBox.setIcon(QMessageBox::Warning);


        msgBox.setText("Cannot select from BehaviourLog table!");
        msgBox.exec();
        return;

    }

    numRowsRead = query.numRowsAffected();
    numRowsProcessed = 0;
    numRowsInserted = 0;

    bool first = true;


    processed = false;

    currentDate = QDateTime(QDate(2000,01,01),QTime(0,0,1));

    readRow();

    while (!processed)
    {

      if (first)
      {
          first = false;
          insertNewRow(currentDate,currentSensorId,currentSensorValue,currentTrainingNumber);

       }
       else
       {

            if ((currentDate > prevDate.addSecs(1))  &&  (currentTrainingNumber == prevTrainingNumber))   // write n copies of current row 1 sec apart
            {
                int n = prevDate.time().msecsTo(currentDate.time()) / 1000;

                n--;

                QDateTime insDate = prevDate;

                for (int i=0;i<n;i++)
                {
                    insDate = insDate.addSecs(1);

                    insertNewRow(insDate,prevSensorId,prevSensorValue,prevTrainingNumber);

                }

                insertNewRow(currentDate,currentSensorId,currentSensorValue, currentTrainingNumber);


            }
            else   // same dates for two events
            {
                insertNewRow(currentDate,currentSensorId,currentSensorValue, currentTrainingNumber);
            }


         }

         readRow();

    }

    qDebug()<< "Rows read   : " << numRowsRead;
    qDebug()<< "Rows processed   : " << numRowsProcessed;
    qDebug()<< "Rows written: " << numRowsInserted;
}
コード例 #20
0
ファイル: bitcoingui.cpp プロジェクト: EclipseCrypto/eclipse
void EclipseGUI::setNumBlocks(int count, int nTotalBlocks)
{
    QWebElement blocksIcon  = documentFrame->findFirstElement("#blocksIcon");
    QWebElement syncingIcon = documentFrame->findFirstElement("#syncingIcon");
    QWebElement syncProgressBar = documentFrame->findFirstElement("#syncProgressBar");

    // don't show / hide progress bar and its label if we have no connection to the network
    if (!clientModel || (clientModel->getNumConnections() == 0 && !clientModel->isImporting()))
    {
        syncProgressBar.setAttribute("style", "display:none;");

        return;
    }

    // -- translation (tr()) makes it difficult to neatly pick block/header
    static QString sBlockType = nNodeMode == NT_FULL ? tr("block") : tr("header");
    static QString sBlockTypeMulti = nNodeMode == NT_FULL ? tr("blocks") : tr("headers");

    QString strStatusBarWarnings = clientModel->getStatusBarWarnings();
    QString tooltip;

    if (nNodeMode != NT_FULL
        && nNodeState == NS_GET_FILTERED_BLOCKS)
    {
        tooltip = tr("Synchronizing with network...");
                + "\n"
                + tr("Downloading filtered blocks...");

        int nRemainingBlocks = nTotalBlocks - pwalletMain->nLastFilteredHeight;
        float nPercentageDone = pwalletMain->nLastFilteredHeight / (nTotalBlocks * 0.01f);

        tooltip += "\n"
                 + tr("~%1 filtered block(s) remaining (%2% done).").arg(nRemainingBlocks).arg(nPercentageDone);

        count = pwalletMain->nLastFilteredHeight;
        syncProgressBar.removeAttribute("style");
    } else
    if (count < nTotalBlocks)
    {
        int nRemainingBlocks = nTotalBlocks - count;
        float nPercentageDone = count / (nTotalBlocks * 0.01f);
        syncProgressBar.removeAttribute("style");

        if (strStatusBarWarnings.isEmpty())
        {
            bridge->networkAlert("");
            tooltip = tr(clientModel->isImporting() ? "Importing blocks..." : "Synchronizing with network...");

            if (nNodeMode == NT_FULL)
            {
                tooltip += "\n"
                         + tr("~%n block(s) remaining", "", nRemainingBlocks);
            } else
            {
                char temp[128];
                snprintf(temp, sizeof(temp), "~%%n %s remaining", nRemainingBlocks == 1 ? qPrintable(sBlockType) : qPrintable(sBlockTypeMulti));

                tooltip += "\n"
                         + tr(temp, "", nRemainingBlocks);

            };
        }

        tooltip += (tooltip.isEmpty()? "" : "\n")
                 + tr(clientModel->isImporting() ? "Imported " : "Downloaded ") + tr("%1 of %2 %3 of transaction history (%4% done).").arg(count).arg(nTotalBlocks).arg(sBlockTypeMulti).arg(nPercentageDone, 0, 'f', 2);
    } else
    {
        tooltip = tr(clientModel->isImporting() ? "Imported " : "Downloaded ") + tr("%1 blocks of transaction history.").arg(count);
    }

    // Override progressBarLabel text when we have warnings to display
    if (!strStatusBarWarnings.isEmpty())
        bridge->networkAlert(strStatusBarWarnings);

    QDateTime lastBlockDate;
    if (nNodeMode == NT_FULL)
        lastBlockDate = clientModel->getLastBlockDate();
    else
        lastBlockDate = clientModel->getLastBlockThinDate();

    int secs = lastBlockDate.secsTo(QDateTime::currentDateTime());
    QString text;

    // Represent time from last generated block in human readable text
    if (secs <= 0)
    {
        // Fully up to date. Leave text empty.
    } else
    if (secs < 60)
    {
        text = tr("%n second(s) ago","",secs);
    } else
    if (secs < 60*60)
    {
        text = tr("%n minute(s) ago","",secs/60);
    } else
    if (secs < 24*60*60)
    {
        text = tr("%n hour(s) ago","",secs/(60*60));
    } else
    {
        text = tr("%n day(s) ago","",secs/(60*60*24));
    }

    // Set icon state: spinning if catching up, tick otherwise
    if (secs < 90*60 && count >= nTotalBlocks
        && nNodeState != NS_GET_FILTERED_BLOCKS)
    {
        tooltip = tr("Up to date") + "\n" + tooltip;
        blocksIcon.removeClass("none");
        syncingIcon.addClass("none");

        QWebElementCollection outOfSyncElements = documentFrame->findAllElements(".outofsync");

        foreach(QWebElement outOfSync, outOfSyncElements)
            outOfSync.setStyleProperty("display", "none");

        syncProgressBar.setAttribute("style", "display:none;");
    } else
    {
        tooltip = tr("Catching up...") + "\n" + tooltip;

        blocksIcon.addClass("none");
        syncingIcon.removeClass("none");

        QWebElementCollection outOfSyncElements = documentFrame->findAllElements(".outofsync");

        foreach(QWebElement outOfSync, outOfSyncElements)
            outOfSync.setStyleProperty("display", "inline");

        syncProgressBar.removeAttribute("style");
    }

    if (!text.isEmpty())
    {
        tooltip += "\n";
        tooltip += tr("Last received %1 was generated %2.").arg(sBlockType).arg(text);
    };

    blocksIcon     .setAttribute("data-title", tooltip);
    syncingIcon    .setAttribute("data-title", tooltip);
    syncProgressBar.setAttribute("data-title", tooltip);
    syncProgressBar.setAttribute("value", QString::number(count));
    syncProgressBar.setAttribute("max",   QString::number(nTotalBlocks));
}
コード例 #21
0
ファイル: lifxlightclient.cpp プロジェクト: GNious/libQTIoT
long LIFXLightClient::setTime(QDateTime newTime)
{
    QTIoT::IoTTimer::setTime_NoUpdate(newTime.toTime_t());
    sendTime();
    return timesec;
}
コード例 #22
0
/** \brief Fills RecordingInfo for the program that air at
 *         "dtime" on "channel".
 *  \param chanid  %Channel ID on which to search for program.
 *  \param dtime   Date and Time for which we desire the program.
 *  \param genUnknown Generate a full entry for live-tv if unknown
 *  \param clampHoursMax Clamp the maximum time to X hours from dtime.
 *  \return LoadStatus describing what happened.
 */
RecordingInfo::RecordingInfo(
    uint _chanid, const QDateTime &desiredts,
    bool genUnknown, uint maxHours, LoadStatus *status) :
    oldrecstatus(rsUnknown),
    savedrecstatus(rsUnknown),
    record(NULL)
{
    ProgramList schedList;
    ProgramList progList;

    MSqlBindings bindings;
    QString querystr = "WHERE program.chanid    = :CHANID   AND "
                       "      program.starttime < :STARTTS1 AND "
                       "      program.endtime   > :STARTTS2 ";
    bindings[":CHANID"] = QString::number(_chanid);
    QString str_startts = desiredts.toString("yyyy-MM-ddThh:mm:50");
    bindings[":STARTTS1"] = str_startts;
    bindings[":STARTTS2"] = str_startts;

    ::LoadFromScheduler(schedList);
    LoadFromProgram(progList, querystr, bindings, schedList, false);

    if (!progList.empty())
    {
        ProgramInfo *pginfo = progList[0];

        if (maxHours > 0)
        {
            if (desiredts.secsTo(
                    pginfo->GetScheduledEndTime()) > (int)maxHours * 3600)
            {
                pginfo->SetScheduledEndTime(desiredts.addSecs(maxHours * 3600));
                pginfo->SetRecordingEndTime(pginfo->GetScheduledEndTime());
            }
        }

        *this = *pginfo;
        if (status)
            *status = kFoundProgram;
        return;
    }

    recstartts = startts = desiredts;
    recendts   = endts   = desiredts;
    lastmodified         = desiredts;

    MSqlQuery query(MSqlQuery::InitCon());
    query.prepare("SELECT chanid, channum, callsign, name, "
                  "commmethod, outputfilters "
                  "FROM channel "
                  "WHERE chanid = :CHANID");
    query.bindValue(":CHANID", _chanid);

    if (!query.exec())
    {
        MythDB::DBError("Loading Program overlapping a datetime", query);
        if (status)
            *status = kNoProgram;
        return;
    }

    if (!query.next())
    {
        if (status)
            *status = kNoProgram;
        return;
    }

    chanid               = query.value(0).toUInt();
    chanstr              = query.value(1).toString();
    chansign             = query.value(2).toString();
    channame             = query.value(3).toString();
    programflags &= ~FL_CHANCOMMFREE;
    programflags |= (query.value(4).toInt() == COMM_DETECT_COMMFREE) ?
        FL_CHANCOMMFREE : 0;
    chanplaybackfilters  = query.value(5).toString();

    {
        QMutexLocker locker(&staticDataLock);
        if (unknownTitle.isEmpty())
            unknownTitle = gCoreContext->GetSetting("UnknownTitle");
        title = unknownTitle;
        title.detach();
    }

    if (!genUnknown)
    {
        if (status)
            *status = kFakedZeroMinProgram;
        return;
    }

    // Round endtime up to the next half-hour.
    endts.setTime(QTime(endts.time().hour(),
                        endts.time().minute() / kUnknownProgramLength
                        * kUnknownProgramLength));
    endts = endts.addSecs(kUnknownProgramLength * 60);

    // if under a minute, bump it up to the next half hour
    if (startts.secsTo(endts) < 60)
        endts = endts.addSecs(kUnknownProgramLength * 60);

    recendts = endts;

    // Find next program starttime
    bindings.clear();
    QDateTime nextstart = startts;
    querystr = "WHERE program.chanid    = :CHANID  AND "
               "      program.starttime > :STARTTS "
               "GROUP BY program.starttime ORDER BY program.starttime LIMIT 1 ";
    bindings[":CHANID"]  = QString::number(_chanid);
    bindings[":STARTTS"] = desiredts.toString("yyyy-MM-ddThh:mm:50");

    LoadFromProgram(progList, querystr, bindings, schedList, false);

    if (!progList.empty())
        nextstart = (*progList.begin())->GetScheduledStartTime();

    if (nextstart > startts && nextstart < recendts)
        recendts = endts = nextstart;

    if (status)
        *status = kFakedLiveTVProgram;
}
コード例 #23
0
void BitcoinGUI::setNumBlocks(int count, int nTotalBlocks)
{
    // Prevent orphan statusbar messages (e.g. hover Quit in main menu, wait until chain-sync starts -> garbelled text)
    statusBar()->clearMessage();

    // Acquire current block source
    enum BlockSource blockSource = clientModel->getBlockSource();
    switch (blockSource) {
        case BLOCK_SOURCE_NETWORK:
            progressBarLabel->setText(tr("Synchronizing with network..."));
            break;
        case BLOCK_SOURCE_DISK:
            progressBarLabel->setText(tr("Importing blocks from disk..."));
            break;
        case BLOCK_SOURCE_REINDEX:
            progressBarLabel->setText(tr("Reindexing blocks on disk..."));
            break;
        case BLOCK_SOURCE_NONE:
            // Case: not Importing, not Reindexing and no network connection
            progressBarLabel->setText(tr("No block source available..."));
            break;
    }

    QString tooltip;

    QDateTime lastBlockDate = clientModel->getLastBlockDate();
    QDateTime currentDate = QDateTime::currentDateTime();
    int secs = lastBlockDate.secsTo(currentDate);

    if(count < nTotalBlocks)
    {
        tooltip = tr("Processed %1 of %2 (estimated) blocks of transaction history.").arg(count).arg(nTotalBlocks);
    }
    else
    {
        tooltip = tr("Processed %1 blocks of transaction history.").arg(count);
    }

    // Set icon state: spinning if catching up, tick otherwise
    if(secs < 90*60 && count >= nTotalBlocks)
    {
        tooltip = tr("Up to date") + QString(".<br>") + tooltip;
        labelBlocksIcon->setPixmap(QIcon(":/icons/synced").pixmap(STATUSBAR_ICONSIZE, STATUSBAR_ICONSIZE));

        walletFrame->showOutOfSyncWarning(false);

        progressBarLabel->setVisible(false);
        progressBar->setVisible(false);
    }
    else
    {
        // Represent time from last generated block in human readable text
        QString timeBehindText;
        if(secs < 48*60*60)
        {
            timeBehindText = tr("%n hour(s)","",secs/(60*60));
        }
        else if(secs < 14*24*60*60)
        {
            timeBehindText = tr("%n day(s)","",secs/(24*60*60));
        }
        else
        {
            timeBehindText = tr("%n week(s)","",secs/(7*24*60*60));
        }

        progressBarLabel->setVisible(true);
        progressBar->setFormat(tr("%1 behind").arg(timeBehindText));
        progressBar->setMaximum(1000000000);
        progressBar->setValue(clientModel->getVerificationProgress() * 1000000000.0 + 0.5);
        progressBar->setVisible(true);

        tooltip = tr("Catching up...") + QString("<br>") + tooltip;
        labelBlocksIcon->setMovie(syncIconMovie);
        if(count != prevBlocks)
            syncIconMovie->jumpToNextFrame();
        prevBlocks = count;

        walletFrame->showOutOfSyncWarning(true);

        tooltip += QString("<br>");
        tooltip += tr("Last received block was generated %1 ago.").arg(timeBehindText);
        tooltip += QString("<br>");
        tooltip += tr("Transactions after this will not yet be visible.");
    }

    // Don't word-wrap this (fixed-width) tooltip
    tooltip = QString("<nobr>") + tooltip + QString("</nobr>");

    labelBlocksIcon->setToolTip(tooltip);
    progressBarLabel->setToolTip(tooltip);
    progressBar->setToolTip(tooltip);
}
コード例 #24
0
ファイル: rulewatch.cpp プロジェクト: fmayet/profilematic
void
RuleWatch::refreshWatch(const QDateTime &now) {
    qDebug("RuleWatch::refreshWatch(%s)", qPrintable(now.toString()));

    _timer.stop();

    QDateTime nextNearestDateTime;

    qDebug("RuleWatch::refreshWatch size of rules: %d", _rules->size());
    for (Rules::const_iterator i = _rules->constBegin(); i != _rules->constEnd(); ++i) {
        const RuleItem &item = *i;
        if (item.ruleActive) {
            QDateTime nearestFromRule = _nextDateTimeFromRule(now, item);
            if (!nearestFromRule.isNull() && (nextNearestDateTime.isNull() || nearestFromRule < nextNearestDateTime)) {
                qDebug("Setting nearest to %s, was %s",
                       qPrintable(nearestFromRule.toString()),
                       qPrintable(nextNearestDateTime.toString()));
                nextNearestDateTime = nearestFromRule;
                _targetRuleItem = &item;
            }
        }
    }

    if (!nextNearestDateTime.isNull()) {
        quint64 interval = now.msecsTo(nextNearestDateTime);
        qDebug("Now %s", qPrintable(now.toString()));
        qDebug("Scheduling a timer to %s, interval %dms", qPrintable(nextNearestDateTime.toString()), (int)interval);
        _timer.start(interval);
    } else {
        _targetRuleItem = NULL;
        qDebug("No nearest time based rule found");
    }
}
コード例 #25
0
Item DateTime::fromValue(const QDateTime &dt) const
{
    Q_ASSERT(dt.isValid());
    return fromDateTime(dt);
}
コード例 #26
0
ファイル: rulewatch.cpp プロジェクト: fmayet/profilematic
QDateTime
RuleWatch::_nextDateTimeFromRule(const QDateTime &from, const RuleItem &rule) const {
    bool isDaysUsable = rule.isDaysRuleUsable();
    bool isTimeStartUsable = rule.isTimeStartRuleUsable();
    if (!isDaysUsable && !isTimeStartUsable) {
        qDebug("QRuleWatch::time(rule %s) Day and time is not usable, returning null date time", qPrintable(rule.rule.getRuleName()));
        return QDateTime();
    }

    if (!isDaysUsable && isTimeStartUsable) {
        qDebug("QRuleWatch::time(rule %s), Day not usable, using timeStart rule %s",
               qPrintable(rule.rule.getRuleName()),
               qPrintable(rule.rule.getTimeStart().toString()));
        QDateTime next = from;
        next.setTime(rule.rule.getTimeStart());
        if (next < from) {
            next = next.addDays(1);
        }
        qDebug("QRuleWatch::time(rule %s), returning %s",
               qPrintable(rule.rule.getRuleName()),
               qPrintable(next.toString()));
        return next;
    }

    // rule.daysActive = true and days not empty always if gets this far
    const QSet<int> &selectedDays = rule.rule.getDays();
    int dayOfWeek = from.date().dayOfWeek();
    // i goes up to 7, so that next week's current day is considered also.
    for (int i = 0; i < 8; ++i) {
        int dayId = (dayOfWeek - 1 + i) % 7;
        bool considerDay = selectedDays.contains(dayId);

        qDebug("QRuleWatch::time(rule %s), considering dayId %d (%d)", qPrintable(rule.rule.getRuleName()), dayId, considerDay);

        if (considerDay) {
            QDateTime next = from;
            next = next.addDays(i);
            if (rule.isTimeStartRuleUsable()) {
                next.setTime(rule.rule.getTimeStart());
            } else {
                next.setTime(QTime(0, 0));
            }
            // Guards against a rule when:
            // - Some days, including current day, are set
            // - No time has not set
            // In other words, a rule that is based on weekdays. In these cases
            // the current day can not be considered as an edge case, but the next day.
            if (next >= from) {
                qDebug("QRuleWatch::time(rule %s), returning %s",
                       qPrintable(rule.rule.getRuleName()),
                       qPrintable(next.toString()));
                return next;
            } else {
                qDebug("QRuleWatch::time(rule %s), continuing to next day because %s < %s",
                       qPrintable(rule.rule.getRuleName()),
                       qPrintable(next.toString()),
                       qPrintable(from.toString()));
            }

        }
    }
    qDebug("QRuleWatch::time(rule %s), returning null QDateTime",
           qPrintable(rule.rule.getRuleName()));
    return QDateTime();
}
コード例 #27
0
ファイル: guiutil.cpp プロジェクト: ghostlander/Orbitcoin
QString dateTimeStr(const QDateTime &date)
{
    return date.date().toString(Qt::SystemLocaleShortDate) + QString(" ") + date.toString("hh:mm");
}
コード例 #28
0
ファイル: bitcoingui.cpp プロジェクト: mad/bitcoin
void BitcoinGUI::setNumBlocks(int count)
{
    if(!clientModel)
        return;
    int total = clientModel->getNumBlocksOfPeers();
    QString tooltip;

    if(count < total)
    {
        if (clientModel->getStatusBarWarnings() == "")
        {
            progressBarLabel->setVisible(true);
            progressBarLabel->setText(tr("Synchronizing with network..."));
            progressBar->setVisible(true);
            progressBar->setMaximum(total);
            progressBar->setValue(count);
        }
        else
        {
            progressBarLabel->setText(clientModel->getStatusBarWarnings());
            progressBarLabel->setVisible(true);
            progressBar->setVisible(false);
        }
        tooltip = tr("Downloaded %1 of %2 blocks of transaction history.").arg(count).arg(total);
    }
    else
    {
        if (clientModel->getStatusBarWarnings() == "")
            progressBarLabel->setVisible(false);
        else
        {
            progressBarLabel->setText(clientModel->getStatusBarWarnings());
            progressBarLabel->setVisible(true);
        }
        progressBar->setVisible(false);
        tooltip = tr("Downloaded %1 blocks of transaction history.").arg(count);
    }

    QDateTime now = QDateTime::currentDateTime();
    QDateTime lastBlockDate = clientModel->getLastBlockDate();
    int secs = lastBlockDate.secsTo(now);
    QString text;

    // Represent time from last generated block in human readable text
    if(secs < 60)
    {
        text = tr("%n second(s) ago","",secs);
    }
    else if(secs < 60*60)
    {
        text = tr("%n minute(s) ago","",secs/60);
    }
    else if(secs < 24*60*60)
    {
        text = tr("%n hour(s) ago","",secs/(60*60));
    }
    else
    {
        text = tr("%n day(s) ago","",secs/(60*60*24));
    }

    // Set icon state: spinning if catching up, tick otherwise
    if(secs < 30*60)
    {
        tooltip = tr("Up to date") + QString("\n") + tooltip;
        labelBlocksIcon->setPixmap(QIcon(":/icons/synced").pixmap(STATUSBAR_ICONSIZE,STATUSBAR_ICONSIZE));
    }
    else
    {
        tooltip = tr("Catching up...") + QString("\n") + tooltip;
        labelBlocksIcon->setMovie(syncIconMovie);
        syncIconMovie->start();
    }

    tooltip += QString("\n");
    tooltip += tr("Last received block was generated %1.").arg(text);

    labelBlocksIcon->setToolTip(tooltip);
    progressBarLabel->setToolTip(tooltip);
    progressBar->setToolTip(tooltip);
}
コード例 #29
0
QVariant BlockchainModel::data(const QModelIndex &_index, int _role) const {
  if(!_index.isValid()) {
    return QVariant();
  }

  IBlockChainExplorerAdapter* blockChainExplorerAdapter = m_cryptoNoteAdapter->getNodeAdapter()->getBlockChainExplorerAdapter();

  CryptoNote::TransactionDetails tx;
  quint32 blockHeight = _index.internalId() == INVALID_BLOCK_INDEX ? _index.row() : _index.internalId();
  CryptoNote::BlockDetails *block;

  if(_role >= Qt::UserRole && _role != ROLE_BLOCK_HEIGHT && _role != ROLE_ITEM_TYPE) {
    block = blockChainExplorerAdapter->getBlock(blockHeight);
    if (block == nullptr) {
     return QVariant();
    }

    if(_index.internalId() != INVALID_BLOCK_INDEX) {
      tx = block->transactions.at(_index.row());
    }
  }

  switch(_role) {
  case Qt::DisplayRole:
  case Qt::EditRole: {
    switch(_index.column()) {
    case COLUMN_BLOCK_HEIGHT:
      return _index.data(ROLE_BLOCK_HEIGHT);
    case COLUMN_BLOCK_HASH:
      return QString::fromLatin1(_index.data(ROLE_BLOCK_HASH).toByteArray().toHex());
    case COLUMN_BLOCK_TIME: {
      QDateTime time = _index.data(ROLE_BLOCK_TIME).toDateTime();
      if (time.isNull()) {
        return "-";
      }

      return QLocale(QLocale::English).toString(time, "dd MMM yyyy, hh:mm:ss");
    }

    case COLUMN_BLOCK_DIFFICULTY:
      return _index.data(ROLE_BLOCK_DIFFICULTY).value<quint64>();
    case COLUMN_BLOCK_IS_ORPHANED:
      return _index.data(ROLE_BLOCK_IS_ORPHANED).toBool() ? tr("Yes") : tr("No");
    case COLUMN_BLOCK_TRANSACTION_COUNT:
      return _index.data(ROLE_BLOCK_TRANSACTION_COUNT).value<quint64>();
    case COLUMN_BLOCK_TRANSACTIONS_SIZE:
      return _index.data(ROLE_BLOCK_TRANSACTIONS_SIZE).value<quint64>();
    case COLUMN_BLOCK_SIZE:
      return _index.data(ROLE_BLOCK_SIZE).value<quint64>();
    case COLUMN_BLOCK_VERSION:
      return QString("%1.%2").arg(_index.data(ROLE_BLOCK_MAJOR_VERSION).value<quint8>()).arg(_index.data(ROLE_BLOCK_MINOR_VERSION).value<quint8>());
    case COLUMN_BLOCK_TOTAL_COIN_COUNT:
      return m_cryptoNoteAdapter->formatUnsignedAmount(_index.data(ROLE_BLOCK_TOTAL_COIN_COUNT).value<quint64>());
    case COLUMN_BLOCK_TOTAL_TRANSACTION_COUNT:
      return _index.data(ROLE_BLOCK_TOTAL_TRANSACTION_COUNT).value<quint64>();
    case COLUMN_BLOCK_BASE_REWARD:
      return m_cryptoNoteAdapter->formatUnsignedAmount(_index.data(ROLE_BLOCK_BASE_REWARD).value<quint64>());
    case COLUMN_BLOCK_REWARD_PENALTY: {
      qreal penalty = _index.data(ROLE_BLOCK_REWARD_PENALTY).value<qreal>() * 100;
      return penalty == 0 ? tr("No") : QLocale(QLocale::English).toString(penalty, 'f').append(" %");
    }

    case COLUMN_BLOCK_REWARD:
      return m_cryptoNoteAdapter->formatUnsignedAmount(_index.data(ROLE_BLOCK_REWARD).value<quint64>());
    case COLUMN_BLOCK_FEE:
      return m_cryptoNoteAdapter->formatUnsignedAmount(_index.data(ROLE_BLOCK_FEE).value<quint64>());
    case COLUMN_TRANSACTION_HASH:
      return QString::fromLatin1(_index.data(ROLE_TRANSACTION_HASH).toByteArray().toHex());
    case COLUMN_TRANSACTION_SIZE:
      return _index.data(ROLE_TRANSACTION_SIZE).value<quint64>();
    case COLUMN_TRANSACTION_FEE:
      return m_cryptoNoteAdapter->formatUnsignedAmount(_index.data(ROLE_TRANSACTION_FEE).value<quint64>());
    case COLUMN_TRANSACTION_INPUT_AMOUNT:
      return m_cryptoNoteAdapter->formatUnsignedAmount(_index.data(ROLE_TRANSACTION_INPUT_AMOUNT).value<quint64>());
    case COLUMN_TRANSACTION_OUTPUT_AMOUNT:
      return m_cryptoNoteAdapter->formatUnsignedAmount(_index.data(ROLE_TRANSACTION_OUTPUT_AMOUNT).value<quint64>());
    case COLUMN_TRANSACTION_MIXIN:
      return _index.data(ROLE_TRANSACTION_MIXIN);
    case COLUMN_TRANSACTION_UNLOCK_TIME: {
      QDateTime time = _index.data(ROLE_TRANSACTION_UNLOCK_TIME).toDateTime();
      return QLocale(QLocale::English).toString(time, "dd MMM yyyy, hh:mm:ss");
    }
    case COLUMN_TRANSACTION_TIME: {
      QDateTime time = _index.data(ROLE_TRANSACTION_UNLOCK_TIME).toDateTime();
      return QLocale(QLocale::English).toString(time, "dd MMM yyyy, hh:mm:ss");
    }
    case COLUMN_TRANSACTION_PAYMENT_ID: {
      QByteArray payment_id = _index.data(ROLE_TRANSACTION_PAYMENT_ID).toByteArray();
      return payment_id == NULL_PAYMENT_ID ? QByteArray() : QString::fromLatin1(payment_id.toHex());
    }
    case COLUMN_TRANSACTION_IS_IN_BLOCKCHAIN:
      return _index.data(ROLE_TRANSACTION_IS_IN_BLOCKCHAIN);
    case COLUMN_TRANSACTION_BLOCK_HASH:
      return QString::fromLatin1(_index.data(ROLE_TRANSACTION_BLOCK_HASH).toByteArray().toHex());
    case COLUMN_TRANSACTION_BLOCK_HEIGHT:
      return _index.data(ROLE_TRANSACTION_BLOCK_HEIGHT).value<quint32>();
    }

    break;
  }

  case Qt::ForegroundRole:
    return _index.column() == COLUMN_BLOCK_HASH || _index.column() == COLUMN_BLOCK_HEIGHT ? QColor("#0580e8") : QVariant();
  case Qt::TextAlignmentRole:
    return headerData(_index.column(), Qt::Horizontal, _role);
  case ROLE_ITEM_TYPE:
    return _index.internalId() != INVALID_BLOCK_INDEX ? TYPE_TRANSACTION : TYPE_BLOCK;
  case ROLE_BLOCK_HEIGHT:
    return blockHeight;
  case ROLE_BLOCK_HASH:
    return QByteArray(reinterpret_cast<char*>(&block->hash), sizeof(block->hash));
  case ROLE_BLOCK_TIME:
    if (block->timestamp == 0) {
      return QDateTime();
    }

    return QDateTime::fromTime_t(block -> timestamp, Qt::UTC);
  case ROLE_BLOCK_DIFFICULTY:
    return static_cast<quint64>(block -> difficulty);
  case ROLE_BLOCK_IS_ORPHANED:
    return block->isAlternative;
  case ROLE_BLOCK_TRANSACTION_COUNT:
    return static_cast<quint64>(block -> transactions.size());
  case ROLE_BLOCK_TRANSACTIONS_SIZE:
    return static_cast<quint64>(block -> transactionsCumulativeSize);
  case ROLE_BLOCK_SIZE:
    return static_cast<quint64>(block -> blockSize);
  case ROLE_BLOCK_MAJOR_VERSION:
    return block -> majorVersion;
  case ROLE_BLOCK_MINOR_VERSION:
    return block -> minorVersion;
  case ROLE_BLOCK_TOTAL_COIN_COUNT:
    return static_cast<quint64>(block -> alreadyGeneratedCoins);
  case ROLE_BLOCK_TOTAL_TRANSACTION_COUNT:
    return static_cast<quint64>(block -> alreadyGeneratedTransactions);
  case ROLE_BLOCK_BASE_REWARD:
    return static_cast<quint64>(block -> baseReward);
  case ROLE_BLOCK_REWARD_PENALTY:
    return block -> penalty;
  case ROLE_BLOCK_REWARD:
    return static_cast<quint64>(block -> reward);
  case ROLE_BLOCK_FEE:
    return static_cast<quint64>(block -> totalFeeAmount);
  case ROLE_COLUMN:
    return headerData(_index.column(), Qt::Horizontal, ROLE_COLUMN);

  case ROLE_TRANSACTION_HASH:
    return QByteArray(reinterpret_cast<char*>(&tx.hash), sizeof(tx.hash));
  case ROLE_TRANSACTION_SIZE:
    return static_cast<quint64>(tx.size);
  case ROLE_TRANSACTION_FEE:
    return static_cast<quint64>(tx.fee);
  case ROLE_TRANSACTION_INPUT_AMOUNT:
    return static_cast<quint64>(tx.totalInputsAmount);
  case ROLE_TRANSACTION_OUTPUT_AMOUNT:
    return static_cast<quint64>(tx.totalOutputsAmount);
  case ROLE_TRANSACTION_MIXIN:
    return static_cast<quint64>(tx.mixin);
  case ROLE_TRANSACTION_UNLOCK_TIME:
    return QDateTime::fromTime_t(tx.unlockTime, Qt::UTC);
  case ROLE_TRANSACTION_TIME:
    return QDateTime::fromTime_t(tx.timestamp, Qt::UTC);
  case ROLE_TRANSACTION_PAYMENT_ID:
    return QByteArray(reinterpret_cast<char*>(&tx.paymentId), sizeof(tx.paymentId));
  case ROLE_TRANSACTION_IS_IN_BLOCKCHAIN:
    return tx.inBlockchain;
  case ROLE_TRANSACTION_BLOCK_HASH:
    return QByteArray(reinterpret_cast<char*>(&tx.blockHash), sizeof(tx.blockHash));
  case ROLE_TRANSACTION_BLOCK_HEIGHT:
    return static_cast<quint32>(tx.blockIndex);
  default:
    break;
  }

  return QVariant();
}
コード例 #30
0
ファイル: DialogTwaLine.cpp プロジェクト: nohal/qtVlm
void DialogTwaLine::traceIt()
{
    line->deleteAll();
    QListIterator<POI*> i (list);
    while(i.hasNext())
    {
        POI * poi=i.next();
        list.removeOne(poi);
        if(poi->isPartOfTwa())
        {
            parent->slot_delPOI_list(poi);
            delete poi;
        }
    }
    this->myBoat=parent->getSelectedBoat();
    if(myBoat==NULL) return;
    if(!dataManager->isOk()) return;
    if(!myBoat->getPolarData()) return;
    time_t eta;
    if(this->startGrib->isChecked() || myBoat->get_boatType()!=BOAT_VLM)
        eta=dataManager->get_currentDate();
    else
        eta=((boatVLM*)myBoat)->getPrevVac()+myBoat->getVacLen();
    nbVac[0]=this->spinBox->value();
    nbVac[1]=this->spinBox_2->value();
    nbVac[2]=this->spinBox_3->value();
    nbVac[3]=this->spinBox_4->value();
    nbVac[4]=this->spinBox_5->value();
    twa[0]=this->doubleSpinBox->value();
    twa[1]=this->doubleSpinBox_2->value();
    twa[2]=this->doubleSpinBox_3->value();
    twa[3]=this->doubleSpinBox_4->value();
    twa[4]=this->doubleSpinBox_5->value();
    mode[0]=this->TWA1->isChecked();
    mode[1]=this->TWA2->isChecked();
    mode[2]=this->TWA3->isChecked();
    mode[3]=this->TWA4->isChecked();
    mode[4]=this->TWA5->isChecked();
    int vacLen=myBoat->getVacLen();
    vlmPoint current(start.x(),start.y());
    line->addVlmPoint(current);
    double wind_speed,wind_angle,cap;
    double lon=0,lat=0;
    time_t maxDate=dataManager->get_maxDate();
    bool crossing=false;
    //int i1,j1,i2,j2;
    GshhsReader *map=parent->get_gshhsReader();
    int mapQuality=map?map->getQuality():4;
    for (int page=0;page<5;page++)
    {
        if (nbVac[page]==0) continue;
        for(int i=1;i<=nbVac[page];i++)
        {
            double current_speed=-1;
            double current_angle=0;
            if(!dataManager->getInterpolatedWind(current.lon, current.lat,
                eta,&wind_speed,&wind_angle,INTERPOLATION_DEFAULT) || eta>maxDate)
                break;
            wind_angle=radToDeg(wind_angle);
            if(dataManager->getInterpolatedCurrent(current.lon, current.lat,
                eta,&current_speed,&current_angle,INTERPOLATION_DEFAULT))
            {
                current_angle=radToDeg(current_angle);
                QPointF p=Util::calculateSumVect(wind_angle,wind_speed,current_angle,current_speed);
                //qWarning()<<"cs="<<current_speed<<"cd="<<current_angle<<"tws="<<wind_speed<<"twd="<<wind_angle<<"Ltws="<<p.x()<<"Ltwd="<<p.y();
                wind_speed=p.x();
                wind_angle=p.y();
            }
            double TWA;
            if(mode[page])
            {
                cap=A360(wind_angle+twa[page]);
                TWA=twa[page];
            }
            else
            {
                cap=twa[page];
                TWA=A360(cap-wind_angle);
                if(qAbs(TWA)>180)
                {
                    if(TWA<0)
                        TWA=360+TWA;
                    else
                        TWA=TWA-360;
                }
            }
            double newSpeed=myBoat->getPolarData()->getSpeed(wind_speed,TWA);
            if(current_speed>0)
            {
                QPointF p=Util::calculateSumVect(cap,newSpeed,A360(current_angle+180.0),current_speed);
                newSpeed=p.x(); //in this case newSpeed is SOG
                cap=p.y(); //in this case cap is COG
            }
            double distanceParcourue=newSpeed*vacLen/3600.00;
            Util::getCoordFromDistanceAngle(current.lat, current.lon, distanceParcourue, cap,&lat,&lon);
            if(!crossing && map && mapQuality>=3)
            {
                double I1,J1,I2,J2;
                parent->getProj()->map2screenDouble(current.lon,current.lat,&I1,&J1);
                parent->getProj()->map2screenDouble(lon,lat,&I2,&J2);
                crossing=map->crossing(QLineF(I1,J1,I2,J2),QLineF(current.lon,current.lat,lon,lat));
            }
            current.lon=lon;
            current.lat=lat;
            line->addVlmPoint(current);
            eta=eta+vacLen;
        }
        if(crossing)
            pen.setColor(Qt::red);
        else
            pen.setColor(color);
        line->setLinePen(pen);
        QDateTime tm;
        tm.setTimeSpec(Qt::UTC);
        if(this->startVac->isChecked())
            tm.setTime_t(eta-vacLen);
        else
            tm.setTime_t(eta);
        //QString name;
        //name.sprintf("Twa %.1f",twa[page]);
        POI * arrival=parent->slot_addPOI(tr("ETA: ")+tm.toString("dd MMM-hh:mm"),0,lat,lon,-1,0,false,myBoat);
        arrival->setPartOfTwa(true);
        list.append(arrival);
    }
    line->slot_showMe();
    QApplication::processEvents();
}