void CommandHandler::processCommand(const Command &command) const
{
    QWebEngineView *webView = ElectricWebView::instance()->webView();

    if (command.name() == "load") {
        if (command.arguments().isEmpty())
            webView->load(QUrl("about:blank"));
        else
            webView->load(QUrl(command.arguments().first()));
    } else if (command.name() == "stop") {
        webView->stop();
    } else if (command.name() == "reload") {
        webView->reload();
    } else if (command.name() == "back") {
        webView->back();
    } else if (command.name() == "forward") {
        webView->forward();
    } else if (command.name() == "open") {
        QString mode = command.arguments().value(0);

        if (mode == "maximized") {
            webView->showMaximized();
        } else if (mode == "fullscreen") {
            webView->setGeometry(qApp->desktop()->screenGeometry());
            webView->showFullScreen();
        }
    } else if (command.name() == "close") {
        webView->close();
    } else if (command.name() == "current_url") {
        command.sendResponse(webView->url().toString().toLocal8Bit());
    } else if (command.name() == "set_html") {
        QString type = command.arguments().value(0);
        QString value = command.arguments().mid(1, -1).join(' ');

        if (type == "string") {
            webView->page()->setHtml(value.toLocal8Bit());
        } else if (type == "file") {
            QFile file(value);
            file.open(QFile::ReadOnly);

            webView->page()->setHtml(file.readAll());
        }
    } else if (command.name() == "get_html") {
        QString format = command.arguments().value(0);

        QEventLoop loop;

        if (format == "html") {
            webView->page()->toHtml([&command, &loop](const QString &html) {
                if (!command.client().isNull()) {
                    command.sendResponse(QUrl::toPercentEncoding(html));

                    if (command.isGetter())
                        command.client()->close();
                }
                loop.quit();
            });
        } else if (format == "text") {
            webView->page()->toPlainText([&command, &loop](const QString &text) {
                if (!command.client().isNull()) {
                    command.sendResponse(QUrl::toPercentEncoding(text));

                    if (command.isGetter())
                        command.client()->close();
                }
                loop.quit();
            });
        } else {
            return;
        }

        loop.exec();
    } else if (command.name() == "current_title") {
        command.sendResponse(webView->title().toLocal8Bit());
    } else if (command.name() == "screenshot") {
        processScreenshotCommand(command);
    } else if (command.name() == "subscribe") {
        QString eventName = command.arguments().value(0);
        QStringList events = QStringList()
                << "title_changed"
                << "url_changed"
                << "load_started"
                << "load_finished"
                << "user_activity"
                << "info_message_raised"
                << "warning_message_raised"
                << "error_message_raised"
                << "feature_permission_requested";

        if (events.contains(eventName)) {
            Event event(command);
            event.setName(eventName);

            ElectricWebView::instance()->eventManager()->subscribe(event);
        }
    } else if (command.name() == "exec_js") {
        processJavaScriptCommand(command);
    } else if (command.name() == "inject_js") {
        QMap<QString, QWebEngineScript::ScriptWorldId> worlds;
        worlds["main"] = QWebEngineScript::MainWorld;
        worlds["application"] = QWebEngineScript::ApplicationWorld;
        worlds["user"] = QWebEngineScript::UserWorld;

        QMap<QString, QWebEngineScript::InjectionPoint> injectionPoints;
        injectionPoints["document_creation"] = QWebEngineScript::DocumentCreation;
        injectionPoints["document_ready"] = QWebEngineScript::DocumentReady;
        injectionPoints["deferred"] = QWebEngineScript::Deferred;

        QWebEngineScript::ScriptWorldId world = worlds[command.arguments().value(0)];
        QWebEngineScript::InjectionPoint injectionPoint = injectionPoints[command.arguments().value(1)];

        QWebEngineScript script;
        script.setWorldId(world);
        script.setInjectionPoint(injectionPoint);

        QString source = command.arguments().value(2);
        QString value = command.arguments().mid(3, -1).join(' ');

        if (source == "string") {
            script.setSourceCode(value);
        } else if (source == "file") {
            QFile file(value);
            file.open(QFile::ReadOnly);

            script.setSourceCode(file.readAll());
        }

        ElectricWebView::instance()->webView()->page()->scripts().insert(script);
    } else if (command.name() == "idle_time") {
        command.sendResponse(QString("%1").arg(ElectricWebView::instance()->inputEventFilter()->idle()).toLocal8Bit());
    } else if (command.name() == "block_user_activity") {
        bool block = QVariant(command.arguments().value(0)).toBool();
        ElectricWebView::instance()->inputEventFilter()->setBlock(block);
    } else if (command.name() == "exec_cmd") {
        bool sync = command.arguments().value(0) == "sync";

        if (sync) {
            QProcess *process = new QProcess;
            process->start(command.arguments().mid(1, -1).join(' '));
            process->waitForFinished(-1);
            command.sendResponse(QUrl::toPercentEncoding(process->readAllStandardOutput()));
        } else {
            QProcess::startDetached(command.arguments().mid(1, -1).join(' '));
        }
    } else if (command.name() == "accept_feature_request" || command.name() == "reject_feature_request") {
        QMap<QString, QWebEnginePage::Feature> features;
        features["geolocation"] = QWebEnginePage::Geolocation;
        features["audio_capture"] = QWebEnginePage::MediaAudioCapture;
        features["video_capture"] = QWebEnginePage::MediaVideoCapture;
        features["audio_video_capture"] = QWebEnginePage::MediaAudioVideoCapture;
        features["mouse_lock"] = QWebEnginePage::MouseLock;

        QUrl securityOrigin(command.arguments().value(1));
        QWebEnginePage::Feature feature = features[command.arguments().value(0)];
        QWebEnginePage::PermissionPolicy policy;

        if (command.name() == "accept_feature_request")
            policy = QWebEnginePage::PermissionGrantedByUser;
        else
            policy = QWebEnginePage::PermissionDeniedByUser;

        ElectricWebView::instance()->webView()->page()->setFeaturePermission(securityOrigin, feature, policy);
    } else if (command.name() == "quit") {
        int exitCode = command.arguments().value(0).toInt();
        qApp->exit(exitCode);
    }
}
Example #2
2
void ConfigDialog::resetComboBoxVoAoItem(const ConfigData::Data& data)
{
    // 使用出来るドライバ項目を取得、初期化する
    QRegExp rx("^\t(.+)\t");
    QProcess p;

    QString mplayerPath;
    if( data.useMplayerPath )
        mplayerPath = data.mplayerPath;
    else
        mplayerPath = "mplayer";

    _comboBoxVo->clear();
    _comboBoxVo->addItem(tr("指定無し"), "");
    _comboBoxVoClipping->clear();
    _comboBoxVoClipping->addItem(tr("指定無し"), "");
    p.start(mplayerPath, QStringList() << "-vo" << "help");
    if( p.waitForFinished() ) {
        QStringList out = QString(p.readAllStandardOutput()).split("\n");

        for(int i=0; i < out.size(); ++i) {
            if( rx.indexIn(out[i]) != -1 ) {
                _comboBoxVo->addItem(rx.cap(1), rx.cap(1));
                _comboBoxVoClipping->addItem(rx.cap(1), rx.cap(1));
            }
        }
    }

    _comboBoxAo->clear();
    _comboBoxAo->addItem(tr("指定無し"), "");
    p.start(mplayerPath, QStringList() << "-ao" << "help");
    if( p.waitForFinished() ) {
        QStringList out = QString(p.readAllStandardOutput()).split("\n");

        for(int i=0; i < out.size(); ++i) {
            if( rx.indexIn(out[i]) != -1 )
                _comboBoxAo->addItem(rx.cap(1), rx.cap(1));
        }
    }

    // 項目を選択する
    int index;
    index = _comboBoxVo->findData(data.voName);
    if( index < 0 ) {
        _comboBoxVo->addItem(data.voName + tr("(使用不可)"), data.voName);
        index = _comboBoxVo->count() - 1;
    }
    _comboBoxVo->setCurrentIndex(index);

    index = _comboBoxVoClipping->findData(data.voNameForClipping);
    if( index < 0 ) {
        _comboBoxVoClipping->addItem(data.voNameForClipping + tr("(使用不可)"), data.voNameForClipping);
        index = _comboBoxVoClipping->count() - 1;
    }
    _comboBoxVoClipping->setCurrentIndex(index);

    index = _comboBoxAo->findData(data.aoName);
    if( index < 0 ) {
        _comboBoxAo->addItem(data.aoName + tr("(使用不可)"), data.aoName);
        index = _comboBoxAo->count() - 1;
    }
    _comboBoxAo->setCurrentIndex(index);
}
Example #3
0
void Area::saveEdit(int del){

    //temporary file for the text edition

    QFile newph("temp.ph");

    newph.open(QIODevice::WriteOnly | QIODevice::Truncate);
    QTextStream flux(&newph);
    flux.setCodec("UTF-8");    

    QString *file = new QString("temp.ph");
    QString fileXML("tempXML.xml");
    std::string phFile = file->toStdString();

    try{

        //Save new text into new file
        if(this->textArea->toPlainText().isEmpty()){

            throw textAreaEmpty_exception();
        }

        flux << this->textArea->toPlainText() << endl;

        newph.close();        

        if(del == 0){

            emit makeTempXML();
        }

        // render graph
        PHPtr myPHPtr = PHIO::parseFile(phFile);
        this->myArea->setPHPtr(myPHPtr);
        myPHPtr->render();
        PHScenePtr scene = myPHPtr->getGraphicsScene();
        this->myArea->setScene(&*scene);

        // delete the current sortsTree and groupsTree
        this->treeArea->sortsTree->clear();
        //this->treeArea->groupsTree->clear();
        // set the pointer of the treeArea
        this->treeArea->myPHPtr = myPHPtr;
        //set the pointer of the treeArea
        this->treeArea->myArea = this->myArea;
        // build the tree in the treeArea
        this->treeArea->build();

        this->indicatorEdit->setVisible(false);       
        this->saveTextEdit->setDefault(false);
        this->textArea->incrementeNberTextChange();        
        this->typeOfCancel = 0;
        this->saveTextEdit->setEnabled(false);        
        this->textArea->setNberEdit(0);
        this->cancelTextEdit->setShortcut(QKeySequence());

        this->setOldText();

        newph.remove();

        this->mainWindow->importXMLMetadata(fileXML);
    }
    catch(textAreaEmpty_exception & e){

        QMessageBox::critical(this, "Error !", "You cannot update from an empty text area !");
    }
    catch(ph_parse_error & argh){

        //Catch a parsing error !
        //Put the exception into a QMessageBox critical

        QString phc = "phc";
        QStringList args;
        args << "-l" << "dump" << "-i" << QString::fromUtf8(phFile.c_str()) << "--no-debug";
        QProcess *phcProcess = new QProcess();
        phcProcess->start(phc, args);
        if (!phcProcess->waitForStarted())
            throw pint_program_not_found() << file_info("phc");

        phcProcess->readChannel();

        // read result
        QByteArray stderr;
        QByteArray stdout;
        while (!phcProcess->waitForFinished()) {
            stderr += phcProcess->readAllStandardError();
            stdout += phcProcess->readAllStandardOutput();
        }
        stderr += phcProcess->readAllStandardError();
        stdout += phcProcess->readAllStandardOutput();
        delete phcProcess;

        //Use split function to only keep the line number

        QStringList list = QString(stderr).split('"');
        QStringList list2 = list[1].split(":");
        QStringList list3 = list2[0].split(" ");

        //One or more of your expressions are wrong !
        newph.remove();
        QMessageBox::critical(this, "Syntax error !", "One or more of your expressions are wrong !\nNear "+list3[0]+" "+list3[1]+" of dump");
        //return NULL;
    }
    catch(sort_not_found& sort){

        //Catch a error if the user delete a sort before associated actions !

        QMessageBox::critical(this, "Error !", "Delete the associated actions before the process !");
    }
}
Example #4
0
void DialogEngines::onAddEngine() {

    QString fileName = QFileDialog::getOpenFileName(this,
        tr("Add UCI Engine"), this->lastAddedEnginePath, tr("UCI Engines (*)"));

    fileName = QString('"').append(fileName).append('"');

    QDir d = QFileInfo(fileName).absoluteDir();
    this->lastAddedEnginePath = d.absolutePath();

    this->setEnabled(false);

    QProcess process;
    process.start(fileName,QIODevice::ReadWrite);
    // Wait for process to start
    if(!process.waitForStarted(500)) {
        // if process doesn't start, just ignore
    } else {
        process.write("uci\n");
        process.waitForBytesWritten();
        // give the engine 700 ms to respond to
        // the uci command
        this->delay(700);

        // read generated output
        QString output = QString("");
        // give another 50 ms until the engine outputs info
        process.waitForReadyRead(50) ;
        output.append(process.readAllStandardOutput());
        // look for engine id
        QString engine_name = QString("");
        QRegularExpression regExpEngineName = QRegularExpression("id\\sname\\s(\\w|\\s|\\S)+");
        QRegularExpressionMatch m_id = regExpEngineName.match(output);
        if(m_id.hasMatch()) {
            int len = m_id.capturedLength(0);
            engine_name = m_id.captured(0).mid(8,len-1).split("\n").at(0);
        }
        // attempt to quit the engine
        process.write("quit\n");
        process.waitForBytesWritten();
        process.waitForFinished(250);
        // if still running, kill it
        if(process.state()  == QProcess::Running) {
            // if engine doesn't response, it could mean that
            // this is no engine _or_ (as in the case of e.g arasanx-64
            // takes an extremely long time to respond to "quit".
            // kill it ...
            process.kill();
            process.waitForFinished();
        }
        // ... however even if we had to kill the engine, as
        // long as the engine provided us with a proper name, we
        // assume that we found a real uci engine
        if(!engine_name.isEmpty()) {
            Engine new_engine = Engine();
            new_engine.setName(engine_name);
            new_engine.setPath(fileName);
            this->engines.append(new_engine);
            QListWidgetItem *item = new QListWidgetItem(new_engine.getName());
            this->lstEngines->addItem(item);
            item->setSelected(true);
            this->update();
        }
    }
    this->setEnabled(true);

}
Example #5
0
void KbFirmware::processDownload(QNetworkReply* reply){
    if(reply->error() != QNetworkReply::NoError)
        return;
    // Update last check
    lastCheck = lastFinished = QDateTime::currentMSecsSinceEpoch();
    QByteArray data = reply->readAll();
    // Don't do anything if this is the same as the last version downloaded
    QByteArray hash = QCryptographicHash::hash(data, QCryptographicHash::Sha256);
    if(hash == fwTableHash)
        return;
    fwTableHash = hash;
    if(hasGPG == UNKNOWN){
        // Check for a GPG installation
        QProcess gpg;
        gpg.start("gpg", QStringList("--version"));
        gpg.waitForFinished();
        if(gpg.error() == QProcess::FailedToStart)
            // No GPG install
            hasGPG = NO;
        else {
            QString output = QString::fromUtf8(gpg.readAll());
            // Must support RSA keys and SHA256
            if(output.contains("RSA", Qt::CaseInsensitive) && output.contains("SHA256", Qt::CaseInsensitive))
                hasGPG = YES;
            else
                hasGPG = NO;
        }
        if(!hasGPG)
            qDebug() << "No GPG detected, signature verification disabled";
    }
    if(hasGPG){
        // If GPG is available, check the signature on the file before proceeding.
        QDir tmp = QDir::temp();
        // Save file to a temporary path. Include PID to avoid conflicts
        qint64 pid = QCoreApplication::applicationPid();
        QString fwPath = tmp.absoluteFilePath(QString("ckb-%1-firmware").arg(pid));
        QFile firmware(fwPath);
        if(!firmware.open(QIODevice::WriteOnly)
                || firmware.write(data) != data.length()){
            qDebug() << "Failed to write firmware file to temporary location, aborting firmware check";
            return;
        }
        firmware.close();
        // Write GPG key
        QString keyPath = tmp.absoluteFilePath(QString("ckb-%1-key.gpg").arg(pid));
        if(!QFile::copy(":/bin/msckey.gpg", keyPath)){
            firmware.remove();
            qDebug() << "Failed to write GPG key to temporary location, aborting firmware check";
            return;
        }
        // Check signature
        QProcess gpg;
        gpg.start("gpg", QStringList("--no-default-keyring") << "--keyring" << keyPath << "--verify" << fwPath);
        gpg.waitForFinished();
        // Clean up temp files
        tmp.remove(fwPath);
        tmp.remove(keyPath);
        if(gpg.error() != QProcess::UnknownError || gpg.exitCode() != 0){
            qDebug() << "GPG couldn't verify firmware signature:";
            qDebug() << gpg.readAllStandardOutput();
            qDebug() << gpg.readAllStandardError();
            return;
        }
        // Signature good, proceed to update database
    }
    fwTable.clear();
    QStringList lines = QString::fromUtf8(data).split("\n");
    bool scan = false;
    foreach(QString line, lines){
        // Collapse whitespace
        line.replace(QRegExp("\\s+"), " ").remove(QRegExp("^\\s")).remove(QRegExp("\\s$"));
        // Skip empty or commented-out lines
        if(line.length() == 0 || line.at(0) == '#')
            continue;
        // Don't read anything until the entries begin and don't read anything after they end
        if(!scan){
            if(line == "!BEGIN FW ENTRIES")
                scan = true;
            else
                continue;
        }
        if(line == "!END FW ENTRIES")
            break;
        QStringList components = line.split(" ");
        if(components.length() != 7)
            continue;
        // "VENDOR-PRODUCT"
        QString device = components[0].toUpper() + "-" + components[1].toUpper();
        FW fw;
        fw.fwVersion = components[2].toFloat();                             // Firmware blob version
        fw.url = QUrl::fromPercentEncoding(components[3].toLatin1());       // URL to zip file
        fw.ckbVersion = PARSE_CKB_VERSION(components[4]);                   // Minimum ckb version
        fw.fileName = QUrl::fromPercentEncoding(components[5].toLatin1());  // Name of file inside zip
        fw.hash = QByteArray::fromHex(components[6].toLatin1());            // SHA256 of file inside zip
        // Update entry
        fwTable[device] = fw;
    }
DUTIL_USE_NAMESPACE

bool setAllMonitorsExtend()
{
    QProcess *checkMons = new QProcess;
    checkMons->start("xrandr");
    checkMons->waitForFinished(1000);

    QString primaryMonitor;
    QStringList otherMonitors;

    const QString result = checkMons->readAllStandardOutput();
    const QStringList &infoList = result.split('\n');
    bool foundMonitor = false;
    for (const QString &info : infoList)
    {
        const QStringList details = info.split(' ');

        if (details.count() < 3 || details.at(1) != "connected")
            continue;

        qDebug() << "info: " << info;
        qDebug() << "found monitor: " << details.first();
        foundMonitor = true;
        if (details.at(2) == "primary")
            primaryMonitor = details.first();
        else
            otherMonitors.append(details.first());
    }

    if (!foundMonitor) {
        qCritical() << "can not find any monitor" << "retray in 15 second...";
        return foundMonitor;
    }

    // set other monitors
    QString lastMonitor = primaryMonitor;
    if (lastMonitor.isEmpty())
        lastMonitor = otherMonitors.first();

    // call enable xrandr first
    QProcess enableMonitor;
    enableMonitor.start("xrandr --auto");
    bool ret = enableMonitor.waitForFinished(-1);
    qDebug()<< "enable monitor" <<ret<<enableMonitor.readAll();

    for (const QString &m : otherMonitors)
    {
        if (m == lastMonitor)
            continue;

        QProcess *setting = new QProcess;
        QString cmd = QString("xrandr --output %1 --right-of %2 --auto").arg(m).arg(lastMonitor);

        qDebug() << "exec: " << cmd;

        setting->start(cmd);
        bool result = setting->waitForFinished(1000);
        qDebug() << "finished: " << result;
        setting->deleteLater();
    }

    checkMons->deleteLater();
    return foundMonitor;
}
Example #7
0
   QList<DiskDevice *> enumerateDevice()
   {
       QList<DiskDevice *> devices;
       utils::writeLog("Enumerating imageable devices for OSX");
       QProcess process;
       QStringList lines;
       process.setEnvironment(QStringList() << "LANG=C");
       process.start("/usr/sbin/diskutil", QStringList() << "list", QIODevice::ReadWrite | QIODevice::Text);
       if (! process.waitForFinished())
           utils::writeLog("Could not execute diskutil to enumerate devices");
       else
       {
           QTextStream stdoutStream(process.readAllStandardOutput());
           while (true)
           {
               QString line = stdoutStream.readLine().simplified(); /* Remove trailing and leading ws */
               if (line.isNull())
                   break;
               /* The line holding the device is the only line always starting with 0: */
               else if (line.startsWith("0:"))
               {
                   lines << line;
               }
           }
           for (int i = 0; i < lines.count(); i++)
           {
               QString line = lines.at(i);
               QStringList deviceAttr = line.split(" ");

               /*
                * THE FOLLOWING LIST CHANGES IF THE DISK WAS NOT INITIALISED
                * In that case, <partition schema name> is missing and the
                * index for the following elements has to be adressed by n-1
                * content is now:
                * [0] 0:
                * [1] <partition scheme name>
                * [2] <total_size>
                * [3] <size_unit>
                * [4] device name (disk0, disk1, etc)
                */
               QString deviceSpace;
               QString devicePath("/dev/");
               if (deviceAttr.at(1).startsWith("*"))
               {
                   /* partition schema name was missing - uninitialised disk */
                   deviceSpace = deviceAttr.at(1) + " " + deviceAttr.at(2);
                   devicePath += (new QString(deviceAttr.at(3)))->replace(0, 1, "rd");
               } else
               {
                   deviceSpace = deviceAttr.at(2) + " " + deviceAttr.at(3);
                   QString deviceName(deviceAttr.at(4));
                   /* make the disk become a rdisk */
                   devicePath += deviceName.replace(0, 1, "rd");
               }

               deviceSpace.remove("*");
               DiskDevice *nd = new DiskDevice(i, devicePath, deviceSpace);
               nd = addAdditionalInfo(nd);

               if (nd->getIsWritable())
                   devices.append(nd);
           }
       }
       return devices;
   }
Example #8
0
bool SSHConnectionCLI::executeSCPFrom(const QString& source,
                                      const QString& dest,
                                      const QStringList& args,
                                      QString* stdout_str, QString* stderr_str,
                                      int* ec)
{
  QProcess proc;

  // Start with input args
  QStringList fullArgs(args);

  // Add port number
  fullArgs << "-P" << QString::number(m_port);

  // Add source
  fullArgs << QString("%1%2%3:%4")
                .arg(m_user)
                .arg(m_user.isEmpty() ? "" : "@")
                .arg(m_host)
                .arg(source);

  // Add destination
  fullArgs << dest;

  proc.start("scp", fullArgs);
  int timeout_ms = 60000; // one minute

  if (!proc.waitForStarted(timeout_ms)) {
    qWarning() << QString("Failed to start scp command with args \"%1\" "
                          "after %2 seconds.")
                    .arg(fullArgs.join(","))
                    .arg(timeout_ms / 1000);
    return false;
  }

  proc.closeWriteChannel();
  if (!proc.waitForFinished(timeout_ms)) {
    qWarning() << QString("scp command with args \"%1\" failed to finish "
                          "within %2 seconds.")
                    .arg(fullArgs.join(","))
                    .arg(timeout_ms / 1000);
    return false;
  }

  if (proc.exitCode() != 0) {
    qWarning() << QString("scp command with args \"%1\" failed with an exit "
                          "code of %2.")
                    .arg(fullArgs.join(","))
                    .arg(proc.exitCode())
               << "\nstdout:\n"
               << QString(proc.readAllStandardOutput()) << "\nstderr:\n"
               << QString(proc.readAllStandardError());
    return false;
  }

  if (stdout_str != nullptr)
    *stdout_str = QString(proc.readAllStandardOutput());
  if (stderr_str != nullptr)
    *stderr_str = QString(proc.readAllStandardError());
  if (ec != nullptr)
    *ec = proc.exitCode();

  proc.close();

  return true;
}
Example #9
0
// Index any PDFs that are attached.  Basically it turns the PDF into text and adds it the same
// way as a note's body
void IndexRunner::indexAttachment(qint32 lid, Resource &r) {
    if (!officeFound)
        return;
    QLOG_DEBUG() << "indexing attachment to note " << lid;
    if (!keepRunning || pauseIndexing) {
        indexTimer->start();
        return;
    }
    ResourceTable rtable(&db->conn);
    qint32 reslid = rtable.getLid(r.guid);
    if (lid <= 0) {
        indexTimer->start();
        return;
    }
    QLOG_DEBUG() << "Resource " << reslid;
    QString extension = "";
    ResourceAttributes attributes;
    if (r.attributes.isSet())
        attributes = r.attributes;
    if (attributes.fileName.isSet()) {
        extension = attributes.fileName;
        int i = extension.indexOf(".");
        extension = extension.mid(i);
    }
    if (extension != ".doc"  && extension != ".xls"  && extension != ".ppt" &&
        extension != ".docx" && extension != ".xlsx" && extension != ".pptx" &&
        extension != ".pps"  && extension != ".pdf"  && extension != ".odt"  &&
        extension != ".odf"  && extension != ".ott"  && extension != ".odm"  &&
        extension != ".html" && extension != ".txt"  && extension != ".oth"  &&
        extension != ".ods"  && extension != ".ots"  && extension != ".odg"  &&
        extension != ".otg"  && extension != ".odp"  && extension != ".otp"  &&
        extension != ".odb"  && extension != ".oxt"  && extension != ".htm"  &&
        extension != ".docm")
                return;

    QString file = global.fileManager.getDbaDirPath() + QString::number(reslid) +extension;
    QFile dataFile(file);
    if (!dataFile.exists()) {
        QDir dir(global.fileManager.getDbaDirPath());
        QStringList filterList;
        filterList.append(QString::number(lid)+".*");
        QStringList list= dir.entryList(filterList, QDir::Files);
        if (list.size() > 0) {
            file = global.fileManager.getDbaDirPath()+list[0];
        }
    }

    QString outDir = global.fileManager.getTmpDirPath();

    QProcess sofficeProcess;
    QString cmd = "soffice --headless --convert-to txt:\"Text\" --outdir "
                    +outDir + " "
                    +file;

    sofficeProcess.start(cmd,
                         QIODevice::ReadWrite|QIODevice::Unbuffered);

    QLOG_DEBUG() << "Starting soffice ";
    sofficeProcess.waitForStarted();
    QLOG_DEBUG() << "Waiting for completion";
    sofficeProcess.waitForFinished();
    int rc = sofficeProcess.exitCode();
    QLOG_DEBUG() << "soffice Errors:" << sofficeProcess.readAllStandardError();
    QLOG_DEBUG() << "soffice Output:" << sofficeProcess.readAllStandardOutput();
    QLOG_DEBUG() << "return code:" << rc;
    if (rc == 255) {
        QLOG_ERROR() << "soffice not found.  Disabling attachment indexing.";
        this->officeFound = false;
        return;
    }
    QFile txtFile(outDir+QString::number(reslid) +".txt");
    if (txtFile.open(QIODevice::ReadOnly)) {
        QString text;
        text = txtFile.readAll();
        NSqlQuery sql(db->conn);
        sql.prepare("Insert into SearchIndex (lid, weight, source, content) values (:lid, :weight, 'recognition', :content)");
        sql.bindValue(":lid", lid);
        sql.bindValue(":weight", 100);
        sql.bindValue(":content", text);
        QLOG_DEBUG() << "Adding note resource to index DB";
        sql.exec();
        txtFile.close();
    }
    QDir dir;
    dir.remove(outDir+QString::number(reslid) +".txt");
}
Example #10
0
void NetworkMan::DevSelectionChanged()
{
   int sel = listNetDev->currentRow();
    
   if ( sel != -1 ) {
    
   pushConfigure->setEnabled(TRUE);

	
   // Check to see if the network tray icon is enabled or not
   QString filename = PREFIX + "/share/pcbsd/xstartup/tray-" + Devs[sel] + ".sh";


   // First run a check to if we need to enable or disable the checkbox
   if ( QFile::exists( filename ) )
   {
     checkSysTray->setChecked(TRUE);
   } else {
     checkSysTray->setChecked(FALSE);
   }
    
    
   DevsIP[sel] = getIpForIdent(Devs[sel]);
   DevsStatus[sel] = getStatusForIdent(Devs[sel]);
   DevsNetmask[sel] = getNetmaskForIdent(Devs[sel]);
    
   textStatusLabel1->setText(tr("Address:"));	
   textStatus1->setText(tr("IP: ") + DevsIP[sel] + " / " + tr("Netmask: ") + DevsNetmask[sel]);

   if ( getTypeForIdent(Devs[sel]) == "Wireless" )
   {
     checkSysTray->setVisible(FALSE);
     textStatusLabel2->setText(tr("SSID:"));
     QString SSID = ""; 
     QString tmp;
       
     QProcess *getIfProc = new QProcess();
     getIfProc->start(IFCONFIG, QStringList() << Devs[sel]);
     if (getIfProc->waitForFinished(2000)) {
       tmp = getIfProc->readAllStandardOutput().simplified();
     }

     getIfProc->kill();
     delete getIfProc;

     if (tmp != "" && tmp.indexOf("ssid ") != -1){
    	SSID = tmp.remove(0, tmp.indexOf("ssid ") + 5);
    	SSID.truncate(tmp.indexOf("channel") - 1 );
     }

     textStatus2->setText(SSID);
   } else {
     if ( ! InstallerMode )
       checkSysTray->setVisible(TRUE);
     textStatusLabel2->setText(tr("MAC Address:"));
     textStatus2->setText(DevsMAC[sel]);
   }
   
   textStatusLabel3->setText(tr("Status:"));
   textStatus3->setText(DevsStatus[sel]);
    
  }
    
}
void EngineSync::subProcessStandardOutput()
{
	QProcess *process = qobject_cast<QProcess *>(this->sender());
	QByteArray data = process->readAllStandardOutput();
	qDebug() << QString(data);
}
bool DFInstanceLinux::find_running_copy(bool connect_anyway) {
    // find PID of DF
    TRACE << "attempting to find running copy of DF by executable name";
    QProcess *proc = new QProcess(this);
    QStringList args;
    args << "dwarfort.exe"; // 0.31.04 and earlier
    args << "Dwarf_Fortress"; // 0.31.05+
    proc->start("pidof", args);
    proc->waitForFinished(1000);
    if (proc->exitCode() == 0) { //found it
        QByteArray out = proc->readAllStandardOutput();
        QStringList str_pids = QString(out).split(" ");
        str_pids.sort();
        if(str_pids.count() > 1){
            m_pid = QInputDialog::getItem(0, tr("Warning"),tr("Multiple Dwarf Fortress processes found, please choose the process to use."),str_pids,str_pids.count()-1,false).toInt();
        }else{
            m_pid = str_pids.at(0).toInt();
        }

        m_memory_file.setFileName(QString("/proc/%1/mem").arg(m_pid));

        TRACE << "USING PID:" << m_pid;
    } else {
        QMessageBox::warning(0, tr("Warning"),
                             tr("Unable to locate a running copy of Dwarf "
                                "Fortress, are you sure it's running?"));
        LOGW << "can't find running copy";
        m_is_ok = false;
        return m_is_ok;
    }

    m_inject_addr = unsigned(-1);
    m_alloc_start = 0;
    m_alloc_end = 0;

    map_virtual_memory();

    //qDebug() << "LOWEST ADDR:" << hex << lowest_addr;


    //DUMP LIST OF MEMORY RANGES
    /*
    QPair<uint, uint> tmp_pair;
    foreach(tmp_pair, m_regions) {
        LOGD << "RANGE start:" << hex << tmp_pair.first << "end:" << tmp_pair.second;
    }*/

    VIRTADDR m_base_addr = read_addr(m_lowest_address + 0x18);
    LOGD << "base_addr:" << m_base_addr << "HEX" << hex << m_base_addr;
    m_is_ok = m_base_addr > 0;

    uint checksum = calculate_checksum();
    LOGD << "DF's checksum is" << hexify(checksum);
    if (m_is_ok) {
        m_layout = get_memory_layout(hexify(checksum).toLower(), !connect_anyway);
    }

    //Get dwarf fortress directory
    m_df_dir = QDir(QFileInfo(QString("/proc/%1/cwd").arg(m_pid)).symLinkTarget());
    LOGI << "Dwarf fortress path:" << m_df_dir.absolutePath();

    return m_is_ok || connect_anyway;
}
int main(int argc, char** argv)
{
  QApplication myApp(argc, argv);
  myApp.setOrganizationName("CommonTK");
  myApp.setApplicationName("CommandLineModuleExplorer");

  ctkCommandLineParser cmdLineParser;
  cmdLineParser.setArgumentPrefix("--", "-");
  cmdLineParser.setStrictModeEnabled(true);

  cmdLineParser.addArgument("module", "", QVariant::String, "Path to a CLI module (executable)");
  //cmdLineParser.addArgument("module-xml", "", QVariant::String, "Path to a CLI XML description.");

  cmdLineParser.addArgument("validate-module", "", QVariant::String, "Path to a CLI module");
  cmdLineParser.addArgument("validate-xml", "", QVariant::String, "Path to a CLI XML description.");
  cmdLineParser.addArgument("verbose", "v", QVariant::Bool, "Be verbose.");
  cmdLineParser.addArgument("help", "h", QVariant::Bool, "Print this help text.");

  bool parseOkay = false;
  QHash<QString, QVariant> args = cmdLineParser.parseArguments(argc, argv, &parseOkay);

  QTextStream out(stdout, QIODevice::WriteOnly);

  if(!parseOkay)
  {
    out << "Error parsing command line arguments: " << cmdLineParser.errorString() << '\n';
    return EXIT_FAILURE;
  }

  if (args.contains("help"))
  {
    out << "Usage:\n" << cmdLineParser.helpText();
    out.flush();
    return EXIT_SUCCESS;
  }

  if (args.contains("validate-module"))
  {
    if (args.contains("validate-xml"))
    {
      out << "Ignoring \"validate-xml\" option.\n\n";
    }

    QString input = args["validate-module"].toString();
    if (!QFile::exists(input))
    {
      qCritical() << "Module does not exist:" << input;
      return EXIT_FAILURE;
    }

    QProcess process;
    process.setReadChannel(QProcess::StandardOutput);
    process.start(input, QStringList("--xml"));

    if (!process.waitForFinished() || process.exitStatus() == QProcess::CrashExit ||
        process.error() != QProcess::UnknownError)
    {
      qWarning() << "The executable at" << input << "could not be started:" << process.errorString();
      return EXIT_FAILURE;
    }

    process.waitForReadyRead();
    QByteArray xml = process.readAllStandardOutput();

    if (args.contains("verbose"))
    {
      qDebug() << xml;
    }

    // validate the outputted xml description
    QBuffer xmlInput(&xml);
    xmlInput.open(QIODevice::ReadOnly);

    ctkCmdLineModuleXmlValidator validator(&xmlInput);
    if (!validator.validateInput())
    {
      qCritical() << validator.errorString();
      return EXIT_FAILURE;
    }

    return EXIT_SUCCESS;
  }
  else if (args.contains("validate-xml"))
  {
    QFile input(args["validate-xml"].toString());
    if (!input.exists())
    {
      qCritical() << "XML description does not exist:" << input.fileName();
      return EXIT_FAILURE;
    }
    input.open(QIODevice::ReadOnly);

    ctkCmdLineModuleXmlValidator validator(&input);
    if (!validator.validateInput())
    {
      qCritical() << validator.errorString();
      return EXIT_FAILURE;
    }

    return EXIT_SUCCESS;
  }


  //ctkCmdLineModuleDescription* descr = ctkCmdLineModuleDescription::parse(&input);

  ctkCLModuleExplorerMainWindow mainWindow;

  if (args.contains("module"))
  {
    mainWindow.addModule(args["module"].toString());
  }

  mainWindow.show();

  return myApp.exec();
}
Example #14
0
int main(int argc, char **argv)
{
    if (argc < 3) {
        qFatal("Usage: ./genversion <git_root> <target_file>");
        return 255;
    }

    QCoreApplication app(argc, argv);

    QString gitroot = app.arguments()[1];
    QString target = app.arguments()[2];
    QString basever, protover, clientneeds, coreneeds, descrver, dirty;
    QString committish, commitdate;

    // check Git for information if present
    if (QFile::exists(gitroot + "/.git")) {
        // try to execute git-describe to get a version string
        QProcess git;
        git.setWorkingDirectory(gitroot);
#ifdef Q_OS_WIN
        git.start("cmd.exe", QStringList() << "/C" << "git" << "describe" << "--long");
#else
        git.start("git", QStringList() << "describe" << "--long");
#endif
        if (git.waitForFinished(10000)) {
            QString descr = git.readAllStandardOutput().trimmed();
            if (!descr.isEmpty() && !descr.contains("fatal")) {
                // seems we have a valid git describe string
                descrver = descr;
                // check if the workdir is dirty
#ifdef Q_OS_WIN
                git.start("cmd.exe", QStringList() << "/C" << "git" << "diff-index" << "--name-only" << "HEAD");
#else
                git.start("git", QStringList() << "diff-index" << "--name-only" << "HEAD");
#endif
                if (git.waitForFinished(10000)) {
                    if (!git.readAllStandardOutput().isEmpty()) dirty = "*";
                }
                // get a full committish
#ifdef Q_OS_WIN
                git.start("cmd.exe", QStringList() << "/C" << "git" << "rev-parse" << "HEAD");
#else
                git.start("git", QStringList() << "rev-parse" << "HEAD");
#endif
                if (git.waitForFinished(10000)) {
                    committish = git.readAllStandardOutput().trimmed();
                }
                // Now we do some replacement magic...
                //QRegExp rxCheckTag("(.*)-0-g[0-9a-f]+\n$");
                //QRegExp rxGittify("(.*)-(\\d+)-g([0-9a-f]+)\n$");
                //gitversion.replace(rxCheckTag, QString("\\1%1").arg(dirty));
                //gitversion.replace(rxGittify, QString("\\1:git-\\3+\\2%1").arg(dirty));
            }
        }
    }

    // parse version.inc
    QFile verfile(gitroot + "/version.inc");
    if (verfile.open(QIODevice::ReadOnly | QIODevice::Text)) {
        QString ver = verfile.readAll();

        QRegExp rxBasever("baseVersion\\s*=\\s*\"(.*)\";");
        if (rxBasever.indexIn(ver) >= 0)
            basever = rxBasever.cap(1);

        QRegExp rxProtover("protocolVersion\\s*=\\s*(\\d+)");
        if (rxProtover.indexIn(ver) >= 0)
            protover = rxProtover.cap(1);

        QRegExp rxClientneeds("clientNeedsProtocol\\s*=\\s*(\\d+)");
        if (rxClientneeds.indexIn(ver) >= 0)
            clientneeds = rxClientneeds.cap(1);

        QRegExp rxCoreneeds("coreNeedsProtocol\\s*=\\s*(\\d+)");
        if (rxCoreneeds.indexIn(ver) >= 0)
            coreneeds = rxCoreneeds.cap(1);

        if (committish.isEmpty()) {
            QRegExp rxCommit("distCommittish\\s*=\\s*([0-9a-f]+)");
            if (rxCommit.indexIn(ver) >= 0) committish = rxCommit.cap(1);
        }

        QRegExp rxTimestamp("distCommitDate\\s*=\\s*([0-9]+)");
        if (rxTimestamp.indexIn(ver) >= 0) commitdate = rxTimestamp.cap(1);
        verfile.close();
    }

    // generate the contents for version.gen
    QByteArray contents = QString("QString buildinfo = \"%1,%2,%3,%4,%5,%6,%7,%8\";\n")
                          .arg(basever, descrver, dirty, committish, commitdate, protover, clientneeds, coreneeds)
                          .toAscii();

    QFile gen(target);
    if (!gen.open(QIODevice::ReadWrite | QIODevice::Text)) {
        qFatal("%s", qPrintable(QString("Could not write %1!").arg(target)));
        return EXIT_FAILURE;
    }
    QByteArray oldContents = gen.readAll();
    if (oldContents != contents) { // only touch the file if something changed
        gen.seek(0);
        gen.resize(0);
        gen.write(contents);
        gen.waitForBytesWritten(10000);
    }
    gen.close();

    return EXIT_SUCCESS;
}
bool CommandLineExporter::executeCommand
(
    const QString& command,
    const QString& inputFilePath,
    const QString& textInput,
    const QString& outputFilePath,
    QString& stdoutOutput,
    QString& stderrOutput
)
{
    QProcess process;
    process.setReadChannel(QProcess::StandardOutput);

    QString expandedCommand = command + QString(" ");

    if (!outputFilePath.isNull() && !outputFilePath.isEmpty())
    {
        // Redirect stdout to the output file path if the path variable wasn't
        // set in the command string.
        //
        if (!expandedCommand.contains(OUTPUT_FILE_PATH_VAR))
        {
            process.setStandardOutputFile(outputFilePath);
        }
        else
        {
            // Surround file path with quotes in case there are spaces in the
            // path.
            //
            QString outputFilePathWithQuotes = QString('\"') +
                outputFilePath + '\"';
            expandedCommand.replace(OUTPUT_FILE_PATH_VAR, outputFilePathWithQuotes);
        }
    }

    if
    (
        this->getSmartTypographyEnabled() &&
        !this->smartTypographyOnArgument.isNull()
    )
    {
        expandedCommand.replace
        (
            SMART_TYPOGRAPHY_ARG,
            smartTypographyOnArgument
        );
    }
    else if
    (
        !this->getSmartTypographyEnabled() &&
        !this->smartTypographyOffArgument.isNull()
    )
    {
        expandedCommand.replace
        (
            SMART_TYPOGRAPHY_ARG,
            smartTypographyOffArgument
        );
    }

    if (!inputFilePath.isNull() && !inputFilePath.isEmpty())
    {
        process.setWorkingDirectory(QFileInfo(inputFilePath).dir().path());
    }

    process.start(expandedCommand);

    if (!process.waitForStarted())
    {
        return false;
    }
    else
    {
        if (!textInput.isNull() && !textInput.isEmpty())
        {
            process.write(textInput.toUtf8());
            process.closeWriteChannel();
        }

        if (!process.waitForFinished())
        {
            return false;
        }
        else
        {
            stdoutOutput = QString::fromUtf8(process.readAllStandardOutput().data());
            stderrOutput = QString::fromUtf8(process.readAllStandardError().data());
        }
    }

    return true;
}
Example #16
0
QHash<QString,QString> ConfigLists::getMidiInputDevices(QString module)
{
	// based on code by Steven Yi
	QHash<QString,QString> deviceList;
#ifdef CSOUND6
	CSOUND *cs = csoundCreate(NULL);
	csoundSetMIDIModule(cs, module.toLatin1().data());
	int i,newn, n = csoundGetMIDIDevList(cs,NULL,0);
	CS_MIDIDEVICE *devs = (CS_MIDIDEVICE *) malloc(n*sizeof(CS_MIDIDEVICE));
	newn = csoundGetMIDIDevList(cs,devs,0);
	if (newn != n) {
		qDebug() << "ConfigLists::getMidiInputDevices Device number changed";
		return deviceList;
	}
	for (i = 0; i < n; i++) {
//		qDebug() << devs[i].device_name;
		QString displayName = QString("%1 (%2)").arg(devs[i].device_name).arg(devs[i].interface_name);
		deviceList.insert(displayName, QString(devs[i].device_id));
	}
	free(devs);
    csoundDestroy(cs);
#else
	if (module == "none") {
		return deviceList;
	}
	if (module == "alsa") {
		QProcess amidi;
		amidi.start("amidi", QStringList() << "-l");
		if (!amidi.waitForFinished())
			return deviceList;

		QByteArray result = amidi.readAllStandardOutput();
		QString values = QString(result);
		QStringList st = values.split("\n");
		st.takeFirst(); // Remove first column lines
		for (int i = 0; i < st.size(); i++){
			QStringList parts = st[i].split(" ", QString::SkipEmptyParts);
			if (parts.size() > 0 && parts[0].contains("I")) {
				QString devname = parts[1]; // Devce name
				parts.takeFirst(); // Remove IO flags
				QString fullname = parts.join(" ") ; // Full name with description
				deviceList.insert(fullname, devname);
			}
		}
		deviceList.insert("All available devices ", "a");
	}
	else if (module == "virtual") {
		QString name = qApp->translate("Enabled", "Virtual MIDI keyboard Enabled");
		deviceList.insert(name, "0");
	}
	else { // if not alsa (i.e. winmm or portmidi)
		QFile file(":/test.csd");
		if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
			return deviceList;
		QString jackCSD = QString(file.readAll());
		QString tempText = jackCSD;
		tempText.replace("$SR", "441000");
		QTemporaryFile tempFile(QDir::tempPath() + QDir::separator() + "testcsdCsoundQtXXXXXX.csd");
		tempFile.open();
		QTextStream out(&tempFile);
		out << tempText;
		tempFile.close();
		tempFile.open();

		QStringList flags;
		QString rtMidiFlag = "-+rtmidi=" + module;
		flags << "-+msg_color=false" << rtMidiFlag << "-otest"  << "-n"  << "-M999" << tempFile.fileName();
		QStringList messages = runCsoundInternally(flags);

		QString startText, endText;
		if (module == "portmidi") {
			startText = "The available MIDI";
			endText = "*** PortMIDI";
		}
		else if (module == "winmm") {
			startText = "The available MIDI";
			endText = "rtmidi: input device number is out of range";
		}
		else if (module == "coremidi") {
			int index = messages.indexOf(QRegExp("[0-9]{1,1} MIDI sources in system\\s*"));
            if (index >= 0) {
                for (int i = 0; i < messages[index].split(" ")[0].toInt(); i++) {
                    deviceList.insert(QString::number(i), QString::number(i));
                }
            }
		}
		else if (module == "alsaseq") {
			//FIXME parse alsaseq devices
		}
		if (startText == "" && endText == "") {
			return deviceList;
		}
		bool collect = false;
		foreach (QString line, messages) {
			if (collect) {
				if (endText.length() > 0 && line.indexOf(endText) >= 0) {
					collect = false;
				}
				else {
					if (line.indexOf(":") >= 0) {
//						qDebug() << "getMidiInputDevices " << line;
						QString fullname = line.mid(line.indexOf(":") + 1).trimmed();
						QString devname = line.mid(0,line.indexOf(":")).trimmed();
						deviceList.insert(fullname, devname);
					}
				}
			}
			else if (line.indexOf(startText) >= 0) {
				collect = true;
			}
		}
	}
#endif
	return deviceList;
}
Example #17
0
void Wizard::checkMltComponents()
{
    m_mltCheck.programList->setColumnCount(2);
    m_mltCheck.programList->setRootIsDecorated(false);
    m_mltCheck.programList->setHeaderHidden(true);
    QSize itemSize(20, fontMetrics().height() * 2.5);
    m_mltCheck.programList->setColumnWidth(0, 30);
    m_mltCheck.programList->setIconSize(QSize(24, 24));


    QTreeWidgetItem *mltitem = new QTreeWidgetItem(m_mltCheck.programList);

    QTreeWidgetItem *meltitem = new QTreeWidgetItem(m_mltCheck.programList, QStringList() << QString() << i18n("Melt") + " (" + KdenliveSettings::rendererpath() + ')');
    meltitem->setData(1, Qt::UserRole, i18n("Required for rendering (part of MLT package)"));
    meltitem->setSizeHint(0, itemSize);
    meltitem->setIcon(0, m_okIcon);

    // Check MLT's installed producers
    QProcess checkProcess;
    checkProcess.start(KdenliveSettings::rendererpath(), QStringList() << "-query" << "producer");
    if (!checkProcess.waitForStarted()) {
        meltitem->setIcon(0, m_badIcon);
        meltitem->setData(1, Qt::UserRole, i18n("Error starting MLT's command line player (melt)"));
        button(QWizard::NextButton)->setEnabled(false);
    } else {
        checkProcess.waitForFinished();
        QByteArray result = checkProcess.readAllStandardError();

        // Check MLT avformat module
        QTreeWidgetItem *avformatItem = new QTreeWidgetItem(m_mltCheck.programList, QStringList() << QString() << i18n("Avformat module (FFmpeg)"));
        avformatItem->setData(1, Qt::UserRole, i18n("Required to work with various video formats (hdv, mpeg, flash, ...)"));
        avformatItem->setSizeHint(0, itemSize);
        if (!result.contains("- avformat")) {
            avformatItem->setIcon(0, m_badIcon);
            m_mltCheck.tabWidget->setTabEnabled(1, false);
        } else {
            avformatItem->setIcon(0, m_okIcon);
            // Make sure we have MLT > 0.3.4
            bool recentMlt = false;
            int version = 0;
            QString mltVersion;
            QString exepath = KStandardDirs::findExe("pkg-config");
            if (!exepath.isEmpty()) {
                checkProcess.start(exepath, QStringList() << "--variable=version" << "mlt++");
                if (!checkProcess.waitForStarted()) {
                    kDebug() << "// Error querying MLT's version";
                } else {
                    checkProcess.waitForFinished();
                    mltVersion = checkProcess.readAllStandardOutput();
                    version = 100 * mltVersion.section('.', 0, 0).toInt() + 10 * mltVersion.section('.', 1, 1).toInt() + mltVersion.section('.', 2, 2).toInt();
                    kDebug() << "// FOUND MLT's pkgconfig version: " << version;
                    if (version > 34) recentMlt = true;
                }
            }
            if (version == 0) {
                checkProcess.start(KdenliveSettings::rendererpath(), QStringList() << "--version");
                if (!checkProcess.waitForStarted()) {
                    kDebug() << "// Error querying MLT's version";
                } else {
                    checkProcess.waitForFinished();
                    mltVersion = checkProcess.readAllStandardError();
                    mltVersion = mltVersion.section('\n', 0, 0).simplified();
                    mltVersion = mltVersion.section(' ', -1).simplified();
                    version = 100 * mltVersion.section('.', 0, 0).toInt() + 10 * mltVersion.section('.', 1, 1).toInt() + mltVersion.section('.', 2, 2).toInt();
                    kDebug() << "// FOUND MLT version: " << version;
                    if (version >= 40) recentMlt = true;
                }
            }

            mltitem->setText(1, i18n("MLT version: %1", mltVersion.simplified()));
            mltitem->setSizeHint(0, itemSize);
            if (version < recommendedMltVersion) {
                mltitem->setData(1, Qt::UserRole, i18n("Please upgrade to the latest MLT version"));
                mltitem->setIcon(0, m_badIcon);
            } else {
                mltitem->setData(1, Qt::UserRole, i18n("MLT version is correct"));
                mltitem->setIcon(0, m_okIcon);
            }

            if (recentMlt) {
                // Check installed audio codecs
                QProcess checkProcess2;
                checkProcess2.start(KdenliveSettings::rendererpath(), QStringList() << "noise:" << "-consumer" << "avformat" << "acodec=list");
                if (!checkProcess2.waitForStarted()) {
                    m_mltCheck.tabWidget->setTabEnabled(1, false);
                    kDebug() << "// Error parsing MLT's avformat codecs";
                } else {
                    checkProcess2.waitForFinished();
                    QByteArray codecList = checkProcess2.readAllStandardError();
                    QString acodecList(codecList);
                    QStringList result;
                    QStringList alist = acodecList.split('\n', QString::SkipEmptyParts);
                    for (int i = 0; i < alist.count(); i++) {
                        if (alist.at(i).contains("- ")) result.append(alist.at(i).section("- ", 1).simplified().toLower());
                    }
                    m_mltCheck.acodecs_list->addItems(result);
                    KdenliveSettings::setAudiocodecs(result);
                    //kDebug()<<"// FOUND LIST:\n\n"<<m_audioCodecs<<"\n\n++++++++++++++++++++";
                }
                // Check video codecs
                checkProcess2.start(KdenliveSettings::rendererpath(), QStringList() << "noise:" << "-consumer" << "avformat" << "vcodec=list");
                if (!checkProcess2.waitForStarted()) {
                    kDebug() << "// Error parsing MLT's avformat codecs";
                } else {
                    checkProcess2.waitForFinished();
                    QByteArray codecList = checkProcess2.readAllStandardError();
                    QString vcodecList(codecList);
                    QStringList result;
                    QStringList vlist = vcodecList.split('\n', QString::SkipEmptyParts);
                    for (int i = 0; i < vlist.count(); i++) {
                        if (vlist.at(i).contains("- ")) result.append(vlist.at(i).section("- ", 1).simplified().toLower());
                    }
                    m_mltCheck.vcodecs_list->addItems(result);
                    KdenliveSettings::setVideocodecs(result);
                    //kDebug()<<"// FOUND LIST:\n\n"<<m_videoCodecs<<"\n\n++++++++++++++++++++";
                }
                // Check formats
                checkProcess2.start(KdenliveSettings::rendererpath(), QStringList() << "noise:" << "-consumer" << "avformat" << "f=list");
                if (!checkProcess2.waitForStarted()) {
                    kDebug() << "// Error parsing MLT's avformat codecs";
                } else {
                    checkProcess2.waitForFinished();
                    QByteArray codecList = checkProcess2.readAllStandardError();
                    QString vcodecList(codecList);
                    QStringList result;
                    QStringList vlist = vcodecList.split('\n', QString::SkipEmptyParts);
                    for (int i = 0; i < vlist.count(); i++) {
                        if (vlist.at(i).contains("- ")) {
                            QString format = vlist.at(i).section("- ", 1).simplified().toLower();
                            if (format.contains(',')) {
                                QStringList sub = format.split(',', QString::SkipEmptyParts);
                                for (int j = 0; j < sub.count(); j++)
                                    result.append(sub.at(j));
                            } else result.append(format);
                        }
                    }
                    m_mltCheck.formats_list->addItems(result);
                    KdenliveSettings::setSupportedformats(result);
                    //kDebug()<<"// FOUND LIST:\n\n"<<m_videoCodecs<<"\n\n++++++++++++++++++++";
                }
            }

        }

        // Check MLT dv module
        QTreeWidgetItem *dvItem = new QTreeWidgetItem(m_mltCheck.programList, QStringList() << QString() << i18n("DV module (libdv)"));
        dvItem->setData(1, Qt::UserRole, i18n("Required to work with dv files if avformat module is not installed"));
        dvItem->setSizeHint(0, itemSize);
        if (!result.contains("- libdv")) {
            dvItem->setIcon(0, m_badIcon);
        } else {
            dvItem->setIcon(0, m_okIcon);
        }

        // Check MLT image format module
        QTreeWidgetItem *imageItem = new QTreeWidgetItem(m_mltCheck.programList, QStringList() << QString() << i18n("QImage module"));
        imageItem->setData(1, Qt::UserRole, i18n("Required to work with images"));
        imageItem->setSizeHint(0, itemSize);
        if (!result.contains("- qimage")) {
            imageItem->setIcon(0, m_badIcon);
            imageItem = new QTreeWidgetItem(m_mltCheck.programList, QStringList() << QString() << i18n("Pixbuf module"));
            imageItem->setData(1, Qt::UserRole, i18n("Required to work with images"));
            imageItem->setSizeHint(0, itemSize);
            if (!result.contains("- pixbuf")) imageItem->setIcon(0, m_badIcon);
            else imageItem->setIcon(0, m_okIcon);
        } else {
            imageItem->setIcon(0, m_okIcon);
        }
    }
}
Example #18
0
QList<QPair<QString, QString> > ConfigLists::getMidiOutputDevices(QString module)
{
	QList<QPair<QString, QString> > deviceList;
#ifdef CSOUND6
	CSOUND *cs = csoundCreate(NULL);
	csoundSetMIDIModule(cs, module.toLatin1().data());
	int i,newn, n = csoundGetMIDIDevList(cs,NULL,1);
	CS_MIDIDEVICE *devs = (CS_MIDIDEVICE *) malloc(n*sizeof(CS_MIDIDEVICE));
	newn = csoundGetMIDIDevList(cs,devs,1);
	if (newn != n) {
		qDebug() << "ConfigLists::getMidiOutputDevices Device number changed";
		return deviceList;
	}
	for (i = 0; i < n; i++) {
//		qDebug() << devs[i].device_name;
		QString displayName = QString("%1 (%2)").arg(devs[i].device_name).arg(devs[i].interface_name);
		deviceList.append(QPair<QString,QString>(displayName, QString(devs[i].device_id)));
	}
	free(devs);
    csoundDestroy(cs);
#else
	if (module == "none") {
		return deviceList;
	}
	if (module == "alsa") {
		QProcess amidi;
		amidi.start("amidi", QStringList() << "-l");
		if (!amidi.waitForFinished())
			return deviceList;

		QByteArray result = amidi.readAllStandardOutput();
		QString values = QString(result);
		QStringList st = values.split("\n");
		st.takeFirst(); // Remove first column lines
		for (int i = 0; i < st.size(); i++){
			QStringList parts = st[i].split(" ", QString::SkipEmptyParts);
			if (parts.size() > 0 && parts[0].contains("O")) {
				QPair<QString, QString> device;
				device.second = parts[1]; // Devce name
				parts.takeFirst(); // Remove IO flags
				device.first = parts.join(" ") ; // Full name with description
				deviceList.append(device);
			}
		}
	}
	else if (module == "virtual") {
		// do nothing
	}
	else { // if not alsa (i.e. winmm or portmidi)
		QFile file(":/test.csd");
		if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
			return deviceList;
		QString jackCSD = QString(file.readAll());
		QString tempText = jackCSD;
		tempText.replace("$SR", "441000");
		QTemporaryFile tempFile(QDir::tempPath() + QDir::separator() + "testcsdCsoundQtXXXXXX.csd");
		tempFile.open();
		QTextStream out(&tempFile);
		out << tempText;
		tempFile.close();
		tempFile.open();

		QStringList flags;
		flags << "-+msg_color=false" << "-otest"  << "-n"   << "-Q999" << tempFile.fileName();
		QStringList messages = runCsoundInternally(flags);

		QString startText, endText;
		if (module == "portmidi") {
			startText = "The available MIDI";
			endText = "*** PortMIDI";
		}
		else if (module == "winmm") {
			startText = "The available MIDI";
			endText = "rtmidi: output device number is out of range";
		}
		if (startText == "" && endText == "") {
			return deviceList;
		}
		bool collect = false;
		foreach (QString line, messages) {
			if (collect) {
				if (endText.length() > 0 && line.indexOf(endText) >= 0) {
					collect = false;
				}
				else {
					if (line.indexOf(":") >= 0) {
						qDebug("%s", line.toLocal8Bit().constData());
						QPair<QString, QString> device;
						device.first = line.mid(line.indexOf(":") + 1).trimmed();
						device.second = line.mid(0,line.indexOf(":")).trimmed();
						deviceList.append(device);
					}
				}
			}
			else if (line.indexOf(startText) >= 0) {
				collect = true;
			}
		}
	}
#endif
	return deviceList;
}
Example #19
0
bool SSHConnectionCLI::executeSSH(const QString& command,
                                  const QStringList& args, QString* stdout_str,
                                  QString* stderr_str, int* ec)
{
  QProcess proc;

  QStringList fullArgs;

  // Add username
  if (!m_user.isEmpty())
    fullArgs << "-l" << m_user;

  // Add port number
  fullArgs << "-p" << QString::number(m_port);

  // Add hostname
  fullArgs << m_host;

  // Add command and original arguments
  fullArgs << command;
  fullArgs << args;

  proc.start("ssh", fullArgs);
  int timeout_ms = 60000; // one minute

  if (!proc.waitForStarted(timeout_ms)) {
    qWarning() << QString("Failed to start ssh command with args \"%1\" "
                          "after %2 seconds.")
                    .arg(fullArgs.join(","))
                    .arg(timeout_ms / 1000);
    return false;
  }

  proc.closeWriteChannel();
  if (!proc.waitForFinished(timeout_ms)) {
    qWarning() << QString("ssh command with args \"%1\" failed to finish "
                          "within %2 seconds.")
                    .arg(fullArgs.join(","))
                    .arg(timeout_ms / 1000);
    return false;
  }

  if (proc.exitCode() == 255) {
    qWarning() << QString("ssh command with args \"%1\" returned an exit "
                          "code of 255. This usually means that ssh failed "
                          "to connect, but it may also be a valid exit code"
                          " for the command which was run. Assuming that "
                          "ssh has errored. Contact the development team "
                          "if you believe this is an error.")
                    .arg(fullArgs.join(","))
               << "\nstdout:\n"
               << QString(proc.readAllStandardOutput()) << "\nstderr:\n"
               << QString(proc.readAllStandardError());
    return false;
  }

  if (stdout_str != nullptr)
    *stdout_str = QString(proc.readAllStandardOutput());
  if (stderr_str != nullptr)
    *stderr_str = QString(proc.readAllStandardError());
  if (ec != nullptr)
    *ec = proc.exitCode();

  proc.close();

  return true;
}
int main( int argc,char * argv[] )
{
	QApplication a( argc,argv ) ;

	MainWindow w( []( const QVector<QString>& exe,const QString& keyFile,const QString& password ){

		/*
		 * TODO: look into passing the passphrase more securely
		 */

		QString arg = QString( "%1 --extract -sf %2 -xf - -p %3" ).arg( exe.first(),keyFile,password ) ;

		QProcess p ;

		p.start( arg ) ;

		p.waitForFinished( -1 ) ;

		QByteArray key = p.readAllStandardOutput() ;

		p.close() ;

		if( key.isEmpty() ){

			return key ;
		}else{

			key = "\n-----BEGIN PGP MESSAGE-----\n\n" + key + "-----END PGP MESSAGE-----\n" ;

			QString temp_path = QString( "%1/%2/" ).arg( QDir::homePath(),"/.zuluCrypt/" ) ;

			QDir d ;
			d.mkpath( temp_path ) ;

			temp_path += QString( ".tomb-%1" ).arg( QString::number( getpid() ) ) ;
			/*
			 * temp_path will have something like "/home/ink/.zuluCrypt/.tomb-3452"
			 * this will be a path to a temporary file we will pass to gpg since gpg expects a keyfile path
			 * TODO: look into skipping creating a temporary file and do everything in memory
			 */
			QFile temp_file( temp_path ) ;

			temp_file.open( QIODevice::WriteOnly ) ;
			temp_file.write( key ) ;
			temp_file.close() ;

			key = plugins::gpg( QVector<QString>{ exe.at( 1 ) },temp_path,password ) ;

			temp_file.setFileName( temp_path ) ;
			temp_file.open( QIODevice::WriteOnly ) ;

			uchar * m = temp_file.map( 0,temp_file.size() ) ;

			if( m ){
				memset( m,'\0',temp_file.size() ) ;
				temp_file.unmap( m ) ;
			}
			temp_file.close() ;
			temp_file.remove() ;
			return key ;
		}
	} ) ;

	w.setToken( argv ) ;
	w.setApplicationName( "tomb" ) ;
	w.setkeyLabel( QObject::tr( "Enter tomb/steghide Key Below" ) ) ;
	w.setkeyFileLabel( QObject::tr( "Enter A Path To A tomb/steghide Keyfile Below" ) ) ;

	w.setExe( { "steghide","gpg" } ) ;

	w.Show() ;

	return a.exec() ;
}
Example #21
0
/**
 * Starting point for the retracing thread.
 *
 * Overrides QThread::run().
 */
void Retracer::run()
{
    QString msg = QLatin1String("Replay finished!");

    /*
     * Construct command line
     */

    QString prog;
    QStringList arguments;

    switch (m_api) {
    case trace::API_GL:
        prog = QLatin1String("glretrace");
        break;
    case trace::API_EGL:
        prog = QLatin1String("eglretrace");
        break;
    case trace::API_DX:
    case trace::API_D3D7:
    case trace::API_D3D8:
    case trace::API_D3D9:
    case trace::API_DXGI:
#ifdef Q_OS_WIN
        prog = QLatin1String("d3dretrace");
#else
        prog = QLatin1String("wine");
        arguments << QLatin1String("d3dretrace.exe");
#endif
        break;
    default:
        emit finished(QLatin1String("Unsupported API"));
        return;
    }

    if (m_singlethread) {
        arguments << QLatin1String("--singlethread");
    }

    if (m_captureState) {
        arguments << QLatin1String("-D");
        arguments << QString::number(m_captureCall);
    } else if (m_captureThumbnails) {
        arguments << QLatin1String("-s"); // emit snapshots
        arguments << QLatin1String("-"); // emit to stdout
    } else if (isProfiling()) {
        if (m_profileGpu) {
            arguments << QLatin1String("--pgpu");
        }

        if (m_profileCpu) {
            arguments << QLatin1String("--pcpu");
        }

        if (m_profilePixels) {
            arguments << QLatin1String("--ppd");
        }
    } else {
        if (m_doubleBuffered) {
            arguments << QLatin1String("--db");
        } else {
            arguments << QLatin1String("--sb");
        }

        if (m_benchmarking) {
            arguments << QLatin1String("-b");
        }
    }

    arguments << m_fileName;

    /*
     * Support remote execution on a separate target.
     */

    if (m_remoteTarget.length() != 0) {
        arguments.prepend(prog);
        arguments.prepend(m_remoteTarget);
        prog = QLatin1String("ssh");
    }

    /*
     * Start the process.
     */

    QProcess process;

    process.start(prog, arguments, QIODevice::ReadOnly);
    if (!process.waitForStarted(-1)) {
        emit finished(QLatin1String("Could not start process"));
        return;
    }

    /*
     * Process standard output
     */

    QList<QImage> thumbnails;
    QVariantMap parsedJson;
    trace::Profile* profile = NULL;

    process.setReadChannel(QProcess::StandardOutput);
    if (process.waitForReadyRead(-1)) {
        BlockingIODevice io(&process);

        if (m_captureState) {
            /*
             * Parse JSON from the output.
             *
             * XXX: QJSON's scanner is inneficient as it abuses single
             * character QIODevice::peek (not cheap), instead of maintaining a
             * lookahead character on its own.
             */

            bool ok = false;
            QJson::Parser jsonParser;

            // Allow Nan/Infinity
            jsonParser.allowSpecialNumbers(true);
#if 0
            parsedJson = jsonParser.parse(&io, &ok).toMap();
#else
            /*
             * XXX: QJSON expects blocking IO, and it looks like
             * BlockingIODevice does not work reliably in all cases.
             */
            process.waitForFinished(-1);
            parsedJson = jsonParser.parse(&process, &ok).toMap();
#endif
            if (!ok) {
                msg = QLatin1String("failed to parse JSON");
            }
        } else if (m_captureThumbnails) {
            /*
             * Parse concatenated PNM images from output.
             */

            while (!io.atEnd()) {
                image::PNMInfo info;

                char header[512];
                qint64 headerSize = 0;
                int headerLines = 3; // assume no optional comment line

                for (int headerLine = 0; headerLine < headerLines; ++headerLine) {
                    qint64 headerRead = io.readLine(&header[headerSize], sizeof(header) - headerSize);

                    // if header actually contains optional comment line, ...
                    if (headerLine == 1 && header[headerSize] == '#') {
                        ++headerLines;
                    }

                    headerSize += headerRead;
                }

                const char *headerEnd = image::readPNMHeader(header, headerSize, info);

                // if invalid PNM header was encountered, ...
                if (headerEnd == NULL ||
                    info.channelType != image::TYPE_UNORM8) {
                    qDebug() << "error: invalid snapshot stream encountered";
                    break;
                }

                unsigned channels = info.channels;
                unsigned width = info.width;
                unsigned height = info.height;

                // qDebug() << "channels: " << channels << ", width: " << width << ", height: " << height";

                QImage snapshot = QImage(width, height, channels == 1 ? QImage::Format_Mono : QImage::Format_RGB888);

                int rowBytes = channels * width;
                for (int y = 0; y < height; ++y) {
                    unsigned char *scanLine = snapshot.scanLine(y);
                    qint64 readBytes = io.read((char *) scanLine, rowBytes);
                    Q_ASSERT(readBytes == rowBytes);
                    (void)readBytes;
                }

                QImage thumb = thumbnail(snapshot);
                thumbnails.append(thumb);
            }

            Q_ASSERT(process.state() != QProcess::Running);
        } else if (isProfiling()) {
            profile = new trace::Profile();

            while (!io.atEnd()) {
                char line[256];
                qint64 lineLength;

                lineLength = io.readLine(line, 256);

                if (lineLength == -1)
                    break;

                trace::Profiler::parseLine(line, profile);
            }
        } else {
            QByteArray output;
            output = process.readAllStandardOutput();
            if (output.length() < 80) {
                msg = QString::fromUtf8(output);
            }
        }
    }

    /*
     * Wait for process termination
     */

    process.waitForFinished(-1);

    if (process.exitStatus() != QProcess::NormalExit) {
        msg = QLatin1String("Process crashed");
    } else if (process.exitCode() != 0) {
        msg = QLatin1String("Process exited with non zero exit code");
    }

    /*
     * Parse errors.
     */

    QList<ApiTraceError> errors;
    process.setReadChannel(QProcess::StandardError);
    QRegExp regexp("(^\\d+): +(\\b\\w+\\b): ([^\\r\\n]+)[\\r\\n]*$");
    while (!process.atEnd()) {
        QString line = process.readLine();
        if (regexp.indexIn(line) != -1) {
            ApiTraceError error;
            error.callIndex = regexp.cap(1).toInt();
            error.type = regexp.cap(2);
            error.message = regexp.cap(3);
            errors.append(error);
        } else if (!errors.isEmpty()) {
            // Probably a multiligne message
            ApiTraceError &previous = errors.last();
            if (line.endsWith("\n")) {
                line.chop(1);
            }
            previous.message.append('\n');
            previous.message.append(line);
        }
    }

    /*
     * Emit signals
     */

    if (m_captureState) {
        ApiTraceState *state = new ApiTraceState(parsedJson);
        emit foundState(state);
    }

    if (m_captureThumbnails && !thumbnails.isEmpty()) {
        emit foundThumbnails(thumbnails);
    }

    if (isProfiling() && profile) {
        emit foundProfile(profile);
    }

    if (!errors.isEmpty()) {
        emit retraceErrors(errors);
    }

    emit finished(msg);
}
Example #22
0
/// called after "file" set in constructor
void g2m::interpret() {
    //success = false;
    QProcess toCanon;
    bool foundEOF; // checked at the end
    
    if (!startInterp(toCanon)) // finds rs274, reads tooltable, start interpreter
        return;
    
    if (!toCanon.waitForReadyRead(1000) ) {
        if ( toCanon.state() == QProcess::NotRunning ){
            infoMsg("Interpreter died.  Bad tool table?");
        } else  
            infoMsg("Interpreter timed out for an unknown reason.");
        std::cout << "stderr: " << (const char*)toCanon.readAllStandardError() << std::endl;
        std::cout << "stdout: " << (const char*)toCanon.readAllStandardOutput() << std::endl;
        toCanon.close();
        return;
    }
    
    // rs274  has now started correctly, and is ready to read ngc-file
    qint64 lineLength;
    char line[260];
    int fails = 0;
    do {
        if (toCanon.canReadLine()) {
            lineLength = toCanon.readLine(line, sizeof(line)); // read one output line from rs274
            if (lineLength != -1 ) {
                QString l(line);
                emit canonLineMessage( l.left(l.size()-1) );
                foundEOF = processCanonLine(line); // line is a canon-line
            } else {  //shouldn't get here!
                std::cout << " ERROR: lineLength= " << lineLength << "  fails="<< fails << "\n";
                fails++;
            }
        } else {
            std::cout << " ERROR: toCanon.canReadLine() fails="<< fails << "\n";
            fails++;
        }
        toCanon.waitForReadyRead();
    } while ( (fails < 100) &&
           ( (toCanon.canReadLine()) ||
            ( toCanon.state() != QProcess::NotRunning ) )  );
  
    if (fails > 1) {
        if (fails < 100) {
            infoMsg("Waited for interpreter over 100  times.");
        } else {
            infoMsg("Waited 100 seconds for interpreter. Giving up.");
            toCanon.close();
            return;
        }
    }
  
  std::string s = (const char *)toCanon.readAllStandardError();
  s.erase(0,s.find("executing"));
  if (s.size() > 10) {
    infoMsg("Interpreter exited with error:\n"+s.substr(10));
    return;
  }
  if (!foundEOF) {
    infoMsg("Warning: file data not terminated correctly. If the file is terminated correctly, this indicates a problem interpreting the file.");
  }

    emit debugMessage( tr("g2m: read %1 lines of g-code which produced %2 canon-lines.").arg(gcode_lines).arg(lineVector.size()) );
    return;
}
Example #23
0
bool Haproxy::haproxy(const QString &host, const QString &ip, const QString &port, const QString &endpoint, const QString &endpointport, const QString &fixedHost, const QString &auth, const QString &provider, const QString &plan, const QString &serviceName) {
    // TODO: this should be set at global scope instead of for these individual users of "host"
    // many files are expected to be at "the same level" as the gui executable
    // - for windows: a relative path is ok
    #if defined(Q_OS_WIN)
    const QString sibling_file_path = "";
    #else
    const QString sibling_file_path = host;
    #endif

    qDebug() << "Starting haproxy";

    QFile::remove(sibling_file_path + "provider.http");
    QFile fileProvider(sibling_file_path + "provider.http");

    QFile::remove(sibling_file_path + "ha_credit.http");
    QFile fileCredit(sibling_file_path + "ha_credit.http");

    QFile::remove(sibling_file_path + "ha_err_badid.http");
    QFile fileBadid(sibling_file_path + "ha_err_badid.http");

    QFile::remove(sibling_file_path + "ha_err_connect.http");
    QFile fileConnect(sibling_file_path + "ha_err_connect.http");

    QFile::remove(sibling_file_path + "ha_err_nopayment.http");
    QFile fileNopayment(sibling_file_path + "ha_err_nopayment.http");

    QFile::remove(sibling_file_path + "ha_err_overlimit.http");
    QFile fileOverlimit(sibling_file_path + "ha_err_overlimit.http");

    QFile::remove(sibling_file_path + "ha_info.http");
    QFile fileInfo(sibling_file_path + "ha_info.http");

    // delete old file and create new one
    QFile::remove(sibling_file_path + "haproxy.cfg");
    QFile file(sibling_file_path + "haproxy.cfg");

    //create provider.http
    if(fileProvider.open(QIODevice::ReadOnly | QIODevice::WriteOnly | QIODevice::Text)){
        QTextStream txtStream(&fileProvider);

        txtStream << "HTTP/1.0 200 PROVIDER\n";
        txtStream << "Access-Control-Allow-Origin: *\n";
        txtStream << "Access-Control-Allow-Methods: GET\n";
        txtStream << "Cache-Control: no-cache\n";
        txtStream << "Content-Type: text/html\n\n";

        txtStream << "{\"provider\":\""+serviceName+"\",\"service\":\""+plan+"\"}";


        txtStream.seek(0);
        /*
        while(!txtStream.atEnd()) {
            qDebug() << txtStream.readLine();
        }
        */
        fileProvider.close();
    }

    //create ha_credit.http
    if(fileCredit.open(QIODevice::ReadOnly | QIODevice::WriteOnly | QIODevice::Text)){
        QTextStream txtStream(&fileCredit);

        txtStream << "HTTP/1.0 200 OK\n";
        txtStream << "Cache-Control: no-cache\n";
        txtStream << "Connection: close\n";
        txtStream << "Content-Type: text/html\n";
        txtStream << "<html>\n";

        txtStream << "<body>\n";
        txtStream << "<h1>ITNSVPN credit unavailable yet</h1>\n";
        txtStream << "</body>\n";
        txtStream << "</html>\n";



        txtStream.seek(0);
        /*
        while(!txtStream.atEnd()) {
            qDebug() << txtStream.readLine();
        }
        */
        fileCredit.close();
    }

    //create ha_err_badid.http
    if(fileBadid.open(QIODevice::ReadOnly | QIODevice::WriteOnly | QIODevice::Text)){
        QTextStream txtStream(&fileBadid);

        txtStream << "HTTP/1.0 503 BAD_ID\n";
        txtStream << "Access-Control-Allow-Origin: *\n";
        txtStream << "Access-Control-Allow-Methods: GET\n";
        txtStream << "Access-Control-Allow-Headers: X-ITNS-Status\n";
        txtStream << "Access-Control-Max-Age: 86400\n";

        txtStream << "Cache-Control: no-cache\n";
        txtStream << "Connection: close\n";
        txtStream << "Content-Type: text/html\n";
        txtStream << "X-ITNS-Status: BAD_ID\n";
        txtStream << "BAD_ID\n";

        txtStream.seek(0);
        /*
        while(!txtStream.atEnd()) {
            qDebug() << txtStream.readLine();
        }
        */
        fileBadid.close();
    }

    //create ha_err_connect.http
    if(fileConnect.open(QIODevice::ReadOnly | QIODevice::WriteOnly | QIODevice::Text)){
        QTextStream txtStream(&fileConnect);

        txtStream << "HTTP/1.0 503 CONNECTION_ERROR\n";
        txtStream << "Access-Control-Allow-Origin: *\n";
        txtStream << "Access-Control-Allow-Methods: GET\n";
        txtStream << "Access-Control-Allow-Headers: X-ITNS-Status\n";
        txtStream << "Access-Control-Max-Age: 86400\n";

        txtStream << "Cache-Control: no-cache\n";
        txtStream << "Connection: close\n";
        txtStream << "Content-Type: text/html\n";
        txtStream << "X-ITNS-Status: CONNECTION_ERROR\n";
        txtStream << "CONNECTION_ERROR\n";

        txtStream.seek(0);
        /*
        while(!txtStream.atEnd()) {
            qDebug() << txtStream.readLine();
        }
        */
        fileConnect.close();
    }

    //create ha_err_nopayment.http
    if(fileNopayment.open(QIODevice::ReadOnly | QIODevice::WriteOnly | QIODevice::Text)){
        QTextStream txtStream(&fileNopayment);

        txtStream << "HTTP/1.0 403 Forbidden\n";
        txtStream << "Access-Control-Allow-Origin: *\n";
        txtStream << "Access-Control-Allow-Methods: GET\n";
        txtStream << "Access-Control-Allow-Headers: X-ITNS-Status\n";
        txtStream << "Access-Control-Max-Age: 86400\n";

        txtStream << "Cache-Control: no-cache\n";
        txtStream << "Connection: close\n";
        txtStream << "Content-Type: text/html\n";
        txtStream << "X-ITNS-Status: NO_PAYMENT\n";
        txtStream << "NO_PAYMENT\n";

        txtStream.seek(0);
        /*
        while(!txtStream.atEnd()) {
            qDebug() << txtStream.readLine();
        }
        */
        fileNopayment.close();
    }

    //create ha_err_overlimit.http
    if(fileOverlimit.open(QIODevice::ReadOnly | QIODevice::WriteOnly | QIODevice::Text)){
        QTextStream txtStream(&fileOverlimit);

        txtStream << "HTTP/1.0 429 Too many requests\n";
        txtStream << "Access-Control-Allow-Origin: *\n";
        txtStream << "Access-Control-Allow-Methods: GET\n";
        txtStream << "Access-Control-Allow-Headers: X-ITNS-Status\n";
        txtStream << "Access-Control-Max-Age: 86400\n";

        txtStream << "Cache-Control: no-cache\n";
        txtStream << "Connection: close\n";
        txtStream << "Content-Type: text/html\n";
        txtStream << "X-ITNS-Status: OVERLIMIT\n";
        txtStream << "OVERLIMIT\n";

        txtStream.seek(0);
        /*
        while(!txtStream.atEnd()) {
            qDebug() << txtStream.readLine();
        }
        */
        fileOverlimit.close();
    }

    //create ha_info.http
    if(fileInfo.open(QIODevice::ReadOnly | QIODevice::WriteOnly | QIODevice::Text)){
        QTextStream txtStream(&fileInfo);

        txtStream << "HTTP/1.0 200 OK\n";
        txtStream << "Access-Control-Allow-Origin: *\n";
        txtStream << "Access-Control-Allow-Methods: GET\n";
        txtStream << "Access-Control-Allow-Headers: X-ITNS-Status\n";
        txtStream << "Access-Control-Max-Age: 86400\n";

        txtStream << "Cache-Control: no-cache\n";
        txtStream << "Connection: close\n";
        txtStream << "Content-Type: text/html\n";
        txtStream << "X-ITNS-Status: OK\n";
        txtStream << "OK\n";

        txtStream.seek(0);
        /*
        while(!txtStream.atEnd()) {
            qDebug() << txtStream.readLine();
        }
        */
        fileInfo.close();
    }

    //create config file
    if (file.open(QIODevice::ReadOnly | QIODevice::WriteOnly | QIODevice::Text)) {

        QTextStream txtStream(&file);
        txtStream << "global\n";
        txtStream << "maxconn         2000\n";
        txtStream << "daemon\n";
        txtStream << "ssl-default-bind-ciphers ECDH+AESGCM\n";
        txtStream << "ssl-default-bind-options force-tlsv12\n";
        txtStream << "no log\n";


        txtStream << "frontend icproxy\n";
        txtStream << "bind            "+ip+":"+port+"\n";
        txtStream << "mode            http\n";
        txtStream << "log             global\n";
        txtStream << "option          dontlognull\n";
        txtStream << "option          nolinger\n";
        txtStream << "option          http_proxy\n";
        txtStream << "option          contstats\n";
        txtStream << "maxconn         8000\n";
        txtStream << "timeout client  30s\n";

        txtStream << "acl is_mgmt_host url_dom _local_\n";
        txtStream << "acl is_mgmt_path path_beg /status\n";
        txtStream << "acl is_stats_path path_beg /stats\n";
        txtStream << "acl is_mgmt_id hdr_reg(X-ITNS-MgmtID) ^"+provider+"$\n";
        txtStream << "acl is_proxy_request url_reg '.*://.*'\n";
        txtStream << "acl is_connect method CONNECT\n";
        txtStream << "acl is_options method OPTIONS\n";

        txtStream << "# If this is local request with right authid /stats, forward to stats backend\n";
        txtStream << "use_backend b-stats if !is_options !is_proxy_request is_stats_path is_mgmt_id\n";

        txtStream << "#  If this is local request with authid /status, forward to status backend\n";
        txtStream << "use_backend b-status if !is_proxy_request is_mgmt_path is_mgmt_id\n";

        txtStream << "# If this is proxy request with right id\n";
        txtStream << "use_backend b-status if is_mgmt_host is_mgmt_path is_mgmt_id\n";

        txtStream << "# If this is proxy request with right id\n";
        txtStream << "use_backend b-stats if is_mgmt_host is_stats_path is_mgmt_id\n";

        txtStream << "# Wrong mgmtid\n";
        txtStream << "use_backend b-err if is_mgmt_host is_mgmt_path !is_mgmt_id\n";

        txtStream << "# Forward OPTIONS to status\n";
        txtStream << "use_backend b-status if is_options !is_proxy_request is_mgmt_path is_mgmt_id\n";
        txtStream << "use_backend b-status if is_options !is_proxy_request is_stats_path\n";
        txtStream << "use_backend http-proxy if is_proxy_request || is_connect\n";

        txtStream << "backend http-proxy\n";
        txtStream << "mode            http\n";
        txtStream << "timeout connect 5s\n";
        txtStream << "timeout server  30s\n";
        //txtStream << "timeout client  30s\n";
        txtStream << "retries         2\n";
        txtStream << "option          nolinger\n";
        txtStream << "option          httplog\n";
        txtStream << "http-request add-header X-ITNS-PaymentID "+auth+"\n";
        #ifdef Q_OS_WIN
        txtStream << "server hatls " + endpoint + ":" + endpointport + " force-tlsv12 ssl ca-file 'ca.cert.pem'\n";
        #else
        txtStream << "server hatls " + endpoint + ":" + endpointport + " force-tlsv12 ssl ca-file '"+sibling_file_path+"ca.cert.pem'\n";
        //save the host variable to show in dashboard
        Haproxy::m_haproxyConfigPath = sibling_file_path;
        #endif

        txtStream << "errorfile 503 " + sibling_file_path + "ha_err_connect.http\n";

        txtStream << "backend b-err\n";
        txtStream << "mode            http\n";
        txtStream << "timeout server  30s\n";
        txtStream << "timeout connect 5s\n";
        //txtStream << "timeout client  30s\n";
        txtStream << "errorfile 503 " + sibling_file_path + "ha_err_badid.http\n";

        txtStream << "backend b-status\n";
        txtStream << "mode            http\n";
        txtStream << "timeout server  30s\n";
        txtStream << "timeout connect 5s\n";
        //txtStream << "timeout client  30s\n";
        txtStream << "errorfile 503 " + sibling_file_path + "ha_info.http\n";

        txtStream << "backend b-stats\n";
        txtStream << "mode            http\n";
        txtStream << "timeout server  30s\n";
        txtStream << "timeout connect 5s\n";
        txtStream << "server Local 127.0.0.1:8181\n";

        txtStream << "listen  stats\n";
        txtStream << "timeout client  30s\n";
        txtStream << "timeout server  30s\n";
        txtStream << "timeout connect 5s\n";
        txtStream << "bind  127.0.0.1:8181\n";
        txtStream << "mode            http\n";
        txtStream << "stats enable\n";
        txtStream << "stats hide-version\n";
        txtStream << "stats refresh 30s\n";
        txtStream << "stats show-node\n";
        txtStream << "stats uri  /stats\n";

        txtStream << "listen provider\n";
        txtStream << "timeout client  30s\n";
        txtStream << "mode            http\n";
        txtStream << "timeout server  30s\n";
        txtStream << "timeout connect 5s\n";
        txtStream << "errorfile 503 " + sibling_file_path + "provider.http\n";

        txtStream << "bind 127.0.0.1:8182\n";

        txtStream.seek(0);
        /*
        while(!txtStream.atEnd()){
            qDebug() << txtStream.readLine();
        }
        */
        file.close();

        QString command = "";
        #ifdef Q_OS_WIN
            command = "haproxy.exe -f haproxy.cfg";
            uint result = WinExec(qPrintable(command),SW_HIDE);            
            if (result < 31) {
                m_haproxyStatus = "Failed to launch haproxy (" + QString::number(result) + ") ";
                qDebug() << "Failed to launch haproxy (Windows): " + QString::number(result);
                return false;
            }
        #else
            QString haProxyPath = NULL;
            QString hasHaproxyExecutable = NULL;

            #if defined(Q_OS_MAC)
                // verify if the haproxy exist in Mac if not send an alert
                QFileInfo check_haproxy_exist_osx("/usr/local/bin/haproxy");
                check_haproxy_exist_osx.refresh();
                if (check_haproxy_exist_osx.exists()) {
                    haProxyPath = "/usr/local/bin/haproxy";
                } else {
                    m_haproxyStatus = "Failed: " + haProxyPath;
                    return false;
                }
            #else
                // try to find haproxy correctly
                QProcess shellProcess;

                // find for haproxy
                shellProcess.start("/bin/sh");
                shellProcess.write("which haproxy || whereis haproxy | cut -d ' ' -f 2");
                shellProcess.closeWriteChannel();
                shellProcess.waitForFinished(-1);
                haProxyPath = shellProcess.readAllStandardOutput().trimmed();

                // when you remove the haproxy from your computer that path still works
                if (haProxyPath == "/etc/haproxy") {
                    qDebug() << "HAProxy has only uninstall path ";
                    return false;
                }

                // verify if has haproxy executable
                command = "[ ! -e " + haProxyPath + " ]; echo $?";
                shellProcess.start("/bin/sh");
                shellProcess.write(qPrintable(command));
                shellProcess.closeWriteChannel();
                shellProcess.waitForFinished(-1);
                hasHaproxyExecutable = shellProcess.readAllStandardOutput().trimmed();

                if (hasHaproxyExecutable != "1") {
                    qDebug() << "HAProxy has no executable ";
                    return false;
                }
            #endif

            qDebug() << "HAProxy Path " << haProxyPath;

            // save in haproxy variable the path to show in dashboard
            Haproxy::m_haproxyPath = haProxyPath;

            // ha proxy location not found if output from command is empty or just the first word from whereis
            if (haProxyPath.isEmpty() || haProxyPath == "haproxy:") {
                qDebug() << "HAProxy not found!";
                 m_haproxyStatus = "NotFound: " + haProxyPath;
                return false;
            }

            //system("trap 'pkill -f haproxy; echo teste haproxy; exit;' INT TERM");
            command = haProxyPath + " -f " + sibling_file_path + "haproxy.cfg";
            int result = system(qPrintable(command));
            qDebug() << "Launched haproxy " << QString::number(result);
            if (result != 0) {
                m_haproxyStatus = "Failed to launch haproxy (" + QString::number(result) + ") " + haProxyPath + " " + sibling_file_path + "haproxy.cfg";
                return false;
            }
        #endif

        qDebug() << "Starting Haproxy: " << command;

    }
    else {
        m_haproxyStatus = "Failed to open (" + QString::number(file.error()) + ") " + sibling_file_path + "haproxy.cfg";
        qDebug() << "could not open the file";
        return false;
    }
    return true;
}
/*!
    \brief Returns the operating system UiGUI is currently running on as one string.

    The String contains name and version of the os. E.g. Linux Ubuntu 9.04.
 */
QString UiGuiSystemInfo::getOperatingSystem() {
    QString operatingSystemString = "";

#if defined(Q_WS_WIN)
    switch ( QSysInfo::WindowsVersion ) {
        case QSysInfo::WV_32s :
            operatingSystemString = "Windows 3.1 with Win 32s";
            break;
        case QSysInfo::WV_95 :
            operatingSystemString = "Windows 95";
            break;
        case QSysInfo::WV_98 :
            operatingSystemString = "Windows 98";
            break;
        case QSysInfo::WV_Me :
            operatingSystemString = "Windows Me";
            break;
        case QSysInfo::WV_NT :
            operatingSystemString = "Windows NT (operating system version 4.0)";
            break;
        case QSysInfo::WV_2000 :
            operatingSystemString = "Windows 2000 (operating system version 5.0)";
            break;
        case QSysInfo::WV_XP :
            operatingSystemString = "Windows XP (operating system version 5.1)";
            break;
        case QSysInfo::WV_2003 :
            operatingSystemString = "Windows Server 2003, Windows Server 2003 R2, Windows Home Server, Windows XP Professional x64 Edition (operating system version 5.2)";
            break;
        case QSysInfo::WV_VISTA :
            operatingSystemString = "Windows Vista, Windows Server 2008 (operating system version 6.0)";
            break;
        case QSysInfo::WV_WINDOWS7 :
            operatingSystemString = "Windows 7 (operating system version 6.1)";
            break;
        case QSysInfo::WV_CE :
            operatingSystemString = "Windows CE";
            break;
        case QSysInfo::WV_CENET :
            operatingSystemString = "Windows CE .NET";
            break;
        case QSysInfo::WV_CE_5 :
            operatingSystemString = "Windows CE 5.x";
            break;
        case QSysInfo::WV_CE_6 :
            operatingSystemString = "Windows CE 6.x";
            break;
        default :
            operatingSystemString = "Unknown Windows operating system.";
            break;
    }
#elif defined(Q_WS_MAC)
    switch ( QSysInfo::MacintoshVersion ) {
        case QSysInfo::MV_9 :
            operatingSystemString = "Mac OS 9 (unsupported)";
            break;
        case QSysInfo::MV_10_0 :
            operatingSystemString = "Mac OS X 10.0 Cheetah (unsupported)";
            break;
        case QSysInfo::MV_10_1 :
            operatingSystemString = "Mac OS X 10.1 Puma (unsupported)";
            break;
        case QSysInfo::MV_10_2 :
            operatingSystemString = "Mac OS X 10.2 Jaguar (unsupported)";
            break;
        case QSysInfo::MV_10_3 :
            operatingSystemString = "Mac OS X 10.3 Panther";
            break;
        case QSysInfo::MV_10_4 :
            operatingSystemString = "Mac OS X 10.4 Tiger";
            break;
        case QSysInfo::MV_10_5 :
            operatingSystemString = "Mac OS X 10.5 Leopard";
            break;
        case QSysInfo::MV_10_6 :
            operatingSystemString = "Mac OS X 10.6 Snow Leopard";
            break;
        case QSysInfo::MV_Unknown :
            operatingSystemString = "An unknown and currently unsupported platform";
            break;
        default :
            operatingSystemString = "Unknown Mac operating system.";
            break;
    }
#else
    //TODO: Detect Unix, Linux etc. distro as described on http://www.novell.com/coolsolutions/feature/11251.html
    operatingSystemString = "Linux";
    QProcess process;

    process.start("uname -s");
    bool result = process.waitForFinished(1000);
    QString os = process.readAllStandardOutput().trimmed();

    process.start("uname -r");
    result = process.waitForFinished(1000);
    QString rev = process.readAllStandardOutput().trimmed();

    process.start("uname -m");
    result = process.waitForFinished(1000);
    QString mach = process.readAllStandardOutput().trimmed();

    if ( os == "SunOS" ) {
        os = "Solaris";

        process.start("uname -p");
        result = process.waitForFinished(1000);
        QString arch = process.readAllStandardOutput().trimmed();

        process.start("uname -v");
        result = process.waitForFinished(1000);
        QString timestamp = process.readAllStandardOutput().trimmed();

        operatingSystemString = os + " " + rev + " (" + arch + " " + timestamp + ")";
    }
    else if ( os == "AIX" ) {
        process.start("oslevel -r");
        result = process.waitForFinished(1000);
        QString oslevel = process.readAllStandardOutput().trimmed();

        operatingSystemString = os + "oslevel " + oslevel;
    }
    else if ( os == "Linux" ) {
        QString dist;
        QString pseudoname;
        QString kernel = rev;

        if ( QFile::exists("/etc/redhat-release") ) {
            dist = "RedHat";

            process.start("sh -c \"cat /etc/redhat-release | sed s/.*\\(// | sed s/\\)//\"");
            result = process.waitForFinished(1000);
            pseudoname = process.readAllStandardOutput().trimmed();

            process.start("sh -c \"cat /etc/redhat-release | sed s/.*release\\ // | sed s/\\ .*//\"");
            result = process.waitForFinished(1000);
            rev = process.readAllStandardOutput().trimmed();
        }
        else if ( QFile::exists("/etc/SUSE-release") ) {
            process.start("sh -c \"cat /etc/SUSE-release | tr '\\n' ' '| sed s/VERSION.*//\"");
            result = process.waitForFinished(1000);
            dist = process.readAllStandardOutput().trimmed();

            process.start("sh -c \"cat /etc/SUSE-release | tr '\\n' ' ' | sed s/.*=\\ //\"");
            result = process.waitForFinished(1000);
            rev = process.readAllStandardOutput().trimmed();
        }
        else if ( QFile::exists("/etc/mandrake-release") ) {
            dist = "Mandrake";

            process.start("sh -c \"cat /etc/mandrake-release | sed s/.*\\(// | sed s/\\)//\"");
            result = process.waitForFinished(1000);
            pseudoname = process.readAllStandardOutput().trimmed();

            process.start("sh -c \"cat /etc/mandrake-release | sed s/.*release\\ // | sed s/\\ .*//\"");
            result = process.waitForFinished(1000);
            rev = process.readAllStandardOutput().trimmed();
        }
        else if ( QFile::exists("/etc/lsb-release") ) {
            dist = "Ubuntu";

            QString processCall = "sh -c \"cat /etc/lsb-release | tr '\\n' ' ' | sed s/.*DISTRIB_RELEASE=// | sed s/\\ .*//\"";
            process.start( processCall );
            result = process.waitForFinished(1000);
            rev = process.readAllStandardOutput().trimmed();
            QString errorStr = process.readAllStandardError();

            process.start("sh -c \"cat /etc/lsb-release | tr '\\n' ' ' | sed s/.*DISTRIB_CODENAME=// | sed s/\\ .*//\"");
            result = process.waitForFinished(1000);
            pseudoname = process.readAllStandardOutput().trimmed();
        }
        else if ( QFile::exists("/etc/debian_version") ) {
            dist = "Debian";

            process.start("cat /etc/debian_version");
            result = process.waitForFinished(1000);
            dist += process.readAllStandardOutput().trimmed();

            rev = "";
        }

        if ( QFile::exists("/etc/UnitedLinux-release") ) {
            process.start("sh -c \"cat /etc/UnitedLinux-release | tr '\\n' ' ' | sed s/VERSION.*//\"");
            result = process.waitForFinished(1000);
            dist += process.readAllStandardOutput().trimmed();
        }

        operatingSystemString = os + " " + dist + " " + rev + " (" + pseudoname + " " + kernel + " " + mach + ")";
    }
#endif

    return operatingSystemString;
}
Example #25
0
Path::List GccLikeCompiler::includes(const QString& arguments) const
{
    if ( !m_definesIncludes.value(arguments).includePaths.isEmpty() ) {
        return m_definesIncludes.value(arguments).includePaths;
    }

    QProcess proc;
    proc.setProcessChannelMode( QProcess::MergedChannels );

    // The following command will spit out a bunch of information we don't care
    // about before spitting out the include paths.  The parts we care about
    // look like this:
    // #include "..." search starts here:
    // #include <...> search starts here:
    //  /usr/lib/gcc/i486-linux-gnu/4.1.2/../../../../include/c++/4.1.2
    //  /usr/lib/gcc/i486-linux-gnu/4.1.2/../../../../include/c++/4.1.2/i486-linux-gnu
    //  /usr/lib/gcc/i486-linux-gnu/4.1.2/../../../../include/c++/4.1.2/backward
    //  /usr/local/include
    //  /usr/lib/gcc/i486-linux-gnu/4.1.2/include
    //  /usr/include
    // End of search list.

    auto compilerArguments = languageOptions(arguments);
    compilerArguments.append("-E");
    compilerArguments.append("-v");
    compilerArguments.append(QProcess::nullDevice());

    proc.start(path(), compilerArguments);

    if ( !proc.waitForStarted( 1000 ) || !proc.waitForFinished( 1000 ) ) {
        definesAndIncludesDebug() <<  "Unable to read standard include paths from " << path();
        return {};
    }

    // We'll use the following constants to know what we're currently parsing.
    enum Status {
        Initial,
        FirstSearch,
        Includes,
        Finished
    };
    Status mode = Initial;

    foreach( const QString &line, QString::fromLocal8Bit( proc.readAllStandardOutput() ).split( '\n' ) ) {
        switch ( mode ) {
            case Initial:
                if ( line.indexOf( "#include \"...\"" ) != -1 ) {
                    mode = FirstSearch;
                }
                break;
            case FirstSearch:
                if ( line.indexOf( "#include <...>" ) != -1 ) {
                    mode = Includes;
                    break;
                }
            case Includes:
                //Detect the include-paths by the first space that is prepended. Reason: The list may contain relative paths like "."
                if ( !line.startsWith( ' ' ) ) {
                    // We've reached the end of the list.
                    mode = Finished;
                } else {
                    // This is an include path, add it to the list.
                    m_definesIncludes[arguments].includePaths << Path(QFileInfo(line.trimmed()).canonicalFilePath());
                }
                break;
            default:
                break;
        }
        if ( mode == Finished ) {
            break;
        }
    }

    return m_definesIncludes[arguments].includePaths;
}
Example #26
0
void StelLogger::init(const QString& logFilePath)
{
	logFile.setFileName(logFilePath);

	if (logFile.open(QIODevice::WriteOnly | QIODevice::Truncate | QIODevice::Text | QIODevice::Unbuffered))
		qInstallMessageHandler(StelLogger::debugLogHandler);

	// write timestamp
	writeLog(QString("%1").arg(QDateTime::currentDateTime().toString(Qt::ISODate)));
	// write info about operating system
	writeLog(StelUtils::getOperatingSystemInfo());

	// write compiler version
#if defined __GNUC__ && !defined __clang__
	#ifdef __MINGW32__
		#define COMPILER "MinGW GCC"
	#else
		#define COMPILER "GCC"
	#endif
	writeLog(QString("Compiled using %1 %2.%3.%4").arg(COMPILER).arg(__GNUC__).arg(__GNUC_MINOR__).arg(__GNUC_PATCHLEVEL__));
#elif defined __clang__
	writeLog(QString("Compiled using %1 %2.%3.%4").arg("Clang").arg(__clang_major__).arg(__clang_minor__).arg(__clang_patchlevel__));
#elif defined _MSC_VER
	writeLog(QString("Compiled using %1").arg(getMsvcVersionString(_MSC_VER)));
#else
	writeLog("Unknown compiler");
#endif

	// write Qt version
	writeLog(QString("Qt runtime version: %1").arg(qVersion()));
	writeLog(QString("Qt compilation version: %1").arg(QT_VERSION_STR));

	// write addressing mode
#if defined(__LP64__) || defined(_WIN64)
	writeLog("Addressing mode: 64-bit");
#else
	writeLog("Addressing mode: 32-bit");
#endif

	// write memory and CPU info
#ifdef Q_OS_LINUX

#ifndef BUILD_FOR_MAEMO
	QFile infoFile("/proc/meminfo");
	if(!infoFile.open(QIODevice::ReadOnly | QIODevice::Text))
		writeLog("Could not get memory info.");
	else
	{
		while(!infoFile.peek(1).isEmpty())
		{
			QString line = infoFile.readLine();
			line.chop(1);
			if (line.startsWith("Mem") || line.startsWith("SwapTotal"))
				writeLog(line);
		}
		infoFile.close();
	}

	infoFile.setFileName("/proc/cpuinfo");
	if (!infoFile.open(QIODevice::ReadOnly | QIODevice::Text))
		writeLog("Could not get CPU info.");
	else
	{
		while(!infoFile.peek(1).isEmpty())
		{
			QString line = infoFile.readLine();
			line.chop(1);
			if(line.startsWith("model name") || line.startsWith("cpu MHz"))
				writeLog(line);
		}
		infoFile.close();
	}

	QProcess lspci;
	lspci.start("lspci -v", QIODevice::ReadOnly);
	lspci.waitForFinished(300);
	const QString pciData(lspci.readAll());
	QStringList pciLines = pciData.split('\n', QString::SkipEmptyParts);
	for (int i = 0; i<pciLines.size(); i++)
	{
		if(pciLines.at(i).contains("VGA compatible controller"))
		{
			writeLog(pciLines.at(i));
			i++;
			while(i < pciLines.size() && pciLines.at(i).startsWith('\t'))
			{
				if(pciLines.at(i).contains("Kernel driver in use"))
					writeLog(pciLines.at(i).trimmed());
				else if(pciLines.at(i).contains("Kernel modules"))
					writeLog(pciLines.at(i).trimmed());
				i++;
			}
		}
	}
#endif

// Aargh Windows API
#elif defined Q_OS_WIN
	// Hopefully doesn't throw a linker error on earlier systems. Not like
	// I'm gonna test it or anything.
	if (QSysInfo::WindowsVersion >= QSysInfo::WV_XP)
	{
		MEMORYSTATUSEX statex;
		statex.dwLength = sizeof (statex);
		GlobalMemoryStatusEx(&statex);
		writeLog(QString("Total physical memory: %1 MB").arg(statex.ullTotalPhys/(1024<<10)));
		writeLog(QString("Available physical memory: %1 MB").arg(statex.ullAvailPhys/(1024<<10)));
		writeLog(QString("Physical memory in use: %1%").arg(statex.dwMemoryLoad));
		#ifndef _WIN64
		// This always reports about 8TB on Win64, not really useful to show.
		writeLog(QString("Total virtual memory: %1 MB").arg(statex.ullTotalVirtual/(1024<<10)));
		writeLog(QString("Available virtual memory: %1 MB").arg(statex.ullAvailVirtual/(1024<<10)));
		#endif
	}
	else
		writeLog("Windows version too old to get memory info.");

	HKEY hKey = NULL;
	DWORD dwType = REG_DWORD;
	DWORD numVal = 0;
	DWORD dwSize = sizeof(numVal);

	// iterate over the processors listed in the registry
	QString procKey = "Hardware\\Description\\System\\CentralProcessor";
	LONG lRet = ERROR_SUCCESS;
	int i;
	for(i = 0; lRet == ERROR_SUCCESS; i++)
	{
		lRet = RegOpenKeyExA(HKEY_LOCAL_MACHINE,
					qPrintable(QString("%1\\%2").arg(procKey).arg(i)),
					0, KEY_QUERY_VALUE, &hKey);

		if(lRet == ERROR_SUCCESS)
		{
			if(RegQueryValueExA(hKey, "~MHz", NULL, &dwType, (LPBYTE)&numVal, &dwSize) == ERROR_SUCCESS)
				writeLog(QString("Processor speed: %1 MHz").arg(numVal));
			else
				writeLog("Could not get processor speed.");
		}

		// can you believe this trash?
		dwType = REG_SZ;
		char nameStr[512];
		DWORD nameSize = sizeof(nameStr);

		if (lRet == ERROR_SUCCESS)
		{
			if (RegQueryValueExA(hKey, "ProcessorNameString", NULL, &dwType, (LPBYTE)&nameStr, &nameSize) == ERROR_SUCCESS)
				writeLog(QString("Processor name: %1").arg(nameStr));
			else
				writeLog("Could not get processor name.");
		}

		RegCloseKey(hKey);
	}
	if(i == 0)
		writeLog("Could not get processor info.");

#elif defined Q_OS_MAC
	QProcess systemProfiler;
	systemProfiler.start("/usr/sbin/system_profiler -detailLevel mini SPHardwareDataType SPDisplaysDataType");
	systemProfiler.waitForStarted();
	systemProfiler.waitForFinished();
	const QString systemData(systemProfiler.readAllStandardOutput());
	QStringList systemLines = systemData.split('\n', QString::SkipEmptyParts);
	for (int i = 0; i<systemLines.size(); i++)
	{
		if(systemLines.at(i).contains("Model"))
		{
			writeLog(systemLines.at(i).trimmed());
		}

		if(systemLines.at(i).contains("Processor"))
		{
			writeLog(systemLines.at(i).trimmed());
		}

		if(systemLines.at(i).contains("Memory"))
		{
			writeLog(systemLines.at(i).trimmed());
		}

		if(systemLines.at(i).contains("VRAM"))
		{
			writeLog(systemLines.at(i).trimmed());
		}

	}

#elif defined Q_OS_BSD4
	QProcess dmesg;
	dmesg.start("/sbin/dmesg", QIODevice::ReadOnly);
	dmesg.waitForStarted();
	dmesg.waitForFinished();
	const QString dmesgData(dmesg.readAll());
	QStringList dmesgLines = dmesgData.split('\n', QString::SkipEmptyParts);
	for (int i = 0; i<dmesgLines.size(); i++)
	{
		if (dmesgLines.at(i).contains("memory"))
		{
			writeLog(dmesgLines.at(i).trimmed());
		}
		if (dmesgLines.at(i).contains("CPU"))
		{
			writeLog(dmesgLines.at(i).trimmed());
		}
		if (dmesgLines.at(i).contains("VGA"))
		{
			writeLog(dmesgLines.at(i).trimmed());
		}
	}

#endif
}
Example #27
0
/* Take the ENML note and transform it into HTML that WebKit will
  not complain about */
QByteArray EnmlFormatter::rebuildNoteEnml() {
    resources.clear();
    QByteArray b;
    qint32 index;

    content.replace("</input>","");

    // Strip off HTML header
    index = content.indexOf("<body");
    index = content.indexOf(">", index)+1;
    content.remove(0,index);
    index = content.indexOf("</body");
    content.truncate(index);
    b.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
    b.append("<!DOCTYPE en-note SYSTEM 'http://xml.evernote.com/pub/enml2.dtd'>\n");
    b.append("<html><head><title></title></head>");
    b.append("<body style=\"word-wrap: break-word; -webkit-nbsp-mode: space; -webkit-line-break: after-white-space;\" >");
    b.append(content);
    b.append("</body></html>");
    content.clear();
    content = b;

    // Run it through "tidy".  It is a program which will fix any invalid HTML
    // and give us the results back through stdout.  In a perfect world this
    // wouldn't be needed, but WebKit doesn't always give back good HTML.
    QProcess tidyProcess;
    tidyProcess.start("tidy -raw -asxhtml -q -m -u -utf8 ", QIODevice::ReadWrite|QIODevice::Unbuffered);
    QLOG_DEBUG() << "Starting tidy " << tidyProcess.waitForStarted();
    tidyProcess.waitForStarted();
    tidyProcess.write(content);
    tidyProcess.closeWriteChannel();
    tidyProcess.waitForFinished();
    QLOG_DEBUG() << "Stopping tidy " << tidyProcess.waitForFinished() << " Return Code: " << tidyProcess.state();
    QLOG_DEBUG() << "Tidy Errors:" << tidyProcess.readAllStandardError();
    content.clear();
    content.append(tidyProcess.readAllStandardOutput());
    if (content == "") {
        formattingError = true;
        return "";
    }

    // Tidy puts this in place, but we don't really need it.
    content.replace("<form>", "");
    content.replace("</form>", "");

    index = content.indexOf("<body");
    content.remove(0,index);
    content.prepend("<style>img { height:auto; width:auto; max-height:auto; max-width:100%; }</style>");
    content.prepend("<head><meta http-equiv=\"content-type\" content=\"text-html; charset=utf-8\"></head>");
    content.prepend("<html>");
    content.append("</html>");
    content = fixEncryptionTags(content);

    QWebPage page;
    QEventLoop loop;
    page.mainFrame()->setContent(content);
    QObject::connect(&page, SIGNAL(loadFinished(bool)), &loop, SLOT(quit()));


    QWebElement element = page.mainFrame()->documentElement();
    QStringList tags = findAllTags(element);

    for (int i=0; i<tags.size(); i++) {
        QString tag = tags[i];
        QWebElementCollection anchors = page.mainFrame()->findAllElements(tag);
        foreach (QWebElement element, anchors) {
            if (element.tagName().toLower() == "input") {
                processTodo(element);
            } else if (element.tagName().toLower() == "a") {
                fixLinkNode(element);
            } else if (element.tagName().toLower() == "object") {
                fixObjectNode(element);
            } else if (element.tagName().toLower() == "img") {
                fixImgNode(element);
            } else if (!isElementValid(element.tagName()))
                element.removeFromDocument();
        }
    }
    content.clear();
    content.append(element.toOuterXml());

    // Strip off HTML header
    index = content.indexOf("<body");
    index = content.indexOf(">", index)+1;
    content.remove(0,index);
    index = content.indexOf("</body");
    content.truncate(index);
    b.clear();
    b.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
    b.append("<!DOCTYPE en-note SYSTEM 'http://xml.evernote.com/pub/enml2.dtd'>");
    b.append("<en-note style=\"word-wrap: break-word; -webkit-nbsp-mode: space; -webkit-line-break: after-white-space;\" >");
    b.append(content);
    b.append("</en-note>");
    content.clear();
    content = b;

    postXmlFix();
    return content;
}
Example #28
0
  ExitCodes main_(int, const char**) override
  {
    String tmp_dir = QDir::toNativeSeparators((File::getTempDirectory() + "/" + File::getUniqueName() + "/").toQString()); // body for the tmp files
    {
      QDir d;
      d.mkpath(tmp_dir.toQString());
    }
    String logfile(getStringOption_("log"));
    String myrimatch_executable(getStringOption_("myrimatch_executable"));

    //-------------------------------------------------------------
    // get version of MyriMatch
    //-------------------------------------------------------------

    QProcess qp;
    String myrimatch_version;
    MyriMatchVersion myrimatch_version_i;

    // we invoke myrimatch w/o arguments. that yields a return code != 0. but
    // there is no other way for version 2.1 to get the version number
    qp.start(myrimatch_executable.toQString(), QStringList(), QIODevice::ReadOnly); // does automatic escaping etc...
    qp.waitForFinished();
    String output(QString(qp.readAllStandardOutput()));

    vector<String> lines;
    vector<String> version_split;
    output.split('\n', lines);

    // the version number is expected to be in the second line
    if (lines.size() < 2)
    {
      writeLog_("Warning: MyriMatch version output (" + output + ") not formatted as expected!");
      return EXTERNAL_PROGRAM_ERROR;
    }

    // the version is expected to be something like:
    // MyriMatch 2.1.111 (2011-12-27)
    lines[1].split(' ', version_split);
    if (version_split.size() == 3 && getVersion_(version_split[1], myrimatch_version_i))
    {
      myrimatch_version = version_split[1].removeWhitespaces();
      writeDebug_("Setting MyriMatch version to " + myrimatch_version, 1);
    }
    else
    {
      writeLog_("Warning: MyriMatch version output (" + output + ") not formatted as expected!");
      return EXTERNAL_PROGRAM_ERROR;
    }
    if (! (   (myrimatch_version_i.myrimatch_major == 2) &&  // major must be 2
              (myrimatch_version_i.myrimatch_minor == 1 || myrimatch_version_i.myrimatch_minor == 2) // minor .1 or .2
          ))
    {
      writeLog_("Warning: unsupported MyriMatch version (" + myrimatch_version + "). Tested only for MyriMatch 2.1.x and 2.2.x."
                "\nIf you encounter parameter errors, you can try the flag 'ignoreConfigErrors', but be aware that MyriMatch might be misconfigured.");
    }

    //-------------------------------------------------------------
    // parsing parameters
    //-------------------------------------------------------------

    String inputfile_name = File::absolutePath(getStringOption_("in"));
    String outputfile_name = getStringOption_("out");
    String db_name = File::absolutePath(String(getStringOption_("database")));

    // building parameter String
    StringList parameters;

    if (getFlag_("ignoreConfigErrors")) parameters << "-ignoreConfigErrors";

    // Common Identification engine options
    StringList static_mod_list;
    StringList dynamic_mod_list;
    translateModifications(static_mod_list, dynamic_mod_list);
    if (!static_mod_list.empty())
      parameters << "-StaticMods" << ListUtils::concatenate(static_mod_list, " ");
    if (!dynamic_mod_list.empty())
      parameters << "-DynamicMods" << ListUtils::concatenate(dynamic_mod_list, " ");

    parameters << "-ProteinDatabase"  << File::absolutePath(db_name);

    if (getFlag_("precursor_mass_tolerance_avg"))
    {
      parameters << "-AvgPrecursorMzTolerance";
    }
    else
    {
      parameters << "-MonoPrecursorMzTolerance";
    }
    String precursor_mass_tolerance_unit = getStringOption_("precursor_mass_tolerance_unit") == "Da" ? " m/z" : " ppm";
    parameters << String(getDoubleOption_("precursor_mass_tolerance")) + precursor_mass_tolerance_unit;

    String fragment_mass_tolerance_unit = getStringOption_("fragment_mass_tolerance_unit");
    if (fragment_mass_tolerance_unit == "Da")
    {
      fragment_mass_tolerance_unit = "m/z";
    }

    parameters << "-FragmentMzTolerance" << String(getDoubleOption_("fragment_mass_tolerance")) + " " + fragment_mass_tolerance_unit;

    StringList slf = getStringList_("SpectrumListFilters");
    if (slf.size() > 0) 
    {
      if (myrimatch_version_i.myrimatch_minor <= 1)
      { // use quotes around the slf arguments (will be added automatically by Qt during call), i.e. "-SpectrumListFilters" "peakPicking false 2-"
        parameters << "-SpectrumListFilters" << ListUtils::concatenate(slf, ";") << "";
      }
      else
      { // no quotes -- pass a single argument, i.e. "-SpectrumListFilters peakPicking false 2-"
        parameters << "-SpectrumListFilters " + ListUtils::concatenate(slf, ";") << "";
      }
      
    }
    //parameters << "-ThreadCountMultiplier" << String(getIntOption_("threads")); // MyriMatch does not recognise this, even though it's in the manual.

    // MyriMatch specific parameters
    parameters << "-NumChargeStates" << getIntOption_("NumChargeStates");
    parameters << "-TicCutoffPercentage" << String(getDoubleOption_("TicCutoffPercentage"));
    parameters << "-MaxDynamicMods" << getIntOption_("MaxDynamicMods");
    parameters << "-MaxResultRank" << getIntOption_("MaxResultRank");
    parameters << "-MinTerminiCleavages" << getIntOption_("MinTerminiCleavages");
    parameters << "-MaxMissedCleavages" << getIntOption_("MaxMissedCleavages");
    String cleavage_rule = getStringOption_("CleavageRules");
    if (cleavage_rule.empty())
    {
      cleavage_rule = "Trypsin/P";
    }
    parameters << "-CleavageRules" << cleavage_rule;

    // advanced parameters
    parameters << "-MinPeptideMass"   << getDoubleOption_("MinPeptideMass");
    parameters << "-MaxPeptideMass"   << getDoubleOption_("MaxPeptideMass");
    parameters << "-MinPeptideLength" << getIntOption_("MinPeptideLength");
    parameters << "-MaxPeptideLength" << getIntOption_("MaxPeptideLength");
    parameters << "-NumIntensityClasses" << getIntOption_("NumIntensityClasses");
    parameters << "-ClassSizeMultiplier" << getDoubleOption_("ClassSizeMultiplier");
    parameters << "-MonoisotopeAdjustmentSet" << getStringOption_("MonoisotopeAdjustmentSet");
    parameters << "-cpus" << getIntOption_("threads");


    // Constant parameters

    // DecoyPrefix worked only when set through the config file
    String cfg_file = tmp_dir + "myrimatch.cfg";
    ofstream f(cfg_file.c_str());
    f << "DecoyPrefix=\"\"\n";
    f.close();
    parameters << "-cfg" << cfg_file;

    // path to input file must be the last parameter
    parameters << inputfile_name;

    //-------------------------------------------------------------
    // calculations
    //-------------------------------------------------------------
    QStringList qparam;
    writeDebug_("MyriMatch arguments:", 1);
    writeDebug_(String("\"") + ListUtils::concatenate(parameters, "\" \"") + "\"", 1);
    for (Size i = 0; i < parameters.size(); ++i)
    {
      qparam << parameters[i].toQString();
    }
    QProcess process;

    // Bad style, because it breaks relative paths?
    process.setWorkingDirectory(tmp_dir.toQString());

    process.start(myrimatch_executable.toQString(), qparam, QIODevice::ReadOnly);
    bool success = process.waitForFinished(-1);
    String myri_msg(QString(process.readAllStandardOutput()));
    String myri_err(QString(process.readAllStandardError()));
    writeDebug_(myri_msg, 1);
    writeDebug_(myri_err, 0);
    if (!success || process.exitStatus() != 0 || process.exitCode() != 0)
    {
      writeLog_("Error: MyriMatch problem! (Details can be seen in the logfile: \"" + logfile + "\")");
      writeLog_("Note: This message can also be triggered if you run out of space in your tmp directory");
      return EXTERNAL_PROGRAM_ERROR;
    }

    //-------------------------------------------------------------
    // reading MyriMatch output
    //-------------------------------------------------------------

    writeDebug_("Reading output of MyriMatch", 5);
    String exp_name = File::basename(inputfile_name);
    String pep_file = tmp_dir + File::removeExtension(exp_name) + ".pepXML";

    vector<ProteinIdentification> protein_identifications;
    vector<PeptideIdentification> peptide_identifications;

    PeakMap exp;
    if (File::exists(pep_file))
    {
      MzMLFile fh;
      fh.load(inputfile_name, exp);

      SpectrumMetaDataLookup lookup;
      lookup.readSpectra(exp.getSpectra());
      PepXMLFile().load(pep_file, protein_identifications,
                        peptide_identifications, exp_name, lookup);
    }
    else
    {
      writeLog_("Error: MyriMatch problem! No pepXML output file (expected as '" + pep_file + "') was generated by MyriMatch.");
      writeLog_("Note: This message can be triggered if no MS2 spectra were found or no identifications were made.");
      writeLog_("      Myrimatch expects MS2 spectra in mzML files to contain the MSn tag. MSSpectrum with MS level 2 is not sufficient. You can use FileConverter to create such an mzML file by converting from mzML --> mzXML --> mzML.");
      return EXTERNAL_PROGRAM_ERROR;
    }

    if (debug_level_ == 0)
    {
      QFile(pep_file.toQString()).remove();
      QFile(cfg_file.toQString()).remove();
    }
    else
    {
      writeDebug_(String("Not removing '") + pep_file + "' for debugging purposes. Please delete manually!", 1);
      writeDebug_(String("Not removing '") + cfg_file + "' for debugging purposes. Please delete manually!", 1);
    }
    //-------------------------------------------------------------
    // writing results
    //-------------------------------------------------------------
    ProteinIdentification::SearchParameters search_parameters;
    search_parameters.db = getStringOption_("database");
    ProteinIdentification::PeakMassType mass_type = getFlag_("precursor_mass_tolerance_avg") == true ? ProteinIdentification::AVERAGE : ProteinIdentification::MONOISOTOPIC;
    search_parameters.mass_type = mass_type;
    search_parameters.fixed_modifications = getStringList_("fixed_modifications");
    search_parameters.variable_modifications = getStringList_("variable_modifications");
    search_parameters.missed_cleavages = getIntOption_("MaxMissedCleavages");
    search_parameters.fragment_mass_tolerance = getDoubleOption_("fragment_mass_tolerance");
    search_parameters.precursor_mass_tolerance = getDoubleOption_("precursor_mass_tolerance");
    search_parameters.precursor_mass_tolerance_ppm = getStringOption_("precursor_mass_tolerance_unit") == "ppm" ? true : false;
    search_parameters.fragment_mass_tolerance_ppm = getStringOption_("fragment_mass_tolerance_unit") == "ppm" ? true : false;
    protein_identifications[0].setSearchParameters(search_parameters);
    protein_identifications[0].setSearchEngineVersion(myrimatch_version);
    protein_identifications[0].setSearchEngine("MyriMatch");

    if (!protein_identifications.empty())
    {
      StringList ms_runs;
      exp.getPrimaryMSRunPath(ms_runs);
      protein_identifications[0].setPrimaryMSRunPath(ms_runs);
    }
    IdXMLFile().store(outputfile_name, protein_identifications, peptide_identifications);
    return EXECUTION_OK;
  }
Example #29
0
// Index any resources
void IndexRunner::indexRecognition(qint32 lid, Resource &r) {

    if (!keepRunning || pauseIndexing) {
        //indexTimer->start();
        return;
    }

    // Add filename or source url to search index
    if (r.attributes.isSet()) {
        NSqlQuery sql(db);
        ResourceAttributes a = r.attributes;
        if (a.fileName.isSet()) {
            sql.prepare("Insert into SearchIndex (lid, weight, source, content) values (:lid, :weight, :source, :content)");
            sql.bindValue(":lid", lid);
            sql.bindValue(":weight", 100);
            sql.bindValue(":source", "recognition");
            sql.bindValue(":content", QString(a.fileName));
            sql.exec();
        }
        if (a.sourceURL.isSet()) {
            sql.prepare("Insert into SearchIndex (lid, weight, source, content) values (:lid, :weight, :source, :content)");
            sql.bindValue(":lid", lid);
            sql.bindValue(":weight", 100);
            sql.bindValue(":source", "recognition");
            sql.bindValue(":content", QString(a.sourceURL));
            sql.exec();
        }
    }


    // Make sure we have something to look through.
    Data recognition;
    if (r.recognition.isSet())
        recognition = r.recognition;
    if (!recognition.body.isSet())
        return;

    QDomDocument doc;
    QString emsg;
    doc.setContent(recognition.body, &emsg);

    // look for text tags
    QDomNodeList anchors = doc.documentElement().elementsByTagName("t");
#if QT_VERSION < 0x050000
    for (unsigned int i=0; keepRunning && !pauseIndexing && i<anchors.length(); i++) {
#else
    for (int i=0; keepRunning && !pauseIndexing && i<anchors.length(); i++) {
#endif
        QApplication::processEvents();
        QDomElement enmedia = anchors.at(i).toElement();
        QString weight = enmedia.attribute("w");
        QString text = enmedia.text();
        if (text != "") {
            IndexRecord *rec = new IndexRecord();
            rec->weight = weight.toInt();
            rec->lid = lid;
            rec->content = text;
            rec->source = "recognition";
            if (indexHash->contains(lid)) {
                delete indexHash->value(lid);
                indexHash->remove(lid);
            }
            indexHash->insert(lid, rec);
        }
    }
}


// Index any PDFs that are attached.  Basically it turns the PDF into text and adds it the same
// way as a note's body
void IndexRunner::indexPdf(qint32 lid, Resource &r) {
    if (!global.indexPDFLocally)
        return;
    if (!keepRunning || pauseIndexing) {
        //indexTimer->start();
        return;
    }
    ResourceTable rtable(db);
    qint32 reslid = rtable.getLid(r.guid);
    if (lid <= 0) {
        //indexTimer->start();
        return;
    }
    QString file = global.fileManager.getDbaDirPath() + QString::number(reslid) +".pdf";

    QString text = "";
    Poppler::Document *doc = Poppler::Document::load(file);
    if (doc == nullptr || doc->isEncrypted() || doc->isLocked()) {
        //indexTimer->start();
        return;
    }
    for (int i=0; keepRunning && !pauseIndexing && i<doc->numPages(); i++) {
        QRectF rect;
        text = text + doc->page(i)->text(rect) + QString(" ");
    }
    IndexRecord *rec = new IndexRecord();
    rec->content = text;
    rec->source = "recognition";
    rec->weight = 100;
    rec->lid = lid;
    if (indexHash->contains(lid)) {
        delete indexHash->value(lid);
        indexHash->remove(lid);
    }
    indexHash->insert(lid, rec);
}




// Index any files that are attached.
void IndexRunner::indexAttachment(qint32 lid, Resource &r) {
    if (!officeFound)
        return;
    QLOG_DEBUG() << "indexing attachment to note " << lid;
    if (!keepRunning || pauseIndexing) {
        //indexTimer->start();
        return;
    }
    ResourceTable rtable(db);
    qint32 reslid = rtable.getLid(r.guid);
    if (lid <= 0) {
        //indexTimer->start();
        return;
    }
    QLOG_DEBUG() << "Resource " << reslid;
    QString extension = "";
    ResourceAttributes attributes;
    if (r.attributes.isSet())
        attributes = r.attributes;
    if (attributes.fileName.isSet()) {
        extension = attributes.fileName;
        int i = extension.indexOf(".");
	if (i != -1)
	  extension = extension.mid(i);
    }
    if (extension != ".doc"  && extension != ".xls"  && extension != ".ppt" &&
        extension != ".docx" && extension != ".xlsx" && extension != ".pptx" &&
        extension != ".pps"  && extension != ".pdf"  && extension != ".odt"  &&
        extension != ".odf"  && extension != ".ott"  && extension != ".odm"  &&
        extension != ".html" && extension != ".txt"  && extension != ".oth"  &&
        extension != ".ods"  && extension != ".ots"  && extension != ".odg"  &&
        extension != ".otg"  && extension != ".odp"  && extension != ".otp"  &&
        extension != ".odb"  && extension != ".oxt"  && extension != ".htm"  &&
        extension != ".docm")
                return;

    QString file = global.fileManager.getDbaDirPath() + QString::number(reslid) +extension;
    QFile dataFile(file);
    if (!dataFile.exists()) {
        QDir dir(global.fileManager.getDbaDirPath());
        QStringList filterList;
        filterList.append(QString::number(lid)+".*");
        QStringList list= dir.entryList(filterList, QDir::Files);
        if (list.size() > 0) {
            file = global.fileManager.getDbaDirPath()+list[0];
        }
    }

    QString outDir = global.fileManager.getTmpDirPath();

    QProcess sofficeProcess;
    QString cmd = "soffice --headless --convert-to txt:\"Text\" --outdir "
                    +outDir + " "
                    +file;

    sofficeProcess.start(cmd,
                         QIODevice::ReadWrite|QIODevice::Unbuffered);

    QLOG_DEBUG() << "Starting soffice ";
    sofficeProcess.waitForStarted();
    QLOG_DEBUG() << "Waiting for completion";
    sofficeProcess.waitForFinished();
    int rc = sofficeProcess.exitCode();
    QLOG_DEBUG() << "soffice Errors:" << sofficeProcess.readAllStandardError();
    QLOG_DEBUG() << "soffice Output:" << sofficeProcess.readAllStandardOutput();
    QLOG_DEBUG() << "return code:" << rc;
    if (rc == 255) {
        QLOG_ERROR() << "soffice not found.  Disabling attachment indexing.";
        this->officeFound = false;
        return;
    }
    QFile txtFile(outDir+QString::number(reslid) +".txt");
    if (txtFile.open(QIODevice::ReadOnly)) {
        QString text;
        text = txtFile.readAll();
        NSqlQuery sql(db);
        db->lockForWrite();
        sql.prepare("Insert into SearchIndex (lid, weight, source, content) values (:lid, :weight, 'recognition', :content)");
        sql.bindValue(":lid", lid);
        sql.bindValue(":weight", 100);

        text = global.normalizeTermForSearchAndIndex(text);
        sql.bindValue(":content", text);

        QLOG_DEBUG() << "Adding note resource to index DB";
        sql.exec();
        db->unlock();
        txtFile.close();
    }
    QDir dir;
    dir.remove(outDir+QString::number(reslid) +".txt");
}


void IndexRunner::flushCache() {
    if (indexHash->size() <= 0)
        return;
    QDateTime start = QDateTime::currentDateTimeUtc();
    NSqlQuery sql(db);
    db->lockForWrite();
    sql.exec("begin");
    QHash<qint32, IndexRecord*>::iterator i;

    // Start adding words to the index.  Every 200 sql insertions we do a commit
    int commitCount = 200;

    for (i=indexHash->begin(); keepRunning && !pauseIndexing && i!=indexHash->end(); ++i) {
        qint32 lid = i.key();
        IndexRecord *rec = i.value();
        qint32 weight = rec->weight;
        QString source = rec->source;
        QString content = rec->content;
        delete rec;

        // Delete any old content
        sql.prepare("Delete from SearchIndex where lid=:lid and source=:source");
        sql.bindValue(":lid", lid);
        sql.bindValue(":source", source);
        sql.exec();

        // Add the new content.  it is basically a text version of the note with a weight of 100.
        sql.prepare("Insert into SearchIndex (lid, weight, source, content) values (:lid, :weight, :source, :content)");
        sql.bindValue(":lid", lid);
        sql.bindValue(":weight", weight);
        sql.bindValue(":source", source);

        content = global.normalizeTermForSearchAndIndex(content);
        sql.bindValue(":content", content);

        sql.exec();
        commitCount--;
        if (commitCount <= 0) {
            sql.exec("commit");
            commitCount = 200;
        }
    }
    indexHash->clear();
    sql.exec("commit");

    sql.finish();
    db->unlock();
    QDateTime finish = QDateTime::currentDateTimeUtc();

    QLOG_DEBUG() << "Index Cache Flush Complete: " <<
                    finish.toMSecsSinceEpoch() - start.toMSecsSinceEpoch()
                    << " milliseconds.";
}



void IndexRunner::busy(bool value, bool finished) {
    iAmBusy=value;
    emit(this->indexDone(finished));
}
Example #30
0
bool AssignmentThread::traditionalTaskPrepare()
{
    compileState = NoValidSourceFile;
    QDir contestantDir = QDir(Settings::sourcePath() + contestantName);
    QList<Compiler*> compilerList = settings->getCompilerList();
    
    for (int i = 0; i < compilerList.size(); i ++) {
        if (task->getCompilerConfiguration(compilerList[i]->getCompilerName()) == "disable") continue;
        QStringList filters = compilerList[i]->getSourceExtensions();
        for (int j = 0; j < filters.size(); j ++) {
            filters[j] = task->getSourceFileName() + "." + filters[j];
        }
        QStringList files = contestantDir.entryList(filters, QDir::Files);
        sourceFile = "";
        for (int j = 0; j < files.size(); j ++) {
            qint64 fileSize = QFileInfo(Settings::sourcePath() + contestantName + QDir::separator() + files[j]).size();
            if (fileSize <= settings->getFileSizeLimit() * 1024) {
                sourceFile = files[j];
                break;
            }
        }
        
        if (! sourceFile.isEmpty()) {
            QDir(Settings::temporaryPath()).mkdir(contestantName);
            QFile::copy(Settings::sourcePath() + contestantName + QDir::separator() + sourceFile,
                        Settings::temporaryPath() + contestantName + QDir::separator() + sourceFile);
            QStringList configurationNames = compilerList[i]->getConfigurationNames();
            QStringList compilerArguments = compilerList[i]->getCompilerArguments();
            QStringList interpreterArguments = compilerList[i]->getInterpreterArguments();
            QString currentConfiguration = task->getCompilerConfiguration(compilerList[i]->getCompilerName());
            for (int j = 0; j < configurationNames.size(); j ++) {
                if (configurationNames[j] == currentConfiguration) {
                    timeLimitRatio = compilerList[i]->getTimeLimitRatio();
                    memoryLimitRatio = compilerList[i]->getMemoryLimitRatio();
                    disableMemoryLimitCheck = compilerList[i]->getDisableMemoryLimitCheck();
                    environment = compilerList[i]->getEnvironment();
                    QStringList values = environment.toStringList();
                    for (int k = 0; k < values.size(); k ++) {
                        int tmp = values[k].indexOf("=");
                        QString variable = values[k].mid(0, tmp);
                        environment.insert(variable, 
                                           environment.value(variable) + ";"
                                           + QProcessEnvironment::systemEnvironment().value(variable));
                    }
                    
                    if (compilerList[i]->getCompilerType() == Compiler::Typical) {
#ifdef Q_OS_WIN32
                                executableFile = task->getSourceFileName() + ".exe";
#endif
#ifdef Q_OS_LINUX
                                executableFile = task->getSourceFileName();
#endif
                                interpreterFlag = false;
                    } else {
                        executableFile = compilerList[i]->getInterpreterLocation();
                        arguments = interpreterArguments[j];
                        arguments.replace("%s.*", sourceFile);
                        arguments.replace("%s", task->getSourceFileName());
                        interpreterFlag = true;
                    }
                    
                    if (compilerList[i]->getCompilerType() != Compiler::InterpretiveWithoutByteCode) {
                        QString arguments = compilerArguments[j];
                        arguments.replace("%s.*", sourceFile);
                        arguments.replace("%s", task->getSourceFileName());
                        QProcess *compiler = new QProcess(this);
                        compiler->setProcessChannelMode(QProcess::MergedChannels);
                        compiler->setProcessEnvironment(environment);
                        compiler->setWorkingDirectory(Settings::temporaryPath() + contestantName);
                        compiler->start(QString("\"") + compilerList[i]->getCompilerLocation() + "\" " + arguments);
                        if (! compiler->waitForStarted(-1)) {
                            compileState = InvalidCompiler;
                            delete compiler;
                            break;
                        }
                        QElapsedTimer timer;
                        timer.start();
                        bool flag = false;
                        while (timer.elapsed() < settings->getCompileTimeLimit()) {
                            if (compiler->state() != QProcess::Running) {
                                flag = true;
                                break;
                            }
                            QCoreApplication::processEvents();
                            if (stopJudging) {
                                compiler->kill();
                                delete compiler;
                                return false;
                            }
                            msleep(10);
                        }
                        if (! flag) {
                            compiler->kill();
                            compileState = CompileTimeLimitExceeded;
                        } else
                            if (compiler->exitCode() != 0) {
                                compileState = CompileError;
                                compileMessage = QString::fromLocal8Bit(compiler->readAllStandardOutput().data());
                            } else {
                                if (compilerList[i]->getCompilerType() == Compiler::Typical) {
                                    if (! QDir(Settings::temporaryPath() + contestantName).exists(executableFile)) {
                                        compileState = InvalidCompiler;
                                    } else {
                                        compileState = CompileSuccessfully;
                                    }
                                } else {
                                    QStringList filters = compilerList[i]->getBytecodeExtensions();
                                    for (int k = 0; k < filters.size(); k ++) {
                                        filters[k] = QString("*.") + filters[k];
                                    }
                                    if (QDir(Settings::temporaryPath() + contestantName)
                                            .entryList(filters, QDir::Files).size() == 0) {
                                        compileState = InvalidCompiler;
                                    } else {
                                        compileState = CompileSuccessfully;
                                    }
                                }
                            }
                        delete compiler;
                    }
                    
                    if (compilerList[i]->getCompilerType() == Compiler::InterpretiveWithoutByteCode)
                        compileState = CompileSuccessfully;
                    
                    break;
                }
            }
            break;
        }
    }
    
    if (compileState != CompileSuccessfully) {
        emit compileError(task->getTotalTimeLimit(), (int)compileState);
        return false;
    }
    
    return true;
}