Ejemplo n.º 1
0
void YggdrasilTask::processReply()
{
	setStatus(getStateMessage(STATE_PROCESSING_RESPONSE));

	if (m_netReply->error() == QNetworkReply::SslHandshakeFailedError)
	{
		emitFailed(
			tr("<b>SSL Handshake failed.</b><br/>There might be a few causes for it:<br/>"
			   "<ul>"
			   "<li>You use Windows XP and need to <a "
			   "href=\"http://www.microsoft.com/en-us/download/details.aspx?id=38918\">update "
			   "your root certificates</a></li>"
			   "<li>Some device on your network is interfering with SSL traffic. In that case, "
			   "you have bigger worries than Minecraft not starting.</li>"
			   "<li>Possibly something else. Check the MultiMC log file for details</li>"
			   "</ul>"));
		return;
	}

	// any network errors lead to offline mode right now
	if (m_netReply->error() >= QNetworkReply::ConnectionRefusedError &&
		m_netReply->error() <= QNetworkReply::UnknownNetworkError)
	{
		// WARNING/FIXME: the value here is used in MojangAccount to detect the cancel/timeout
		emitFailed("Yggdrasil task cancelled.");
		QLOG_ERROR() << "Yggdrasil task cancelled because of: " << m_netReply->error() << " : "
					 << m_netReply->errorString();
		return;
	}

	// Try to parse the response regardless of the response code.
	// Sometimes the auth server will give more information and an error code.
	QJsonParseError jsonError;
	QByteArray replyData = m_netReply->readAll();
	QJsonDocument doc = QJsonDocument::fromJson(replyData, &jsonError);
	// Check the response code.
	int responseCode = m_netReply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();

	if (responseCode == 200)
	{
		// If the response code was 200, then there shouldn't be an error. Make sure
		// anyways.
		// Also, sometimes an empty reply indicates success. If there was no data received,
		// pass an empty json object to the processResponse function.
		if (jsonError.error == QJsonParseError::NoError || replyData.size() == 0)
		{
			if (processResponse(replyData.size() > 0 ? doc.object() : QJsonObject()))
			{
				emitSucceeded();
				return;
			}

			// errors happened anyway?
			emitFailed(m_error ? m_error->m_errorMessageVerbose
							   : tr("An unknown error occurred when processing the response "
									"from the authentication server."));
		}
		else
		{
			emitFailed(tr("Failed to parse Yggdrasil JSON response: %1 at offset %2.")
						   .arg(jsonError.errorString())
						   .arg(jsonError.offset));
		}
		return;
	}

	// If the response code was not 200, then Yggdrasil may have given us information
	// about the error.
	// If we can parse the response, then get information from it. Otherwise just say
	// there was an unknown error.
	if (jsonError.error == QJsonParseError::NoError)
	{
		// We were able to parse the server's response. Woo!
		// Call processError. If a subclass has overridden it then they'll handle their
		// stuff there.
		QLOG_DEBUG() << "The request failed, but the server gave us an error message. "
						"Processing error.";
		emitFailed(processError(doc.object()));
	}
	else
	{
		// The server didn't say anything regarding the error. Give the user an unknown
		// error.
		QLOG_DEBUG() << "The request failed and the server gave no error message. "
						"Unknown error.";
		emitFailed(tr("An unknown error occurred when trying to communicate with the "
					  "authentication server: %1").arg(m_netReply->errorString()));
	}
}
Ejemplo n.º 2
0
void NWebView::printNodeName(QString s) {
    QLOG_DEBUG() << s;
}
Ejemplo n.º 3
0
//***********************************************************
//* Process a <note> tag
//***********************************************************
void ImportData::processNoteNode() {
    QLOG_DEBUG() << "Processing Note Node";
    Note note;
    QUuid uuid;
    QString newGuid = uuid.createUuid().toString().replace("{", "").replace("}", "");
    note.guid = newGuid;
    NoteMetaData meta;
    bool noteIsDirty = false;

    bool atEnd = false;
    while(!atEnd) {
        QString name = reader->name().toString().toLower();
        if (name == "guid" && !reader->isEndElement() && backup) {
            note.guid = textValue();
            noteList.append(note.guid);
        }
        if (name == "updatesequencenumber" && !reader->isEndElement()) {
            note.updateSequenceNum = textValue().toLong();
        }
        if (name == "title" && !reader->isEndElement()) {
            note.title = textValue();
        }
        if (name == "created" && !reader->isEndElement()) {
            note.created = longLongValue();
        }
        if (name == "updated" && !reader->isEndElement()) {
            note.updated = longLongValue();
        }
        if (name == "deleted" && !reader->isEndElement()) {
            note.deleted = longLongValue();
        }
        if (name == "active" && !reader->isEndElement()) {
            note.active = booleanValue();
        }
        if (name == "notebookguid" && !reader->isEndElement()) {
            note.notebookGuid = textValue();
        }
        if (name == "dirty" && !reader->isEndElement()) {
            noteIsDirty = booleanValue();
        }
        if (name == "content" && !reader->isEndElement()) {
            note.content = textValue();
        }
        if (name == "titlecolor" && !reader->isEndElement()) {
            meta.setColor(intValue());
        }
        if (name == "notetags" && (createTags || backup) && !reader->isEndElement()) {
            QStringList names, guids;
            processNoteTagList(guids, names);
            QList<QString> tagGuids;
            QList<QString> tagNames;
            for (qint32 i=0; i<guids.size(); i++) {
                tagGuids.append(guids[i]);
                tagNames.append(names[i]);
            }
            note.tagNames = tagNames;
            note.tagGuids = tagGuids;
        }
        if (name == "noteattributes" && !reader->isEndElement()) {
            processNoteAttributes(note.attributes);
        }
        if (name == "noteresource" && !reader->isEndElement()) {
            Resource newRes;
            processResource(newRes);
            newRes.noteGuid = note.guid;
            if (!backup)
                newRes.updateSequenceNum = 0;
            QList<Resource> resources;
            if (note.resources.isSet())
                resources = note.resources;
            resources.append(newRes);
            note.resources = resources;
        }
        reader->readNext();
        QString endName = reader->name().toString().toLower();
        if (endName == "note" && reader->isEndElement())
            atEnd = true;
    }

    // Loop through the resources & make sure they all have the
    // proper guid for this note
    QList<Resource> resources;
    if (note.resources.isSet())
        resources = note.resources;
    for (int i=0; i<resources.size(); i++) {
        resources[i].noteGuid = note.guid;
    }
    note.resources = resources;
    NoteTable noteTable(global.db);
    if (backup)
        noteTable.add(0,note, noteIsDirty);
    else {
        note.updateSequenceNum = 0;
        if (notebookGuid != NULL)
            note.notebookGuid = notebookGuid;
        noteTable.add(0,note, true);
        if (metaData.contains(note.guid)) {
            QLOG_ERROR() << "ERROR IN IMPORTING DATA:  Metadata not yet supported";
        }
    }
    return;
}
Ejemplo n.º 4
0
void SyncRunner::evernoteSync() {
    QLOG_TRACE() << "Sync thread:" << QThread::currentThreadId();
    if (!global.connected)
        return;

    User user;
    UserTable userTable(db);
    if (!comm->getUserInfo(user)) {
        this->communicationErrorHandler();
        error =true;
        return;
    }
    userTable.updateUser(user);

    SyncState syncState;
    if (!comm->getSyncState("", syncState)) {
        this->communicationErrorHandler();
        error = true;
        return;
    }

    fullSync = false;

    qlonglong lastSyncDate = userTable.getLastSyncDate();
    updateSequenceNumber = userTable.getLastSyncNumber();

    if ((syncState.fullSyncBefore/1000) > lastSyncDate) {
        QLOG_DEBUG() <<  "Full sequence date has expired";
        lastSyncDate = 0;
        fullSync = true;
    }

    if (updateSequenceNumber == 0)
        fullSync = true;

    emit setMessage(tr("Beginning Sync"), defaultMsgTimeout);
    // If there are remote changes
    QLOG_DEBUG() <<  "--->>>  Current Chunk High Sequence Number: " << syncState.updateCount;
    QLOG_DEBUG() <<  "--->>>  Last User High Sequence Number: " <<  updateSequenceNumber;

    if (syncState.updateCount > updateSequenceNumber) {
        QLOG_DEBUG() <<  "Remote changes found";
        QLOG_DEBUG() << "Downloading changes";
        emit setMessage(tr("Downloading changes"), defaultMsgTimeout);
        bool rc = syncRemoteToLocal(syncState.updateCount);
        if (!rc)
            error = true;
    }

    if (!comm->getUserInfo(user)) {
        this->communicationErrorHandler();
        error = true;
        return;
    }
    userTable.updateUser(user);

    if (!global.disableUploads && !error) {
        qint32 searchUsn = uploadSavedSearches();
        if (searchUsn > updateSequenceNumber)
            updateSequenceNumber = searchUsn;
        qint32 tagUsn = uploadTags();
        if (tagUsn > updateSequenceNumber)
            updateSequenceNumber = tagUsn;
        qint32 notebookUsn = uploadNotebooks();
        if (notebookUsn > updateSequenceNumber)
            updateSequenceNumber = notebookUsn;
        qint32 personalNotesUsn = uploadPersonalNotes();
        if (personalNotesUsn > updateSequenceNumber)
            updateSequenceNumber = personalNotesUsn;
    }

    // Synchronize linked notebooks
    if (!error && !syncRemoteLinkedNotebooksActual())
           error = true;

    if (error || !comm->getSyncState("", syncState)) {
        error =true;
        this->communicationErrorHandler();
        return;
    }
    userTable.updateSyncState(syncState);

    // Cleanup any missing parent tags
    QList<qint32> lids;
    TagTable tagTable(db);
    tagTable.findMissingParents(lids);
    for (int i=0; i<lids.size(); i++) {
        if (!finalSync)
            emit(tagExpunged(lids[i]));
    }
    tagTable.cleanupMissingParents();

    if (!error)
        emit setMessage(tr("Sync Complete Successfully"), defaultMsgTimeout);
    QLOG_TRACE() << "Leaving SyncRunner::evernoteSync()";
}
Ejemplo n.º 5
0
void UASActionsWidget::loadApmSettings()
{
    // Load defaults from settings
    QSettings settings;
    settings.sync();

    if(m_uas->isMultirotor()){
       if (settings.contains("APM_MULTI_SHORTCUT_OPT1")){
           QLOG_DEBUG() << "Mutli: opt1Mode: " << settings.value("APM_MULTI_SHORTCUT_OPT1").toString();
           QLOG_DEBUG() << "Mutli: opt2Mode: " << settings.value("APM_MULTI_SHORTCUT_OPT2").toString();
           QLOG_DEBUG() << "Mutli: opt3Mode: " << settings.value("APM_MULTI_SHORTCUT_OPT3").toString();
           QLOG_DEBUG() << "Mutli: opt4Mode: " << settings.value("APM_MULTI_SHORTCUT_OPT4").toString();
           ui.opt1ModeButton->setText(settings.value("APM_MULTI_SHORTCUT_OPT1").toString());
           ui.opt2ModeButton->setText(settings.value("APM_MULTI_SHORTCUT_OPT2").toString());
           ui.opt3ModeButton->setText(settings.value("APM_MULTI_SHORTCUT_OPT3").toString());
           ui.opt4ModeButton->setText(settings.value("APM_MULTI_SHORTCUT_OPT4").toString());
        }

    } else if (m_uas->isFixedWing()){
       if (settings.contains("APM_FIXED_SHORTCUT_OPT1")){
           QLOG_DEBUG() << "Fixed: opt1Mode: " << settings.value("APM_FIXED_SHORTCUT_OPT1").toString();
           QLOG_DEBUG() << "Fixed: opt2Mode: " << settings.value("APM_FIXED_SHORTCUT_OPT2").toString();
           QLOG_DEBUG() << "Fixed: opt3Mode: " << settings.value("APM_FIXED_SHORTCUT_OPT3").toString();
           QLOG_DEBUG() << "Fixed: opt4Mode: " << settings.value("APM_FIXED_SHORTCUT_OPT4").toString();
           ui.opt1ModeButton->setText(settings.value("APM_FIXED_SHORTCUT_OPT1").toString());
           ui.opt2ModeButton->setText(settings.value("APM_FIXED_SHORTCUT_OPT2").toString());
           ui.opt3ModeButton->setText(settings.value("APM_FIXED_SHORTCUT_OPT3").toString());
           ui.opt4ModeButton->setText(settings.value("APM_FIXED_SHORTCUT_OPT4").toString());
       }

     } else if(m_uas->isMultirotor()){
       if (settings.contains("APM_GROUND_SHORTCUT_OPT1")){
           QLOG_DEBUG() << "Ground: opt1Mode: " << settings.value("APM_GROUND_SHORTCUT_OPT1").toString();
           QLOG_DEBUG() << "Ground: opt2Mode: " << settings.value("APM_GROUND_SHORTCUT_OPT2").toString();
           QLOG_DEBUG() << "Ground: opt3Mode: " << settings.value("APM_GROUND_SHORTCUT_OPT3").toString();
           QLOG_DEBUG() << "Ground: opt4Mode: " << settings.value("APM_GROUND_SHORTCUT_OPT4").toString();

           ui.opt1ModeButton->setText(settings.value("APM_GROUND_SHORTCUT_OPT1").toString());
           ui.opt2ModeButton->setText(settings.value("APM_GROUND_SHORTCUT_OPT2").toString());
           ui.opt3ModeButton->setText(settings.value("APM_GROUND_SHORTCUT_OPT3").toString());
           ui.opt4ModeButton->setText(settings.value("APM_GROUND_SHORTCUT_OPT4").toString());
       }
     }
}
Ejemplo n.º 6
0
void TagEditorNewTag::mouseCompleterSelection(QString value) {
    QLOG_DEBUG() << "Mouse selection completer for tag: " << value;
    QKeyEvent *event = new QKeyEvent (QEvent::KeyPress, Qt::Key_Tab, Qt::NoModifier);
    QCoreApplication::postEvent (this, event);
}
Ejemplo n.º 7
0
bool SyncRunner::syncRemoteToLocal(qint32 updateCount) {
    QLOG_TRACE() << "Entering SyncRunner::SyncRemoteToLocal()";

    // The sync is run in several parts.
    // Part #1: Get all remote tags, notebooks, & saved searches for
    //          a user's account.  We do this first because we want
    //          the tag & notebook naems for filling out the note table.
    //          It is just easier this way.
    // Part #2: Get all changed notes & resources.  If it is a full sync
    //          then we get the resources & notes together as one entity
    //          (the resource chunk won't have anything).  We also do not
    //          get deleted notes on a full sync.  If it is a partial sync
    //          then we get resources & notes separately (i.e. the notes chunk
    //          may reference a resource guid, but it won't have the detail and
    //          the chunk resources will have valid data.  We get deleted notes
    //          on a partial sync.
    // Part #3: Upload anything local to the user's account.
    // Part #4: Do linked notebook stuff.  Basically the same as
    //          this except we do it across multiple accounts.

    int chunkSize = 5000;
    bool more = true;

    bool rc;
    int startingSequenceNumber = updateSequenceNumber;

    while(more && keepRunning)  {
        SyncChunk chunk;
        rc = comm->getSyncChunk(chunk, updateSequenceNumber, chunkSize,
                                SYNC_CHUNK_LINKED_NOTEBOOKS | SYNC_CHUNK_NOTEBOOKS |
                                SYNC_CHUNK_TAGS | SYNC_CHUNK_SEARCHES,
                                fullSync);
        if (!rc) {
            QLOG_ERROR() << "Error retrieving chunk";
            error = true;
            this->communicationErrorHandler();
            return false;
        }
        QLOG_DEBUG() << "-(Pass 1)->>>>  Old USN:" << updateSequenceNumber << " New USN:" << chunk.chunkHighUSN;
        int pct = (updateSequenceNumber-startingSequenceNumber)*100/(updateCount-startingSequenceNumber);
        emit setMessage(tr("Download ") +QString::number(pct) + tr("% complete for notebooks, tags, & searches."), defaultMsgTimeout);

        processSyncChunk(chunk);

        updateSequenceNumber = chunk.chunkHighUSN;
        if (!chunk.chunkHighUSN.isSet() || chunk.chunkHighUSN >= chunk.updateCount)
            more = false;
    }

    emit setMessage(tr("Download complete for notebooks, tags, & searches.  Downloading notes."), defaultMsgTimeout);

    comm->loadTagGuidMap();
    more = true;
    chunkSize = 50;
    updateSequenceNumber = startingSequenceNumber;
    UserTable userTable(db);


    while(more && keepRunning)  {
        SyncChunk chunk;
        rc = comm->getSyncChunk(chunk, updateSequenceNumber, chunkSize, SYNC_CHUNK_NOTES | SYNC_CHUNK_RESOURCES, fullSync);
        if (!rc) {
            QLOG_ERROR() << "Error retrieving chunk";
            error = true;
            this->communicationErrorHandler();
            return false;
        }
        QLOG_DEBUG() << "-(Pass 2) ->>>>  Old USN:" << updateSequenceNumber << " New USN:" << chunk.chunkHighUSN;
        int pct = (updateSequenceNumber-startingSequenceNumber)*100/(updateCount-startingSequenceNumber);
        emit setMessage(tr("Download ") +QString::number(pct) + tr("% complete."), defaultMsgTimeout);
        processSyncChunk(chunk);

        userTable.updateLastSyncNumber(chunk.chunkHighUSN);
        userTable.updateLastSyncDate(chunk.currentTime);

        updateSequenceNumber = chunk.chunkHighUSN;
        if (!chunk.chunkHighUSN.isSet() || chunk.chunkHighUSN >= chunk.updateCount) {
            more = false;
            userTable.updateLastSyncNumber(updateCount);
        }
    }

    emit setMessage(tr("Download complete."), defaultMsgTimeout);
    return true;
}
Ejemplo n.º 8
0
UdpEchoClient::~UdpEchoClient()
{
    QLOG_DEBUG();
}
Ejemplo n.º 9
0
/* This only parses uniform variables between the following lines:

// BEGIN UNIFORM
uniform float x;    // default
uniform vec4 color; // red green blue alpha
// END UNIFORM

uniform can be replaced by 'in' and if no default is given the floats default
to 0.0 and the color to white.  Comments between the BEGIN and END lines are
ignored.
*/
QVariantMap ShaderLibrary::parseUniformVariables(QString const& shaderPath)
{
   QVariantMap map;

   QFile file(shaderPath);
   if (file.open(QIODevice::ReadOnly | QIODevice::Text)) {
      Parser::TextStream textStream(&file);

      int n;
      bool tf;
      double value;
      QString line;
      QString name;
      QColor  color;
      QStringList tokens;
      textStream.seek("BEGIN UNIFORM");

      while (!textStream.atEnd()) {
         line = textStream.nextLine();      
         if (line.contains("END UNIFORM")) break;

         if (!line.startsWith("//")) {
            line = line.replace(";"," ");
            line = line.replace(","," ");
            line = line.replace("//"," ");

            tokens = Parser::TextStream::tokenize(line);
            n = tokens.size();

            if (n >= 3 && (tokens[0] == "uniform" || tokens[0] == "in"))  {
               name = tokens[2];

               if (tokens[1] == "float") {
                  value = (n >= 4) ? tokens[3].toDouble() : 0.0;
                  map.insert(name, value);
               }else if (tokens[1] == "bool") {
                  tf = (n >= 4) ? tokens[3].toInt() : false;
                  map.insert(name, tf);
               }else if (tokens[1] == "vec4") {
                  color = Qt::white;
                  if (n >= 7) {
                     color.setRgbF(tokens[3].toDouble(), tokens[4].toDouble(), 
                        tokens[5].toDouble(), tokens[6].toDouble());
                  }
                  map.insert(name, color);
               }else {
                  QLOG_DEBUG() << "Unknown uniform variable in shader" << tokens[1];
               }
            }
         }
      }

      file.close();
   }   

   return map;

/*
   qDebug() << "Parsed the following uniform variables:";
   for (QVariantMap::iterator iter = map.begin(); iter != map.end(); ++iter) {
        qDebug() << iter.key() << iter.value();
   }
*/
}
Ejemplo n.º 10
0
// Add a new note to the database
qint32 NoteTable::add(qint32 l, Note &t, bool isDirty) {
    QLOG_DEBUG() << "Adding note: " << QString::fromStdString(t.title);
    ResourceTable resTable;
    ConfigStore cs;
    QSqlQuery query;
    qint32 position;
    TagScanner scanner;
    qint32 lid = l;
    qint32 notebookLid;

    query.prepare("Insert into DataStore (lid, key, data) values (:lid, :key, :data)");
    if (lid <= 0)
        lid = cs.incrementLidCounter();

    query.bindValue(":lid", lid);
    query.bindValue(":key", NOTE_GUID);
    query.bindValue(":data", QString::fromStdString(t.guid));
    query.exec();

    query.bindValue(":lid", lid);
    query.bindValue(":key", NOTE_INDEX_NEEDED);
    query.bindValue(":data", true);
    query.exec();

    if (t.__isset.title) {
        query.bindValue(":lid", lid);
        query.bindValue(":key", NOTE_TITLE);
        query.bindValue(":data", QString::fromStdString(t.title.c_str()));
        query.exec();
    }

    if (t.__isset.content) {
        query.bindValue(":lid", lid);
        query.bindValue(":key", NOTE_CONTENT);
        QByteArray b;
        b.append(QString::fromStdString(t.content).toAscii());
        query.bindValue(":data", b);
        query.exec();
    }

    if (t.__isset.contentHash) {
        query.bindValue(":lid", lid);
        query.bindValue(":key", NOTE_CONTENT_HASH);
        query.bindValue(":data", QString::fromStdString(t.contentHash));
        query.exec();
    }

    if (t.__isset.contentLength) {
        query.bindValue(":lid", lid);
        query.bindValue(":key", NOTE_CONTENT_LENGTH);
        query.bindValue(":data", t.contentLength);
        query.exec();
    }

    query.bindValue(":lid", lid);
    query.bindValue(":key", NOTE_UPDATE_SEQUENCE_NUMBER);
    query.bindValue(":data", t.updateSequenceNum);
    query.exec();

    query.bindValue(":lid", lid);
    query.bindValue(":key", NOTE_ISDIRTY);
    query.bindValue(":data", isDirty);
    query.exec();

    if (t.__isset.created) {
        query.bindValue(":lid", lid);
        query.bindValue(":key", NOTE_CREATED_DATE);
        query.bindValue(":data", QVariant::fromValue(t.created));
        query.exec();
    }

    if (t.__isset.updated) {
        query.bindValue(":lid", lid);
        query.bindValue(":key", NOTE_UPDATED_DATE);
        query.bindValue(":data", QVariant::fromValue(t.updated));
        query.exec();
    }

    if (t.__isset.deleted) {
        query.bindValue(":lid", lid);
        query.bindValue(":key", NOTE_DELETED_DATE);
        query.bindValue(":data", QVariant::fromValue(t.deleted));
        query.exec();
    }

    if (t.__isset.active) {
        query.bindValue(":lid", lid);
        query.bindValue(":key", NOTE_ACTIVE);
        query.bindValue(":data", QVariant::fromValue(t.active));
        query.exec();
    }

    if (t.__isset.notebookGuid) {
        query.bindValue(":lid", lid);
        query.bindValue(":key", NOTE_NOTEBOOK_LID);
        NotebookTable notebookTable;
        notebookLid = notebookTable.getLid(QString::fromStdString(t.notebookGuid));

        // If not found, we insert one to avoid problems.  We'll probably get the real data later
        if (notebookLid == 0) {
            notebookLid = cs.incrementLidCounter();
            Notebook notebook;
            notebook.guid = t.notebookGuid;
            notebook.name = "";
            notebook.__isset.guid = true;
            notebook.__isset.name = true;
            notebookTable.add(notebookLid, notebook, false, false);
        }
        query.bindValue(":data", notebookLid);
        query.exec();
    }

    for (unsigned int i=0; t.__isset.tagGuids && i<t.tagGuids.size(); i++) {
        TagTable tagTable;
        qint32 tagLid = tagTable.getLid(t.tagGuids.at(i));
        if (tagLid == 0) {
            // create a dummy tag to avoid later problems
            Tag newTag;
            newTag.guid = t.tagGuids.at(i);
            newTag.name = "";
            newTag.__isset.guid = true;
            newTag.__isset.name = true;
            tagLid = cs.incrementLidCounter();
            tagTable.add(tagLid, newTag, false, 0);
        }

        query.bindValue(":lid", lid);
        query.bindValue(":key", NOTE_TAG_LID);
        query.bindValue(":data", tagLid);
        query.exec();
    }

    for (unsigned int i=0; t.__isset.resources && i<t.resources.size(); i++) {
        qint32 resLid;
        Resource *r;
        r = &t.resources[i];
        resLid = resTable.getLid(t.guid,t.resources[i].guid);
        if (resLid == 0)
            resLid = cs.incrementLidCounter();
        resTable.add(resLid, t.resources[i], isDirty);

        if (r->__isset.mime) {
            QString mime = QString::fromStdString(r->mime);
            if (!mime.startsWith("image/") && mime != "vnd.evernote.ink") {
                query.bindValue(":lid", lid);
                query.bindValue(":key", NOTE_HAS_ATTACHMENT);
                query.bindValue(":data", true);
                query.exec();
            }
        }
    }

    if (t.__isset.attributes) {
        if (t.attributes.__isset.subjectDate) {
            query.bindValue(":lid", lid);
            query.bindValue(":key", NOTE_ATTRIBUTE_SUBJECT_DATE);
            query.bindValue(":data", QVariant::fromValue(t.attributes.subjectDate));
            query.exec();
        }
        if (t.attributes.__isset.latitude) {
            query.bindValue(":lid", lid);
            query.bindValue(":key", NOTE_ATTRIBUTE_LATITUDE);
            query.bindValue(":data", QVariant::fromValue(t.attributes.latitude));
            query.exec();
        }
        if (t.attributes.__isset.latitude) {
            query.bindValue(":lid", lid);
            query.bindValue(":key", NOTE_ATTRIBUTE_LONGITUDE);
            query.bindValue(":data", QVariant::fromValue(t.attributes.longitude));
            query.exec();
        }
        if (t.attributes.__isset.altitude) {
            query.bindValue(":lid", lid);
            query.bindValue(":key", NOTE_ATTRIBUTE_ALTITUDE);
            query.bindValue(":data", QVariant::fromValue(t.attributes.altitude));
            query.exec();
        }
        if (t.attributes.__isset.author) {
            query.bindValue(":lid", lid);
            query.bindValue(":key", NOTE_ATTRIBUTE_AUTHOR);
            query.bindValue(":data", QString::fromStdString(t.attributes.author));
            query.exec();
        }
        if (t.attributes.__isset.source) {
            query.bindValue(":lid", lid);
            query.bindValue(":key", NOTE_ATTRIBUTE_SOURCE);
            query.bindValue(":data", QString::fromStdString(t.attributes.source));
            query.exec();
        }
        if (t.attributes.__isset.sourceURL) {
            query.bindValue(":lid", lid);
            query.bindValue(":key", NOTE_ATTRIBUTE_SOURCE_URL);
            query.bindValue(":data", QString::fromStdString(t.attributes.sourceURL));
            query.exec();
        }
        if (t.attributes.__isset.sourceApplication) {
            query.bindValue(":lid", lid);
            query.bindValue(":key", NOTE_ATTRIBUTE_SOURCE_APPLICATION);
            query.bindValue(":data", QString::fromStdString(t.attributes.sourceApplication));
            query.exec();
        }
        if (t.attributes.__isset.shareDate) {
            query.bindValue(":lid", lid);
            query.bindValue(":key", NOTE_ATTRIBUTE_SHARE_DATE);
            query.bindValue(":data",QVariant::fromValue(t.attributes.shareDate));
            query.exec();
        }
        if (t.attributes.__isset.placeName) {
            query.bindValue(":lid", lid);
            query.bindValue(":key", NOTE_ATTRIBUTE_PLACE_NAME);
            query.bindValue(":data", QString::fromStdString(t.attributes.placeName));
            query.exec();
        }
        if (t.attributes.__isset.contentClass) {
            query.bindValue(":lid", lid);
            query.bindValue(":key", NOTE_ATTRIBUTE_CONTENT_CLASS);
            query.bindValue(":data", QString::fromStdString(t.attributes.contentClass));
            query.exec();
        }
    }

    // No determine some attributes of the note based upon the content
    // This should probably happen every time a note changes? Or at least something simular:
    QString content;
    if (t.__isset.content)
        content = QString::fromStdString(t.content);
    else
        content = "";

    position = content.indexOf("<en-crypt");
    if (position > 0) {
        query.bindValue(":lid", lid);
        query.bindValue(":key", NOTE_HAS_ENCRYPT);
        query.bindValue(":data", true);
        query.exec();
    }
    position = content.indexOf("<en-todo");
    if (position > 0) {
        position = content.indexOf("<en-todo checked=\"true\"");
        if (position > 0) {
            query.bindValue(":lid", lid);
            query.bindValue(":key", NOTE_HAS_TODO_COMPLETED);
            query.bindValue(":data", true);
            query.exec();
        }
        position = qMax(content.indexOf("<en-todo checked=\"false\""), content.indexOf("<en-todo>"));
        if (position > 0) {
            query.bindValue(":lid", lid);
            query.bindValue(":key", NOTE_HAS_TODO_UNCOMPLETED);
            query.bindValue(":data", true);
            query.exec();
        }
    }

    updateNoteList(lid, t, isDirty);
    return lid;
}
Ejemplo n.º 11
0
int InputCEC::CecCommand(void *cbParam, const cec_command command)
{
    InputCEC *cec = (InputCEC*)cbParam;

    switch(command.opcode)
    {
    case CEC_OPCODE_PLAY:
        cec->sendReceivedInput(CEC_INPUT_NAME, INPUT_KEY_PLAY);
        break;

    case CEC_OPCODE_DECK_CONTROL:
        if (command.parameters.size)
        {
            switch(command.parameters[0])
            {
            case CEC_DECK_CONTROL_MODE_SKIP_FORWARD_WIND:
                cec->sendReceivedInput(CEC_INPUT_NAME, INPUT_KEY_SEEKFWD);
                break;

            case CEC_DECK_CONTROL_MODE_SKIP_REVERSE_REWIND:
                cec->sendReceivedInput(CEC_INPUT_NAME, INPUT_KEY_SEEKBCK);
                break;

            case CEC_DECK_CONTROL_MODE_STOP:
                cec->sendReceivedInput(CEC_INPUT_NAME, INPUT_KEY_STOP);
                break;

            default:
                break;
            }
        }
        break;

    case CEC_OPCODE_VENDOR_REMOTE_BUTTON_DOWN:
        if (command.parameters.size)
        {
            switch(command.parameters[0])
            {
            // samsung Return key
            case CEC_USER_CONTROL_CODE_AN_RETURN:
                cec->sendReceivedInput(CEC_INPUT_NAME, INPUT_KEY_BACK);
                break;

            default:
                break;
            }
        }
        break;

    case CEC_OPCODE_VENDOR_REMOTE_BUTTON_UP:
    case CEC_OPCODE_USER_CONTROL_PRESSED:
        // ignore those commands as they are handled in CecKeypress
        break;

    case CEC_OPCODE_GIVE_OSD_NAME:
    case CEC_OPCODE_GIVE_PHYSICAL_ADDRESS:
        // ignore those known commands (only pollng from TV)
        break;

    default:
        QLOG_DEBUG() << "Unhandled CEC command " << command.opcode;
        if (command.parameters.size)
        {
            for (int i=0; i<command.parameters.size; i++)
                QLOG_DEBUG() << command.parameters.size << QString("parameters -> [%1]= %2").arg(i).arg(command.parameters[i]);
        }
        break;
    }

    return 1;
}
Ejemplo n.º 12
0
void ImportEnex::import(QString file) {
    fileName = file;
    errorMessage = "";

    lastError = 0;
    QFile xmlFile(fileName);
    QFile scanFile(fileName);
    if (!xmlFile.open(QIODevice::ReadOnly) || !scanFile.open(QIODevice::ReadOnly)) {
        lastError = 16;
        errorMessage = "Cannot open file.";
        return;
    }

    reader = new QXmlStreamReader(&xmlFile);
    QTextStream *countReader = new QTextStream(&scanFile);
    int recCnt = 0;

    QMessageBox mb;
    mb.setWindowTitle(tr("Scanning File"));
    mb.setText(QString::number(recCnt) + tr(" notes found."));
    QPushButton *cancelButton = mb.addButton(QMessageBox::Cancel);
    connect(cancelButton, SIGNAL(clicked()), this, SLOT(canceled()));
    mb.show();
    QCoreApplication::processEvents();

    while (!countReader->atEnd() && !stopNow) {
        QString line = countReader->readLine();
        if (line.contains("<note>")) {
            recCnt++;
            mb.setText(QString::number(recCnt) + tr(" notes found."));
            QCoreApplication::processEvents();
        }
    }

    progress->setMaximum(recCnt);
    progress->setMinimum(0);
    progress->setWindowTitle(tr("Importing Notes"));
    progress->setLabelText(tr("Importing Notes"));
    progress->setWindowModality(Qt::ApplicationModal);
    connect(progress, SIGNAL(canceled()), this, SLOT(canceled()));
    progress->setVisible(true);
    mb.close();
    progress->show();


    NSqlQuery query(global.db);
    query.exec("begin");
    recCnt = 0;
    while (!reader->atEnd() && !stopNow) {
        reader->readNext();
        if (reader->hasError()) {
            errorMessage = reader->errorString();
            QLOG_ERROR() << "************************* ERROR READING BACKUP " << errorMessage;
            lastError = 16;
            return;
        }

        if (reader->name().toString().toLower() == "en-export" && reader->isStartElement()) {
            QXmlStreamAttributes attributes = reader->attributes();
            QString version = attributes.value("version").toString();
            QString application = attributes.value("application").toString();
            // Version 5.x & 6.x are for Windows
            if (version != "5.x" && version != "6.x" && version.toLower() != "evernote mac") {
                lastError = 1;
                errorMessage = "Unknown export version = " +version;
                return;
            }
            if (application.toLower() != "evernote/windows" && application.toLower() != "evernote") {
                lastError = 2;
                errorMessage = "This export is from an unknown application = " +application;
                return;
            }
        }
        if (reader->name().toString().toLower() == "note" && reader->isStartElement()) {
            recCnt++;
            progress->setValue(recCnt);
            QLOG_DEBUG() << "Importing Note " << recCnt;
            processNoteNode();
        }
    }
    xmlFile.close();
    query.exec("commit");
    progress->hide();
}
Ejemplo n.º 13
0
int DisplayManager::findBestMatch(int display, DMMatchMediaInfo& matchInfo)
{

  // Grab current videomode information
  DMVideoModePtr currentVideoMode = getCurrentVideoMode(display);
  if (!currentVideoMode)
    return -1;

  // now we try to find the exact match in current resolution
  // then fill a list
  DMVideoModeWeightMap weights;

  DMVideoModeMap::const_iterator modeit = displays[display]->videoModes.constBegin();

  while (modeit != displays[display]->videoModes.constEnd())
  {
    DMVideoModePtr candidate = modeit.value();

    weights[candidate->id] = DMVideoModeWeightPtr(new DMVideoModeWeight);
    weights[candidate->id]->mode = candidate;
    weights[candidate->id]->weight = 0;

    // Weight Resolution match
    if ((candidate->width == currentVideoMode->width) &&
        (candidate->height == currentVideoMode->height) &&
        (candidate->bitsPerPixel == currentVideoMode->bitsPerPixel))
    {
      weights[candidate->id]->weight += MATCH_WEIGHT_RES;
    }

    // weight refresh rate
    // exact Match
    if (candidate->refreshRate == matchInfo.refreshRate)
      weights[candidate->id]->weight += MATCH_WEIGHT_REFRESH_RATE_EXACT;

    // exact multiple refresh rate
    if (isRateMultipleOf(matchInfo.refreshRate, candidate->refreshRate, true))
      weights[candidate->id]->weight += MATCH_WEIGHT_REFRESH_RATE_MULTIPLE;

    // close refresh match (less than 1 hz diff to match all 23.xxx modes to 24p)
    if (fabs(candidate->refreshRate - matchInfo.refreshRate) <= 1)
    {
      weights[candidate->id]->weight += MATCH_WEIGHT_REFRESH_RATE_CLOSE;
    }

    // approx multiple refresh rate
    if (isRateMultipleOf(matchInfo.refreshRate, candidate->refreshRate, false))
      weights[candidate->id]->weight += MATCH_WEIGHT_REFRESH_RATE_MULTIPLE_CLOSE;

    // weight interlacing
    if (candidate->interlaced == matchInfo.interlaced)
      weights[candidate->id]->weight += MATCH_WEIGHT_INTERLACE;

    if (candidate->id == currentVideoMode->id)
      weights[candidate->id]->weight += MATCH_WEIGHT_CURRENT;

    modeit++;
  }

  // now grab the mode with the highest weight
  DMVideoModeWeightPtr chosen;
  float maxWeight = 0;

  DMVideoModeWeightMap::const_iterator weightit = weights.constBegin();
  while (weightit != weights.constEnd())
  {
    QLOG_DEBUG() << "Mode " << weightit.value()->mode->id << "("
                 << weightit.value()->mode->getPrettyName() << ") has weight "
                 << weightit.value()->weight;
    if (weightit.value()->weight > maxWeight)
    {
      chosen = weightit.value();
      maxWeight = chosen->weight;
    }

    weightit++;
  }

  if ((chosen) && (chosen->weight > MATCH_WEIGHT_RES))
  {
    QLOG_INFO() << "DisplayManager RefreshMatch : found a suitable mode : "
                << chosen->mode->getPrettyName();
    return chosen->mode->id;
  }

  QLOG_INFO() << "DisplayManager RefreshMatch : found no suitable videomode";
  return -1;
}
Ejemplo n.º 14
0
void AuthenticateTask::processResponse(QJsonObject responseData)
{
	// Read the response data. We need to get the client token, access token, and the selected
	// profile.
	QLOG_DEBUG() << "Processing authentication response.";
	// QLOG_DEBUG() << responseData;
	// If we already have a client token, make sure the one the server gave us matches our
	// existing one.
	QLOG_DEBUG() << "Getting client token.";
	QString clientToken = responseData.value("clientToken").toString("");
	if (clientToken.isEmpty())
	{
		// Fail if the server gave us an empty client token
		changeState(STATE_FAILED_HARD, tr("Authentication server didn't send a client token."));
		return;
	}
	if (!m_account->m_clientToken.isEmpty() && clientToken != m_account->m_clientToken)
	{
		changeState(STATE_FAILED_HARD, tr("Authentication server attempted to change the client token. This isn't supported."));
		return;
	}
	// Set the client token.
	m_account->m_clientToken = clientToken;

	// Now, we set the access token.
	QLOG_DEBUG() << "Getting access token.";
	QString accessToken = responseData.value("accessToken").toString("");
	if (accessToken.isEmpty())
	{
		// Fail if the server didn't give us an access token.
		changeState(STATE_FAILED_HARD, tr("Authentication server didn't send an access token."));
		return;
	}
	// Set the access token.
	m_account->m_accessToken = accessToken;

	// Now we load the list of available profiles.
	// Mojang hasn't yet implemented the profile system,
	// but we might as well support what's there so we
	// don't have trouble implementing it later.
	QLOG_DEBUG() << "Loading profile list.";
	QJsonArray availableProfiles = responseData.value("availableProfiles").toArray();
	QList<AccountProfile> loadedProfiles;
	for (auto iter : availableProfiles)
	{
		QJsonObject profile = iter.toObject();
		// Profiles are easy, we just need their ID and name.
		QString id = profile.value("id").toString("");
		QString name = profile.value("name").toString("");
		bool legacy = profile.value("legacy").toBool(false);

		if (id.isEmpty() || name.isEmpty())
		{
			// This should never happen, but we might as well
			// warn about it if it does so we can debug it easily.
			// You never know when Mojang might do something truly derpy.
			QLOG_WARN() << "Found entry in available profiles list with missing ID or name "
						   "field. Ignoring it.";
		}

		// Now, add a new AccountProfile entry to the list.
		loadedProfiles.append({id, name, legacy});
	}
	// Put the list of profiles we loaded into the MojangAccount object.
	m_account->m_profiles = loadedProfiles;

	// Finally, we set the current profile to the correct value. This is pretty simple.
	// We do need to make sure that the current profile that the server gave us
	// is actually in the available profiles list.
	// If it isn't, we'll just fail horribly (*shouldn't* ever happen, but you never know).
	QLOG_DEBUG() << "Setting current profile.";
	QJsonObject currentProfile = responseData.value("selectedProfile").toObject();
	QString currentProfileId = currentProfile.value("id").toString("");
	if (currentProfileId.isEmpty())
	{
		changeState(STATE_FAILED_HARD, tr("Authentication server didn't specify a currently selected profile. The account exists, but likely isn't premium."));
		return;
	}
	if (!m_account->setCurrentProfile(currentProfileId))
	{
		changeState(STATE_FAILED_HARD, tr("Authentication server specified a selected profile that wasn't in the available profiles list."));
		return;
	}

	// this is what the vanilla launcher passes to the userProperties launch param
	if (responseData.contains("user"))
	{
		User u;
		auto obj = responseData.value("user").toObject();
		u.id = obj.value("id").toString();
		auto propArray = obj.value("properties").toArray();
		for (auto prop : propArray)
		{
			auto propTuple = prop.toObject();
			auto name = propTuple.value("name").toString();
			auto value = propTuple.value("value").toString();
			u.properties.insert(name, value);
		}
		m_account->m_user = u;
	}

	// We've made it through the minefield of possible errors. Return true to indicate that
	// we've succeeded.
	QLOG_DEBUG() << "Finished reading authentication response.";
	changeState(STATE_SUCCEEDED);
}
Ejemplo n.º 15
0
in_addr_t HostLookup(QString const& hostname)
{
   in_addr_t address(INADDR_NONE);

#ifdef WIN32

   // This can only handle IPv4 addresses and should only be used when
   // inet_ntop is unavailable.
   QString octet("(?:[0-1]?[0-9]?[0-9]|2[0-4][0-9]|25[0-5])");
   QRegExpValidator ipv4Validator(0);
   ipv4Validator.setRegExp(QRegExp(
      "^" + octet + "\\." + octet + "\\." + octet + "\\." + octet + "$"));

   int pos;
   QString tmp(hostname);

   if (ipv4Validator.validate(tmp,pos) == QValidator::Acceptable) {
      address = inet_addr(hostname.toLatin1().data());
      if (address == INADDR_ANY || address == INADDR_NONE) {
         throw InvalidHostname(hostname);
      }
   }else {
      struct hostent* host;
      host = gethostbyname(hostname.toLatin1().data());
      if (host->h_addrtype == AF_INET6) {
         throw Exception("IPv6 addresses are not supported");
      }else if (host) {
         address = *(in_addr_t*)host->h_addr;
      }
   }

#else

   struct addrinfo hints, *res;
   int errcode;
   char addrstr[100];
   void *ptr(0);

   memset(&hints, 0, sizeof (hints));
   hints.ai_family = PF_UNSPEC;
   hints.ai_socktype = SOCK_STREAM;
   hints.ai_flags |= AI_CANONNAME;

   errcode = getaddrinfo(hostname.toLatin1().data(), NULL, &hints, &res);
   if (errcode != 0) throw InvalidHostname(hostname);
 
   inet_ntop(res->ai_family, res->ai_addr->sa_data, addrstr, 100);

   switch (res->ai_family) {
      case AF_INET:
         ptr = &((struct sockaddr_in *) res->ai_addr)->sin_addr;
         break;
      case AF_INET6:
         ptr = &((struct sockaddr_in6 *) res->ai_addr)->sin6_addr;
         break;
   }

   inet_ntop(res->ai_family, ptr, addrstr, 100);
   address = inet_addr(addrstr);

   QString ipv((res->ai_family == PF_INET6) ? "IPv6 address:" : "IPv4 address:");
   QLOG_DEBUG() << ipv << QString(addrstr) << "=>" << QString(res->ai_canonname);

#endif

   return address;
}
void PlayerComponent::handleMpvEvent(mpv_event *event)
{
  switch (event->event_id)
  {
    case MPV_EVENT_START_FILE:
    {
      m_CurrentUrl = mpv::qt::get_property_variant(m_mpv, "path").toString();
      m_playbackStartSent = false;
      break;
    }
    case MPV_EVENT_FILE_LOADED:
    {
      emit playing(m_CurrentUrl);
      break;
    }
    case MPV_EVENT_END_FILE:
    {
      mpv_event_end_file *end_file = (mpv_event_end_file *)event->data;
      switch (end_file->reason)
      {
        case MPV_END_FILE_REASON_EOF:
          emit finished(m_CurrentUrl);
          break;
        case MPV_END_FILE_REASON_ERROR:
          emit error(end_file->error, mpv_error_string(end_file->error));
          break;
        default:
          emit stopped(m_CurrentUrl);
          break;
      }

      emit playbackEnded(m_CurrentUrl);
      m_CurrentUrl = "";

      m_restoreDisplayTimer.start(0);
      break;
    }
    case MPV_EVENT_IDLE:
    {
      emit playbackAllDone();
      break;
    }
    case MPV_EVENT_PLAYBACK_RESTART:
    {
      // it's also sent after seeks are completed
      if (!m_playbackStartSent)
        emit playbackStarting();
      m_playbackStartSent = true;
      break;
    }
    case MPV_EVENT_PROPERTY_CHANGE:
    {
      mpv_event_property *prop = (mpv_event_property *)event->data;
      if (strcmp(prop->name, "pause") == 0 && prop->format == MPV_FORMAT_FLAG)
      {
        int state = *(int *)prop->data;
        emit paused(state);
      }
      else if (strcmp(prop->name, "cache-buffering-state") == 0 && prop->format == MPV_FORMAT_INT64)
      {
        int64_t percentage = *(int64_t *)prop->data;
        emit buffering(percentage);
      }
      else if (strcmp(prop->name, "playback-time") == 0 && prop->format == MPV_FORMAT_DOUBLE)
      {
        double pos = *(double*)prop->data;
        if (fabs(pos - m_lastPositionUpdate) > 0.25)
        {
          quint64 ms = (quint64)(qMax(pos * 1000.0, 0.0));
          emit positionUpdate(ms);
          m_lastPositionUpdate = pos;
        }
      }
      else if (strcmp(prop->name, "vo-configured") == 0)
      {
        int state = prop->format == MPV_FORMAT_FLAG ? *(int *)prop->data : 0;
        emit windowVisible(state);
      }
      else if (strcmp(prop->name, "duration") == 0)
      {
        if (prop->format == MPV_FORMAT_DOUBLE)
          emit updateDuration(*(double *)prop->data * 1000.0);
      }
      else if (strcmp(prop->name, "audio-device-list") == 0)
      {
        updateAudioDeviceList();
      }
      break;
    }
    case MPV_EVENT_LOG_MESSAGE:
    {
      mpv_event_log_message *msg = (mpv_event_log_message *)event->data;
      // Strip the trailing '\n'
      size_t len = strlen(msg->text);
      if (len > 0 && msg->text[len - 1] == '\n')
        len -= 1;
      QString logline = QString::fromUtf8(msg->prefix) + ": " + QString::fromUtf8(msg->text, len);
      if (msg->log_level >= MPV_LOG_LEVEL_V)
        QLOG_DEBUG() << qPrintable(logline);
      else if (msg->log_level >= MPV_LOG_LEVEL_INFO)
        QLOG_INFO() << qPrintable(logline);
      else if (msg->log_level >= MPV_LOG_LEVEL_WARN)
        QLOG_WARN() << qPrintable(logline);
      else
        QLOG_ERROR() << qPrintable(logline);
      break;
    }
    case MPV_EVENT_CLIENT_MESSAGE:
    {
      mpv_event_client_message *msg = (mpv_event_client_message *)event->data;
      // This happens when the player is about to load the file, but no actual loading has taken part yet.
      // We use this to block loading until we explicitly tell it to continue.
      if (msg->num_args >= 3 && !strcmp(msg->args[0], "hook_run") && !strcmp(msg->args[1], "1"))
      {
        QString resume_id = QString::fromUtf8(msg->args[2]);
        // Calling this lambda will instruct mpv to continue loading the file.
        auto resume = [=] {
          QLOG_INFO() << "resuming loading";
          mpv::qt::command_variant(m_mpv, QStringList() << "hook-ack" << resume_id);
        };
        if (switchDisplayFrameRate())
        {
          // Now wait for some time for mode change - this is needed because mode changing can take some
          // time, during which the screen is black, and initializing hardware decoding could fail due
          // to various strange OS-related reasons.
          // (Better hope the user doesn't try to exit Konvergo during mode change.)
          int pause = SettingsComponent::Get().value(SETTINGS_SECTION_VIDEO, "refreshrate.delay").toInt() * 1000;
          QLOG_INFO() << "waiting" << pause << "msec after rate switch before loading";
          QTimer::singleShot(pause, resume);
        }
        else
        {
          resume();
        }
        break;
      }
    }
    default:; /* ignore */
  }
}
Ejemplo n.º 17
0
bool TestNetworkConnection()
{
   bool okay(true);

   try {
      HttpConnection http("iqmol.q-chem.com");
      http.open();

      QEventLoop loop;
      Reply* reply;
/*
      QStringList input;

      input << "$molecule"
            << "0  1"
            << "He"
            << "$end"

            << "$rem"
            << "  exchange  hf"
            << "  gui       2"
            << "  basis     6-31G"
            << "$end";

      reply = http.post("submit", input.join("\n"));


      QObject::connect(reply, SIGNAL(finished()), &loop, SLOT(quit()));
      loop.exec();

      okay = (reply->status() == Reply::Finished);
      if (okay) {
         QLOG_DEBUG() << "--------- SUCCESS -------------";
         QLOG_DEBUG() << reply->message();
         QLOG_DEBUG() << "-------------------------------";
      }
      else {
         QLOG_DEBUG() << "----------- ERROR -------------";
         QLOG_DEBUG() << reply->message();
         QLOG_DEBUG() << "-------------------------------";
      }

      delete reply;

*/


      // reply = http.get("list?jobid=db33b0f063b511e4bda190b11c4a068c");

      //reply = http.get("status?jobid=db33b0f063b511e4bda190b11c4a068c");

      //reply = http.get("register");
      //reply = http.get("download?jobid=22dbd72c647211e4a1d190b11c4a068c&cookie=4b6d8c1c5b3743efbc2acd550887b7a4&file=input.FChk");
      reply = http.get("download?cookie=4b6d8c1c5b3743efbc2acd550887b7a4&jobid=22dbd72c647211e4a1d190b11c4a068c&file=input.FChk");

      QObject::connect(reply, SIGNAL(finished()), &loop, SLOT(quit()));
      loop.exec();

      okay = (reply->status() == Reply::Finished);
      if (okay) {
         QLOG_DEBUG() << "--------- SUCCESS -------------";
         QLOG_DEBUG() << reply->message();
         QLOG_DEBUG() << "-------------------------------";
      }
      else {
         QLOG_DEBUG() << "----------- ERROR -------------";
         QLOG_DEBUG() << reply->message();
         QLOG_DEBUG() << "-------------------------------";
      }

      delete reply;

      reply = http.get("list?jobid=db33b0f063b511e4bda190b11c4a068c&cookie=4b6d8c1c5b3743efbc2acd550887b7a4");

      QObject::connect(reply, SIGNAL(finished()), &loop, SLOT(quit()));
      loop.exec();

      okay = (reply->status() == Reply::Finished);
      if (okay) {
         QLOG_DEBUG() << "--------- SUCCESS -------------";
         QLOG_DEBUG() << reply->message();
         QLOG_DEBUG() << "-------------------------------";
      }
      else {
         QLOG_DEBUG() << "----------- ERROR -------------";
         QLOG_DEBUG() << reply->message();
         QLOG_DEBUG() << "-------------------------------";
      }

      delete reply;

   // These catch the connection errors, not the reply errors
   }catch (AuthenticationError& err) {
      QMsgBox::warning(0, "IQmol", "Invalid username or password");

   }catch (Exception& err) {
      okay = false;
      QMsgBox::warning(0, "IQmol", err.what());
   }

   return okay;
}
Ejemplo n.º 18
0
void KonvergoWindow::setFullScreen(bool enable)
{
  QLOG_DEBUG() << "setting fullscreen = " << enable;

  SettingsComponent::Get().setValue(SETTINGS_SECTION_MAIN, "fullscreen", enable);
}
Ejemplo n.º 19
0
void TagEditorNewTag::enterPressed() {
    QLOG_DEBUG() << "Enter pressed in new tag";
    QKeyEvent *event = new QKeyEvent (QEvent::KeyPress, Qt::Key_Tab, Qt::NoModifier);
    QCoreApplication::postEvent (this, event);
}
Ejemplo n.º 20
0
void TableView3D::setValue(int row, int column,double value,bool ignoreselection)
{
	if (row >= ui.tableWidget->rowCount() || column >= ui.tableWidget->columnCount())
	{
		QLOG_ERROR() << "Larger than life, should be unreachable code! FIXME!";
		return;
	}
	// Ignore bottom right corner if the disallow on editing fails
	if (row == -1 && column == -1)
	{
		QLOG_ERROR() << "This should not happen! Bottom right corner ignored!";
		return;
	}
	//bool conversionOk = false; // Note, value of this is irrelevant, overwritten during call in either case, but throws a compiler error if not set.
	//double tempValue = ui.tableWidget->item(row,column)->text().toDouble(&conversionOk);
	double tempValue = value;
	double oldValue = tempValue;
	/*if (!conversionOk)
	{
		QMessageBox::information(0,"Error","Value entered is not a number!");
		setSilentValue(row,column,formatNumber(currentvalue));
		//ui.tableWidget->item(row,column)->setText(QString::number(currentvalue));
		return;
	}*/

	//ui.tableWidget->item(row,column)->setText(QString::number(tempValue,'f',2));
	//tempValue = ui.tableWidget->item(row,column)->text().toDouble(&conversionOk);

	//New value has been accepted. Let's write it.

	//If the value is an axis, and there are multiple cells selected, cancel the edit!
	if (ui.tableWidget->selectedItems().size() > 1 && !ignoreselection)
	{
		for (int i=0;i<ui.tableWidget->selectedItems().size();i++)
		{
			if (ui.tableWidget->selectedItems()[i].y() == ui.tableWidget->rowCount()-1)
			{
				QLOG_ERROR() << "XAxis edit attempted with multiple cells selected. This is not allowed";
				QMessageBox::information(0,"Error","Editing of multiple AXIS cells at once is not allowed. Please select a single axis cell to edit at a time");
				//setSilentValue(row,column,m_currentValue);
				return;
			}
			if (ui.tableWidget->selectedItems()[i].x() == 0)
			{
				QLOG_ERROR() << "YAxis edit attempted with multiple cells selected. This is not allowed";
				QMessageBox::information(0,"Error","Editing of multiple AXIS cells at once is not allowed. Please select a single axis cell to edit at a time");
				//setSilentValue(row,column,m_currentValue);
				return;
			}
		}
		setSilentValue(row,column,m_currentValue); //Reset the value, setRange will set it properly.
		//currentvalue = oldValue;
		QLOG_DEBUG() << "Setting all cells to" << m_currentValue << "for" << row << column;
		QList<QPair<QPair<int,int>,double> > vallist;
		for (int i=0;i<ui.tableWidget->selectedItems().size();i++)
		{
			QPair<QPair<int,int>,double> val;
			val.first = QPair<int,int>(ui.tableWidget->selectedItems()[i].y(),ui.tableWidget->selectedItems()[i].x());
			val.second = tempValue;
			vallist.append(val);
		}
		setRange(vallist);
	}
	else
	{
		if (row == -1)
		{

			if (tempValue > tableData->maxCalcedXAxis())
			{
				QMessageBox::information(0,"Error",QString("Value entered too large! Value range " + QString::number(tableData->minCalcedXAxis()) + "-" + QString::number(tableData->maxCalcedXAxis()) + ". Entered value:") + ui.tableWidget->item(row,column));
				//setSilentValue(row,column,m_currentValue);
				//ui.tableWidget->item(row,column)->setText(QString::number(currentvalue));
				return;
			}
			else if (tempValue < tableData->minCalcedXAxis())
			{
				QMessageBox::information(0,"Error",QString("Value entered too small! Value range " + QString::number(tableData->minCalcedXAxis()) + "-" + QString::number(tableData->maxCalcedXAxis()) + ". Entered value:") + ui.tableWidget->item(row,column));
				//setSilentValue(row,column,m_currentValue);
				//ui.tableWidget->item(row,column)->setText(QString::number(currentvalue));
				return;
			}
			//setSilentValue(row,column,formatNumber(tempValue,m_metaData.xDp));
			tableData->setXAxis(column,oldValue);
		}
		else if (column == -1)
		{
			//setSilentValue(row,column,formatNumber(tempValue,m_metaData.yDp));
			if (tempValue > tableData->maxCalcedYAxis())
			{
				QMessageBox::information(0,"Error",QString("Value entered too large! Value range " + QString::number(tableData->minCalcedYAxis()) + "-" + QString::number(tableData->maxCalcedYAxis()) + ". Entered value:") + ui.tableWidget->item(row,column));
				//ui.tableWidget->item(row,column)->setText(QString::number(currentvalue));
				//setSilentValue(row,column,m_currentValue);
				return;
			}
			else if (tempValue < tableData->minCalcedYAxis())
			{
				QMessageBox::information(0,"Error",QString("Value entered too small! Value range " + QString::number(tableData->minCalcedYAxis()) + "-" + QString::number(tableData->maxCalcedYAxis()) + ". Entered value:") + ui.tableWidget->item(row,column));
				//ui.tableWidget->item(row,column)->setText(QString::number(currentvalue));
				//setSilentValue(row,column,m_currentValue);
				return;
			}
			tableData->setYAxis(ui.tableWidget->rowCount()-(row+1),oldValue);
		}
		else
		{
			//setSilentValue(row,column,formatNumber(tempValue,m_metaData.zDp));
			if (tempValue > tableData->maxCalcedValue())
			{
				QMessageBox::information(0,"Error",QString("Value entered too large! Value range " + QString::number(tableData->minCalcedValue()) + "-" + QString::number(tableData->maxCalcedValue()) + ". Entered value:") + ui.tableWidget->item(row,column));
				//ui.tableWidget->item(row,column)->setText(QString::number(currentvalue));
				//setSilentValue(row,column,m_currentValue);
				return;
			}
			if (tempValue < tableData->minCalcedValue())
			{
				QMessageBox::information(0,"Error",QString("Value entered too small! Value range " + QString::number(tableData->minCalcedValue()) + "-" + QString::number(tableData->maxCalcedValue()) + ". Entered value:") + ui.tableWidget->item(row,column));
				//ui.tableWidget->item(row,column)->setText(QString::number(currentvalue));
				//setSilentValue(row,column,m_currentValue);
				return;
			}
			tableData->setCell(ui.tableWidget->rowCount()-(row+1),column,oldValue);
		}
	}
}
Ejemplo n.º 21
0
void SyncRunner::applicationException(QString s) {
    QLOG_DEBUG() << "Application Exception!!! : " << s;
}
Ejemplo n.º 22
0
void OcFeedsModelNew::feedsRequested(const QList<int> &updated, const QList<int> &newFeeds, const QList<int> &deleted)
{
    if (updated.isEmpty() && newFeeds.isEmpty() && deleted.isEmpty())
        return;

    QSqlQuery query;

    if (!updated.isEmpty()) {

        QLOG_INFO() << "Feeds model: updating changed feeds";

        for (int i = 0; i < updated.size(); ++i)
        {
            int idx = findIndex(updated.at(i), 0);

            if (!query.exec(QString("SELECT title, iconSource, iconWidth, iconHeight, folderId, localUnreadCount, FROM feeds WHERE id = %1").arg(updated.at(i)))) {
                QLOG_ERROR() << "Feeds model: failed to select data for changed feeds from database: " << query.lastError().text();
            }

            query.next();

            int fId = query.value(4).toInt();

            // check if updated feed is still child of these folder
            if ((idx != -999) && (fId == folderId())) {

                QLOG_DEBUG() << "Feeds model: updating feed at index " << idx;

                m_items.at(i)->title = query.value(0).toString();
                m_items.at(i)->iconSource = query.value(1).toString();
                m_items.at(i)->iconWidth = query.value(2).toInt();
                m_items.at(i)->iconHeight = query.value(3).toInt();

                QVector<int> roles(1, TitleRole);
                roles.append(IconSourceRole);
                roles.append(IconWidthRole);
                roles.append(IconHeightRole);

#if QT_VERSION >= QT_VERSION_CHECK(5, 0, 0)
                emit dataChanged(index(idx), index(idx), roles);
#else
                emit dataChanged(index(idx), index(idx));
#endif
            } else if ((idx != -999) && (fId != folderId())) {

                // the updated feed is no longer child of these folder

                QLOG_DEBUG() << "Feeds model: removing feed at index " << idx << " because it is no longer child of this folder";

                beginRemoveRows(QModelIndex(), idx, idx);

                delete m_items.takeAt(i);

                endRemoveRows();
            } else if ((idx == -999) && (fId == folderId())) {

                // the feed has been moved to this folder

                QLOG_DEBUG() << "Feeds model: adding feed that has been moved to this folder";

                beginInsertRows(QModelIndex(), rowCount(), rowCount());

                OcFeedObject *fobj = new OcFeedObject(updated.at(i),
                                                      0,
                                                      query.value(0).toString(),
                                                      query.value(5).toInt(),
                                                      query.value(1).toString(),
                                                      query.value(2).toInt(),
                                                      query.value(3).toInt());
                m_items.append(fobj);

                endInsertRows();
            }
        }
    }


    if (!newFeeds.isEmpty()) {

        QString feedList("(");
        for (int i = 0; i < newFeeds.size(); ++i) {
            feedList.append(QString::number(newFeeds.at(i)));
            feedList.append(", ");
        }
        feedList.chop(2);
        feedList.append(")");

        int length = 0;

        if (!query.exec(QString("SELECT COUNT(id) FROM feeds WHERE folderId = %1 AND id IN %2").arg(folderId()).arg(feedList))) {
            QLOG_ERROR() << "Feeds model: failed to select count of new feeds in this folder from database: " << query.lastError().text();
        }

        query.next();

        length = query.value(0).toInt();

        if (length > 0) {

            QLOG_INFO() << "Feeds model: adding new feeds";

            if (!query.exec(QString("SELECT id, title, localUnreadCount, iconSource, iconWidth, iconHeight WHERE folderId = %1 AND id IN %2").arg(folderId()).arg(feedList))) {
                QLOG_ERROR() << "Feeds model: failed to select data for newly added feeds from database: " << query.lastError().text();
            }

            beginInsertRows(QModelIndex(), rowCount(), (rowCount() + length - 1));

            while(query.next()) {

                OcFeedObject *fobj = new OcFeedObject(query.value(0).toInt(),
                                                      0,
                                                      query.value(1).toString(),
                                                      query.value(2).toInt(),
                                                      query.value(3).toString(),
                                                      query.value(4).toInt(),
                                                      query.value(5).toInt());
                m_items.append(fobj);
            }

            endInsertRows();

            endInsertRows();
        }
    }


    if (!deleted.isEmpty()) {

        for (int i = 0; i < deleted.size(); ++i) {

            int idx = findIndex(deleted.at(i), 0);

            if (idx != -999) {

                QLOG_INFO() << "Feeds model: removing deleted feed at index " << idx;

                beginRemoveRows(QModelIndex(), idx, idx);

                delete m_items.takeAt(idx);

                endRemoveRows();
            }
        }
    }

    queryAndSetTotalUnread();
}
Ejemplo n.º 23
0
// --------------- Move ---------------
void Move::reset()
{
   QLOG_DEBUG() << "Animator: Move::reset() called";
   //m_object->setPosition(m_endPoint);
}
Ejemplo n.º 24
0
void UpdateChecker::updateCheckFinished(bool notifyNoUpdate)
{
	QLOG_DEBUG() << "Finished downloading repo index. Checking for new versions.";

	QJsonParseError jsonError;
	QByteArray data;
	{
		ByteArrayDownloadPtr dl =
			std::dynamic_pointer_cast<ByteArrayDownload>(indexJob->first());
		data = dl->m_data;
		indexJob.reset();
	}

	QJsonDocument jsonDoc = QJsonDocument::fromJson(data, &jsonError);
	if (jsonError.error != QJsonParseError::NoError || !jsonDoc.isObject())
	{
		QLOG_ERROR() << "Failed to parse GoUpdate repository index. JSON error"
					 << jsonError.errorString() << "at offset" << jsonError.offset;
		return;
	}

	QJsonObject object = jsonDoc.object();

	bool success = false;
	int apiVersion = object.value("ApiVersion").toVariant().toInt(&success);
	if (apiVersion != API_VERSION || !success)
	{
		QLOG_ERROR() << "Failed to check for updates. API version mismatch. We're using"
					 << API_VERSION << "server has" << apiVersion;
		return;
	}

	QLOG_DEBUG() << "Processing repository version list.";
	QJsonObject newestVersion;
	QJsonArray versions = object.value("Versions").toArray();
	for (QJsonValue versionVal : versions)
	{
		QJsonObject version = versionVal.toObject();
		if (newestVersion.value("Id").toVariant().toInt() <
			version.value("Id").toVariant().toInt())
		{
			newestVersion = version;
		}
	}

	// We've got the version with the greatest ID number. Now compare it to our current build
	// number and update if they're different.
	int newBuildNumber = newestVersion.value("Id").toVariant().toInt();
	if (newBuildNumber != BuildConfig.VERSION_BUILD)
	{
		QLOG_DEBUG() << "Found newer version with ID" << newBuildNumber;
		// Update!
		emit updateAvailable(m_repoUrl, newestVersion.value("Name").toVariant().toString(),
							 newBuildNumber);
	}
	else if (notifyNoUpdate)
	{
		emit noUpdateFound();
	}

	m_updateChecking = false;
}
Ejemplo n.º 25
0
void NWebView::downloadAttachment(QNetworkRequest *req) {
    QLOG_DEBUG() << req->url().toString();
    emit(downloadAttachmentRequested(req));
}
Ejemplo n.º 26
0
void HelperLauncher::socketDisconnect()
{
  QLOG_DEBUG() << "Disconnected from helper, trying to relaunch";
  connectToHelper();
}
Ejemplo n.º 27
0
EditorButtonBar::EditorButtonBar(QWidget *parent) :
    QToolBar(parent)
{
    contextMenu = new QMenu();
    undoVisible = contextMenu->addAction(tr("Undo"));
    redoVisible = contextMenu->addAction(tr("Redo"));
    cutVisible  = contextMenu->addAction(tr("Cut"));
    copyVisible = contextMenu->addAction(tr("Copy"));
    pasteVisible = contextMenu->addAction(tr("Paste"));
    removeFormatVisible = contextMenu->addAction(tr("Remove Formatting"));
    boldVisible = contextMenu->addAction(tr("Bold"));
    italicVisible = contextMenu->addAction(tr("Italics"));
    superscriptVisible = contextMenu->addAction(tr("Superscript"));
    subscriptVisible = contextMenu->addAction(tr("Subscript"));
    underlineVisible = contextMenu->addAction(tr("Underline"));
    strikethroughVisible = contextMenu->addAction(tr("Strikethrough"));
    leftJustifyVisible = contextMenu->addAction(tr("Align Left"));
    centerJustifyVisible = contextMenu->addAction(tr("Align Center"));
    rightJustifyVisible = contextMenu->addAction(tr("Align Right"));
    hlineVisible = contextMenu->addAction(tr("Horizontal Line"));
    insertDatetimeVisible = contextMenu->addAction(tr("Insert Date && Time"));
    shiftRightVisible = contextMenu->addAction(tr("Shift Right"));
    shiftLeftVisible = contextMenu->addAction(tr("Shift Left"));
    bulletListVisible = contextMenu->addAction(tr("Bullet List"));
    numberListVisible = contextMenu->addAction(tr("Number List"));
    fontVisible = contextMenu->addAction(tr("Font"));
    fontSizeVisible = contextMenu->addAction(tr("Font Size"));
    fontColorVisible = contextMenu->addAction(tr("Font Color"));
    highlightVisible = contextMenu->addAction(tr("Highlight"));
    todoVisible = contextMenu->addAction(tr("To-do"));
    spellCheckButtonVisible = contextMenu->addAction(tr("Spell Check"));
    insertTableButtonVisible = contextMenu->addAction(tr("Insert Table"));
    htmlEntitiesButtonVisible = contextMenu->addAction(tr("HTML Entities"));

    undoVisible->setCheckable(true);
    redoVisible->setCheckable(true);
    cutVisible->setCheckable(true);
    copyVisible->setCheckable(true);
    pasteVisible->setCheckable(true);
    removeFormatVisible->setCheckable(true);
    boldVisible->setCheckable(true);
    italicVisible->setCheckable(true);
    underlineVisible->setCheckable(true);
    strikethroughVisible->setCheckable(true);
    superscriptVisible->setCheckable(true);
    subscriptVisible->setCheckable(true);
    leftJustifyVisible->setCheckable(true);
    centerJustifyVisible->setCheckable(true);
    rightJustifyVisible->setCheckable(true);
    hlineVisible->setCheckable(true);
    shiftRightVisible->setCheckable(true);
    shiftLeftVisible->setCheckable(true);
    bulletListVisible->setCheckable(true);
    numberListVisible->setCheckable(true);
    todoVisible->setCheckable(true);
    fontColorVisible->setCheckable(true);
    highlightVisible->setCheckable(true);
    fontColorVisible->setCheckable(true);
    fontSizeVisible->setCheckable(true);
    fontVisible->setCheckable(true);
    spellCheckButtonVisible->setCheckable(true);
    spellCheckButtonVisible->setChecked(true);
    insertTableButtonVisible->setCheckable(true);
    htmlEntitiesButtonVisible->setCheckable(true);
    insertDatetimeVisible->setCheckable(true);

    connect(undoVisible, SIGNAL(triggered()), this, SLOT(toggleUndoButtonVisible()));
    connect(redoVisible, SIGNAL(triggered()), this, SLOT(toggleRedoButtonVisible()));
    connect(cutVisible, SIGNAL(triggered()), this, SLOT(toggleCutButtonVisible()));
    connect(copyVisible, SIGNAL(triggered()), this, SLOT(toggleCopyButtonVisible()));
    connect(pasteVisible, SIGNAL(triggered()), this, SLOT(togglePasteButtonVisible()));
    connect(removeFormatVisible, SIGNAL(triggered()), this, SLOT(toggleRemoveFormatVisible()));
    connect(boldVisible, SIGNAL(triggered()), this, SLOT(toggleBoldButtonVisible()));
    connect(italicVisible, SIGNAL(triggered()), this, SLOT(toggleItalicButtonVisible()));
    connect(underlineVisible, SIGNAL(triggered()), this, SLOT(toggleUnderlineButtonVisible()));
    connect(strikethroughVisible, SIGNAL(triggered()), this, SLOT(toggleStrikethroughButtonVisible()));
    connect(superscriptVisible, SIGNAL(triggered()), this, SLOT(toggleSuperscriptButtonVisible()));
    connect(subscriptVisible, SIGNAL(triggered()), this, SLOT(toggleSubscriptButtonVisible()));
    connect(insertDatetimeVisible, SIGNAL(triggered()), this, SLOT(toggleInsertDatetimeVisible()));
    connect(leftJustifyVisible, SIGNAL(triggered()), this, SLOT(toggleLeftJustifyButtonVisible()));
    connect(centerJustifyVisible, SIGNAL(triggered()), this, SLOT(toggleCenterJustifyButtonVisible()));
    connect(rightJustifyVisible, SIGNAL(triggered()), this, SLOT(toggleRightJustifyButtonVisible()));
    connect(hlineVisible, SIGNAL(triggered()), this, SLOT(toggleHlineButtonVisible()));
    connect(shiftRightVisible, SIGNAL(triggered()), this, SLOT(toggleShiftRightButtonVisible()));
    connect(shiftLeftVisible, SIGNAL(triggered()), this, SLOT(toggleShiftLeftButtonVisible()));
    connect(bulletListVisible, SIGNAL(triggered()), this, SLOT(toggleBulletListButtonVisible()));
    connect(numberListVisible, SIGNAL(triggered()), this, SLOT(toggleNumberListButtonVisible()));
    connect(fontVisible, SIGNAL(triggered()), this, SLOT(toggleFontButtonVisible()));
    connect(fontSizeVisible, SIGNAL(triggered()), this, SLOT(toggleFontSizeButtonVisible()));
    connect(todoVisible, SIGNAL(triggered()), this, SLOT(toggleTodoButtonVisible()));
    connect(highlightVisible, SIGNAL(triggered()), this, SLOT(toggleHighlightColorVisible()));
    connect(fontColorVisible, SIGNAL(triggered()), this, SLOT(toggleFontColorVisible()));
    connect(insertTableButtonVisible, SIGNAL(triggered()), this, SLOT(toggleInsertTableButtonVisible()));
    connect(spellCheckButtonVisible, SIGNAL(triggered()), this, SLOT(toggleSpellCheckButtonVisible()));
    connect(htmlEntitiesButtonVisible, SIGNAL(triggered()), this, SLOT(toggleHtmlEntitiesButtonVisible()));


  undoButtonAction = this->addAction(global.getIconResource(":undoIcon"), tr("Undo"));
  undoButtonShortcut = new QShortcut(this);
  setupShortcut(undoButtonShortcut, "Edit_Undo");

  redoButtonAction = this->addAction(global.getIconResource(":redoIcon"), tr("Redo"));
  redoButtonShortcut = new QShortcut(this);
  setupShortcut(redoButtonShortcut, "Edit_Redo");
  redoButtonShortcut->setContext(Qt::WidgetShortcut);

  cutButtonAction = this->addAction(global.getIconResource(":cutIcon"), tr("Cut"));
  cutButtonShortcut = new QShortcut(this);
  setupShortcut(cutButtonShortcut, "Edit_Cut");

  copyButtonAction = this->addAction(global.getIconResource(":copyIcon"), tr("Copy"));
  copyButtonShortcut = new QShortcut(this);
  setupShortcut(copyButtonShortcut, "Edit_Copy");

  pasteButtonAction = this->addAction(global.getIconResource(":pasteIcon"), tr("Paste"));
  //this->setupShortcut(pasteButtonAction, "Edit_Paste");  // This is captured in NWebView via a keyevent statement

  removeFormatButtonAction = this->addAction(global.getIconResource(":eraserIcon"), tr("Remove Formatting"));
  removeFormatButtonShortcut = new QShortcut(this);
  this->setupShortcut(removeFormatButtonShortcut, "Edit_Remove_Formatting");
  QLOG_DEBUG() << removeFormatButtonShortcut->key();

  boldButtonWidget = new QToolButton(this);
  boldButtonWidget->setIcon(global.getIconResource(":boldIcon"));
  boldButtonWidget->setText(tr("Bold"));
  boldButtonAction = this->addWidget(boldButtonWidget);
  boldButtonShortcut = new QShortcut(this);
  this->setupShortcut(boldButtonShortcut, "Format_Bold");

  italicButtonWidget = new QToolButton(this);
  italicButtonWidget->setIcon(global.getIconResource(":italicsIcon"));
  italicButtonWidget->setText(tr("Italics"));
  italicButtonWidget->setToolTip(tr("Italics"));
  italicButtonAction = this->addWidget(italicButtonWidget);
  italicButtonShortcut = new QShortcut(this);
  this->setupShortcut(italicButtonShortcut, "Format_Italic");

  underlineButtonWidget = new QToolButton(this);
  underlineButtonWidget->setIcon(global.getIconResource(":underlineIcon"));
  underlineButtonWidget->setText(tr("Underline"));
  underlineButtonWidget->setToolTip(tr("Underline"));
  underlineButtonAction = this->addWidget(underlineButtonWidget);
  underlineButtonShortcut = new QShortcut(this);
  this->setupShortcut(underlineButtonShortcut, "Format_Underline");

  strikethroughButtonAction = this->addAction(global.getIconResource(":strikethroughIcon"), tr("Strikethrough"));
  strikethroughButtonShortcut = new QShortcut(this);
  this->setupShortcut(strikethroughButtonShortcut, "Format_Strikethrough");

  superscriptButtonAction = this->addAction(global.getIconResource(":superscriptIcon"), tr("Superscript"));
  superscriptButtonShortcut = new QShortcut(this);
  this->setupShortcut(superscriptButtonShortcut, "Format_Superscript");

  subscriptButtonAction = this->addAction(global.getIconResource(":subscriptIcon"), tr("Subscript"));
  subscriptButtonShortcut = new QShortcut(this);
  this->setupShortcut(subscriptButtonShortcut, "Format_Subscript");

  centerJustifyButtonAction = this->addAction(global.getIconResource(":centerAlignIcon"), tr("Center"));
  centerJustifyButtonShortcut = new QShortcut(this);
  this->setupShortcut(centerJustifyButtonShortcut, "Format_Alignment_Center");

  rightJustifyButtonAction = this->addAction(global.getIconResource(":rightAlignIcon"), tr("Right Justify"));
  rightJustifyButtonShortcut = new QShortcut(this);
  this->setupShortcut(rightJustifyButtonShortcut, "Format_Alignment_Right");

  leftJustifyButtonAction = this->addAction(global.getIconResource(":leftAlignIcon"), tr("Left Justify"));
  leftJustifyButtonShortcut = new QShortcut(this);
  this->setupShortcut(leftJustifyButtonShortcut, "Format_Alignment_Left");

  hlineButtonAction = this->addAction(global.getIconResource(":hlineIcon"), tr("Horizontal Line"));
  hlineButtonShortcut = new QShortcut(this);
  this->setupShortcut(hlineButtonShortcut, "Format_Horizontal_Line");

  insertDatetimeButtonWidget = new QToolButton(this);
  insertDatetimeButtonWidget->setIcon(global.getIconResource(":dateTime"));
  insertDatetimeButtonWidget->setText(tr("Insert Date & Time"));
  insertDatetimeButtonWidget->setToolTip(tr("Insert Date & Time"));
  insertDatetimeButtonAction = this->addWidget(insertDatetimeButtonWidget);
  insertDatetimeButtonShortcut = new QShortcut(this);
  insertDatetimeButtonShortcut->setKey(insertDatetimeButtonWidget->shortcut());

  shiftRightButtonAction = this->addAction(global.getIconResource(":shiftRightIcon"), tr("Shift Right"));
  shiftRightButtonShortcut = new QShortcut(this);
  this->setupShortcut(shiftRightButtonShortcut, "Format_Indent_Increase");

  shiftLeftButtonAction = this->addAction(global.getIconResource(":shiftLeftIcon"), tr("Shift Left"));
  shiftLeftButtonShortcut = new QShortcut(this);
  this->setupShortcut(shiftLeftButtonShortcut, "Format_Indent_Decrease");

  bulletListButtonAction = this->addAction(global.getIconResource(":bulletListIcon"), tr("Bullet List"));
  bulletListButtonShortcut = new QShortcut(this);
  this->setupShortcut(bulletListButtonShortcut, "Format_List_Bullet");

  numberListButtonAction = this->addAction(global.getIconResource(":numberListIcon"), tr("Number List"));
  numberListButtonShortcut = new QShortcut(this);
  this->setupShortcut(numberListButtonShortcut, "Format_List_Numbered");

  fontNames = new FontNameComboBox(this);
  fontSizes = new FontSizeComboBox(this);

  loadFontNames();
  fontButtonAction = addWidget(fontNames);
  fontSizeButtonAction = addWidget(fontSizes);

  fontColorMenuWidget = new ColorMenu();
  fontColorButtonWidget = new QToolButton(this);
  fontColorButtonWidget->setAutoRaise(false);
  fontColorButtonWidget->setMenu(fontColorMenuWidget->getMenu());
  fontColorButtonWidget->setIcon(global.getIconResource(":fontColorIcon"));
  fontColorButtonWidget->setToolTip(tr("Font Color"));
  fontColorAction = this->addWidget(fontColorButtonWidget);

  highlightColorMenuWidget = new ColorMenu();
  highlightColorMenuWidget->setDefault(Qt::yellow);
  highlightColorButtonWidget = new QToolButton(this);
  highlightColorButtonWidget->setAutoRaise(false);
  highlightColorButtonWidget->setMenu(highlightColorMenuWidget->getMenu());
  highlightColorButtonWidget->setIcon(global.getIconResource(":fontHighlightIcon"));
  highlightColorButtonWidget->setToolTip(tr("Highlight"));
  highlightColorAction = this->addWidget(highlightColorButtonWidget);
  highlightColorShortcut = new QShortcut(this);
  this->setupShortcut(highlightColorShortcut, "Format_Highlight");

  todoButtonAction = this->addAction(global.getIconResource(":todoIcon"), tr("Todo"));
  todoButtonShortcut = new QShortcut(this);
  this->setupShortcut(todoButtonShortcut, "Edit_Insert_Todo");

  spellCheckButtonAction = this->addAction(global.getIconResource(":spellCheckIcon"), tr("Spell Check"));
  spellCheckButtonShortcut = new QShortcut(this);
  this->setupShortcut(spellCheckButtonShortcut, "Tools_Spell_Check");

  insertTableButtonAction = this->addAction(global.getIconResource(":gridIcon"), tr("Insert Table"));
  insertTableButtonShortcut = new QShortcut(this);
  this->setupShortcut(insertTableButtonShortcut, "Edit_Insert_Table");

  htmlEntitiesButtonAction = this->addAction(global.getIconResource(":htmlentitiesIcon"), tr("Insert HTML Entities"));
  htmlEntitiesButtonShortcut = new QShortcut(this);
  setupShortcut(htmlEntitiesButtonShortcut, "Edit_Insert_Html_Entities");
  htmlEntitiesButtonShortcut->setContext(Qt::WidgetShortcut);
}
Ejemplo n.º 28
0
void HelperLauncher::didConnect()
{
  QLOG_DEBUG() << "Connected to helper";
  updateClientId();
}
Ejemplo n.º 29
0
//***********************************************************
//* Process a <noteresource> node.
//***********************************************************
void ImportData::processResource(Resource &resource) {
    QLOG_DEBUG() << "Processing Resource Node";

    bool atEnd = false;
    //bool isDirty = false;

    while(!atEnd) {
        if (reader->isStartElement()) {
            QString name = reader->name().toString().toLower();
            if (name == "guid") {
                resource.guid = textValue();
            }
            if (!backup) {
                QUuid uuid;
                QString g =  uuid.createUuid().toString().replace("{","").replace("}","");
                resource.guid = g;
            }
            if (name == "noteguid") {
                QString tx = textValue();
                resource.noteGuid = tx;
            }
            if (name == "updatesequencenumber") {
                resource.updateSequenceNum = intValue();
            }
            if (name == "active") {
                resource.active =  booleanValue();
            }
            if (name == "mime") {
                resource.mime = textValue();
            }
            if (name == "duration") {
                resource.duration = shortValue();
            }
            if (name == "height") {
                resource.height = shortValue();
            }
            if (name == "width") {
                resource.width = shortValue();
            }
//            if (name == "dirty")
//                isDirty = booleanValue();
            if (name == "data") {
                Data data;
                resource.data = data;
                processData("Data", resource.data);
            }
            if (name == "alternatedata") {
                processData("AlternateData", resource.data);
            }
            if (name == "recognitiondata") {
                processData("RecognitionData", resource.recognition);
            }
            if (name == "noteresourceattributes") {
                processResourceAttributes(resource.attributes);
            }
        }
        reader->readNext();
        QString endName = reader->name().toString().toLower();
        if (endName == "noteresource" && reader->isEndElement())
            atEnd = true;
    }
}
Ejemplo n.º 30
0
void ItemsManagerWorker::OnTabReceived(int request_id) {
    if (!replies_.count(request_id)) {
        QLOG_WARN() << "Received a reply for request" << request_id << "that was not requested.";
        return;
    }

    ItemsReply reply = replies_[request_id];
    QLOG_DEBUG() << "Received a reply for" << reply.request.location.GetHeader().c_str();
    QByteArray bytes = reply.network_reply->readAll();
    rapidjson::Document doc;
    doc.Parse(bytes.constData());

    bool error = false;
    if (!doc.IsObject()) {
        QLOG_WARN() << request_id << "got a non-object response";
        error = true;
    } else if (doc.HasMember("error")) {
        // this can happen if user is browsing stash in background and we can't know about it
        QLOG_WARN() << request_id << "got 'error' instead of stash tab contents";
        error = true;
    }

    // re-queue a failed request
    if (error)
        QueueRequest(reply.request.network_request, reply.request.location);

    ++requests_completed_;

    if (!error)
        ++total_completed_;

    bool throttled = false;
    if (requests_completed_ == requests_needed_ && queue_.size() > 0) {
        throttled = true;
        QLOG_DEBUG() << "Sleeping one minute to prevent throttling.";
        QTimer::singleShot(kThrottleSleep * 1000, this, SLOT(FetchItems()));
    }
    CurrentStatusUpdate status = CurrentStatusUpdate();
    status.state = throttled ? ProgramState::ItemsPaused : ProgramState::ItemsReceive;
    status.progress = total_completed_;
    status.total = total_needed_;
    if (total_completed_ == total_needed_)
        status.state = ProgramState::ItemsCompleted;
    emit StatusUpdate(status);

    if (error)
        return;

    ParseItems(&doc["items"], reply.request.location, doc.GetAllocator());

    if (total_completed_ == total_needed_) {
        // all requests completed
        emit ItemsRefreshed(items_, tabs_, false);

        // since we build items_as_string_ in a hackish way inside ParseItems last character will either be
        // ' ' when no items were parsed or ',' when at least one item is parsed, and the first character is '['
        items_as_string_[items_as_string_.size() - 1] = ']';

        // DataStore is thread safe so it's ok to call it here
        data_.Set("items", items_as_string_);
        data_.Set("tabs", tabs_as_string_);

        updating_ = false;
        QLOG_DEBUG() << "Finished updating stash.";

        // if we're at the verge of getting throttled, sleep so we don't
        if (requests_completed_ == kThrottleRequests)
            QTimer::singleShot(kThrottleSleep, this, SLOT(PreserveSelectedCharacter()));
        else
            PreserveSelectedCharacter();
    }

    reply.network_reply->deleteLater();
}