Example #1
0
int IDAService::MatchPersonRFID(QString rfid_info, QString timeout, QString db_name)
{
    QString app_name = "IDADesktopConsole.exe";
    QStringList arguments;
    arguments << "-m" << "MatchPersonRFID";
    arguments << "-u" << "NG";
    arguments << "-w" << app_dir+"/";
    arguments << "-d" << db_name;
    arguments << "-r" << rfid_info;

    QProcess proc;
    proc.start(app_name,arguments);

    // Wait for process start
    if(!proc.waitForStarted()){
        qDebug()<<"process start failed";
        emit MatchPersonRFIDFinished("NG");
        return 1;
    }

    // Close write channel because we do not need it
    proc.closeWriteChannel();

    QByteArray proc_output;
    while (false == proc.waitForFinished())
    {
       qDebug()<<"Process finish failed";
       emit MatchPersonRFIDFinished("NG");
       return 1;
    }

    proc_output = proc.readAll();
    qDebug()<<proc_output;
    //emit MatchPersonImageFinished(proc_output);
    emit MatchPersonRFIDFinished(proc_output);
    return 0;
}
Example #2
0
int IDAService::ShowAllUsername(QString db_name)
{
    qDebug()<<"enter showAllUsername";
    QString app_name = "IDADesktopConsole.exe";
    QStringList arguments;
    arguments << "-m" << "ShowAllUsername";
    arguments << "-w" << app_dir+"/";
    arguments << "-d" << db_name;

    QProcess proc;
    proc.start(app_name,arguments);

    // Wait for process start
    if(!proc.waitForStarted()){
        qDebug()<<"process start failed";
        emit ShowAllUsernameFinished("NG");
        return 1;
    }

    // Close write channel because we do not need it
    proc.closeWriteChannel();

    QByteArray proc_output;
    while (false == proc.waitForFinished())
    {
       qDebug()<<"Process finish failed";
       emit ShowAllUsernameFinished(proc_output);
       return 1;
    }

    proc_output = proc.readAll();
    qDebug()<<proc_output;
     emit ShowAllUsernameFinished(proc_output);
    return 0;

}
Example #3
0
int IDAService::MatchPersonImage(unsigned int image_index, float threshold, QString db_name)
{

    QString app_name = "IDADesktopConsole.exe";
    QStringList arguments;
    QString image_file_name = QString::number(image_index,10)+".bmp";
    arguments << "-m" << "MatchPersonImage";
    arguments << "-i" << image_file_name;
    arguments << "-u" << "NG";
    arguments << "-w" << app_dir+"/";
    arguments << "-d" << db_name;
    arguments << "-t" << QString::number((int)threshold,10);
    QProcess proc;
    proc.start(app_name,arguments);

    // Wait for process start
    if(!proc.waitForStarted()){
        qDebug()<<"process start failed";
        return 1;
    }

    // Close write channel because we do not need it
    proc.closeWriteChannel();

    QByteArray proc_output;
    while (false == proc.waitForFinished())
    {
       qDebug()<<"Process finish failed";
       return 1;
    }

    proc_output = proc.readAll();
    emit MatchPersonImageFinished(proc_output);
    qDebug()<<proc_output;
    return 0;
}
Example #4
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;
}
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 #6
0
QString FsInfo::GetFilesystem( QString path )
{
    QProcess p;
#ifdef Q_WS_WIN
    bool ok = false;
    QString drive = ToWinPath( path, &ok );
    int colon = drive.indexOf( ":" );
    if( colon != 1 || !ok )
    {
		qCritical() << "FsInfo::GetFilesystem() colon != 1" << colon << ok;
		return QString();
    }
    drive.resize( 1 );

    p.start( "wmic", QStringList() << "/output:stdout" << "/interactive:off" << "/locale:ms_409" <<\
			 "logicaldisk" << "where" << "DeviceID=\'" + drive + ":\'" << "get" << "filesystem" );
#elif defined Q_WS_MAC
    p.start( "diskutil", QStringList() << "info" << path );
#else
    //try statfs first as it is the fastest.  but its descriptors are less than descriptive for ext variants
    struct statfs fInfo;
    int r = statfs( path.toLatin1().data(), &fInfo );
    if( !r )
    {
		switch( fInfo.f_type )
		{
		case MSDOS_SUPER_MAGIC:
			return "FAT";
			break;
		case NTFS_SB_MAGIC:
		case NTFS_PUNE_MAGIC:
			return "NTFS";
			break;
		case HFS_SUPER_MAGIC:
		case HPFS_SUPER_MAGIC:
			return "HPFS";
			break;
		default:
			break;
		}
    }
    p.start( "df", QStringList() << "-T" << path );
#endif
    if( !p.waitForStarted( 5000 ) )
    {
		qCritical() << "FsInfo::GetFilesystem failed to start";
		return QString();
    }
    p.closeWriteChannel();

    if( !p.waitForFinished() )
    {
		qCritical() << "!p.waitForFinished() ( getfs )";
		return QString();
    }
    if( p.exitCode() != QProcess::NormalExit )
    {
		qCritical() << "exit status ( getfs )" << p.exitCode();
		return QString();
    }

    QString output = p.readAll();
    output.remove( "\r" );
    QStringList list = output.split( "\n", QString::SkipEmptyParts );
#ifdef Q_WS_WIN
    if( !list.contains( "FileSystem  " ) || list.size() != 2 )
    {
		qCritical() << "wrong output ( getfs )" << list;
		return QString();
    }
    QString fs = list.at( 1 );
    fs = fs.simplified();
    return fs;
#elif defined Q_WS_MAC
    int size = list.size();
    for( int i = 0; i < size; i++ )
    {
		if( !list.at( i ).contains( "File System:" ) )
			continue;

		QString fs = list.at( i );
		fs.remove( 0, fs.indexOf( "File System:" ) + 12 );
		fs = fs.trimmed();
		int space = fs.indexOf( " " );
		if( space > 0 )
		{
			fs.remove( 0, space + 1 );
		}
		//qDebug() << fs;
		return fs;
    }
    return  QString();
#else
    int size = list.size();
    if( size != 2 )
    {
		qCritical() << "size != 2 ( getfs )" << list;
		return QString();
    }
    QString fs = list.at( 1 );
    fs = fs.simplified();
    if( fs.count( " " ) < 2 )
    {
		qCritical() << "spaces < 2 ( getfs )" << fs;
		return QString();
    }
    fs.remove( 0, fs.indexOf( " ") + 1 );
    fs.resize( fs.indexOf( " " ) );
    if( fs == "devtmpfs" )//this is what it shows if if has permission to read a block device -- ie,  WBFS partition at /dev/sdc2
    {
		qCritical() << "fs == devtmpfs ( getfs )";
		return QString();
    }
    return fs;
#endif
}
Example #7
0
bool EProcess::exec() {
  se = so = "";
  
  QMessageBox box;
  // We're not using a progressdialog, because we have no clue
  // how long things will take.
  QString allout;
  box.setWindowTitle("eln");
  box.setText(winCap);
  box.setWindowModality(Qt::ApplicationModal);
  box.setStandardButtons(QMessageBox::Cancel);
  box.show();
  QObject::connect(&box, SIGNAL(buttonClicked(QAbstractButton*)),
                   &box, SLOT(close()));
  QEventLoop el;
  QProcess process;
  if (!wd.isEmpty())
    process.setWorkingDirectory(wd);
  process.start(cmd, args);
  process.closeWriteChannel();
  if (!process.waitForStarted()) {
    QString msg = msgNoStart.isEmpty()
      ? "Could not start command: " + cmd
      : msgNoStart;
    se += msg + "\n";
    return false;
  }

  for (int ntimeouts=0; ntimeouts<10*300; ntimeouts++) {
    el.processEvents(); // this makes the messagebox show up
    if (process.waitForFinished(100)) {
      break; // success or failure
    }
    if (box.isHidden()) {
#ifdef Q_OS_LINUX
      ::kill(process.pid(), SIGINT);
      // Killing bzr with INT produces cleaner exit than with TERM...
#else
      process.kill();
      // ... but if we don't have POSIX, we have no choice.
#endif
      process.waitForFinished(500); // allow it some time to respond to signal
      break; // not good, but oh well
    }
    QString ste = process.readAllStandardError();
    allout += ste;
    se += ste;

    QString sto = process.readAllStandardOutput();
    allout += sto;
    so += sto;

    if (!ste.isEmpty() || !sto.isEmpty())
      box.setText(winCap + "\n" + allout);
  }

  QString ste = process.readAllStandardError();
  se += ste;
  
  QString sto = process.readAllStandardOutput();
  so += sto;

  se.replace(QRegExp("\\s*Traceback.*"), "");
  
  if (process.state()!=QProcess::NotRunning) {
    return false;
  }
  return process.exitStatus()==QProcess::NormalExit && process.exitCode()==0;
}
Example #8
0
void ExternalExtractor::extract(ExtractionResult* result)
{
    Q_D(ExternalExtractor);

    QJsonDocument writeData;
    QJsonObject writeRootObject;
    QByteArray output;
    QByteArray errorOutput;

    writeRootObject[QStringLiteral("path")] = QJsonValue(result->inputUrl());
    writeRootObject[QStringLiteral("mimetype")] = result->inputMimetype();
    writeData.setObject(writeRootObject);

    QProcess extractorProcess;
    extractorProcess.start(d->mainPath, QIODevice::ReadWrite);
    extractorProcess.write(writeData.toJson());
    extractorProcess.closeWriteChannel();
    extractorProcess.waitForFinished(EXTRACTOR_TIMEOUT_MS);

    output = extractorProcess.readAll();
    errorOutput = extractorProcess.readAllStandardError();

    if (extractorProcess.exitStatus()) {
        qDebug() << errorOutput;
        return;
    }

    // now we read in the output (which is a standard json format) into the
    // ExtractionResult

    QJsonDocument extractorData = QJsonDocument::fromJson(output);
    if (!extractorData.isObject()) {
        return;
    }
    QJsonObject rootObject = extractorData.object();
    QJsonObject propertiesObject = rootObject[QStringLiteral("properties")].toObject();

    Q_FOREACH(auto key, propertiesObject.keys()) {
        if (key == QStringLiteral("typeInfo")) {
            TypeInfo info = TypeInfo::fromName(propertiesObject.value(key).toString());
            result->addType(info.type());
            continue;
        }

        // for plaintext extraction
        if (key == QStringLiteral("text")) {
            result->append(propertiesObject.value(key).toString(QStringLiteral("")));
            continue;
        }

        PropertyInfo info = PropertyInfo::fromName(key);
        if (info.name() != key) {
            continue;
        }
        result->add(info.property(), propertiesObject.value(key).toVariant());
    }

    if (rootObject[QStringLiteral("status")].toString() != QStringLiteral("OK")) {
        qDebug() << rootObject[QStringLiteral("error")].toString();
    }
}
Example #9
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 #10
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;
}
Example #11
0
bool InitDriveThread::method_resizePartitions()
{
    uint newStartOfRescuePartition = getFileContents(sysclassblock(_drive, 1)+"/start").trimmed().toUInt();
    uint newSizeOfRescuePartition  = sizeofBootFilesInKB()*1.024/1000 + 100;

    if (!umountSystemPartition())
    {
        emit error(tr("Error unmounting system partition."));
        return false;
    }

    if (!QFile::exists(partdev(_drive, 1)))
    {
        // SD card does not have a MBR.

        // Warn user that their SD card does not have an MBR and ask
        // if they would like us to create one for them
        QMessageBox::StandardButton answer;
        emit query(tr("Would you like NOOBS to create one for you?\nWARNING: This will erase all data on your SD card"),
                   tr("Error: No MBR present on SD Card"),
                   &answer);

        if(answer == QMessageBox::Yes)
        {
            emit statusUpdate(tr("Zeroing partition table"));
            if (!zeroMbr())
            {
                emit error(tr("Error zero'ing MBR/GPT. SD card may be broken or advertising wrong capacity."));
                return false;
            }

            // Create MBR containing single FAT partition
            emit statusUpdate(tr("Writing new MBR"));
            QProcess proc;
            proc.setProcessChannelMode(proc.MergedChannels);
            proc.start("/usr/sbin/parted "+_drive+" --script -- mktable msdos mkpartfs primary fat32 8192s -1");
            proc.waitForFinished(-1);
            if (proc.exitCode() != 0)
            {
                // Warn user if we failed to create an MBR on their card
                emit error(tr("Error creating MBR")+"\n"+proc.readAll());
                return false;
            }
            qDebug() << "Created missing MBR on SD card. parted output:" << proc.readAll();

            // Advise user that their SD card has now been formatted
            // suitably for installing NOOBS and that they will have to
            // re-copy the files before rebooting
            emit error(tr("SD card has now been formatted ready for NOOBS installation. Please re-copy the NOOBS files onto the card and reboot"));
            return false;
        }
        else
        {
            emit error(tr("SD card has not been formatted correctly. Please reformat using the SD Association Formatting Tool and try again."));
            return false;
        }

    }

    emit statusUpdate(tr("Removing partitions 2,3,4"));

    QFile f(_drive);
    f.open(f.ReadWrite);
    // Seek to partition entry 2
    f.seek(462);
    // Zero out partition 2,3,4 to prevent parted complaining about invalid constraints
    f.write(QByteArray(16*3, '\0'));
    f.flush();
    // Tell Linux to re-read the partition table
    ioctl(f.handle(), BLKRRPART);
    f.close();
    QThread::msleep(500);

    emit statusUpdate(tr("Resizing FAT partition"));

    /* Relocating the start of the FAT partition is a write intensive operation
     * only move it when it is not aligned on a MiB boundary already */
    if (newStartOfRescuePartition < 2048 || newStartOfRescuePartition % 2048 != 0)
    {
        newStartOfRescuePartition = PARTITION_ALIGNMENT; /* 4 MiB */
    }

    QString cmd = "/usr/sbin/parted --script "+_drive+" resize 1 "+QString::number(newStartOfRescuePartition)+"s "+QString::number(newSizeOfRescuePartition)+"M";
    qDebug() << "Executing" << cmd;
    QProcess p;
    QProcessEnvironment env = QProcessEnvironment::systemEnvironment();
    /* Suppress parted's big fat warning about its file system manipulation code not being robust.
       It distracts from any real error messages that may follow it. */
    env.insert("PARTED_SUPPRESS_FILE_SYSTEM_MANIPULATION_WARNING", "1");
    p.setProcessEnvironment(env);
    p.setProcessChannelMode(p.MergedChannels);
    p.start(cmd);
    p.closeWriteChannel();
    p.waitForFinished(-1);

    if (p.exitCode() != 0)
    {
        emit error(tr("Error resizing existing FAT partition")+"\n"+p.readAll());
        return false;
    }
    qDebug() << "parted done, output:" << p.readAll();
    QThread::msleep(500);

    emit statusUpdate(tr("Creating extended partition"));

    QByteArray partitionTable;
    uint startOfOurPartition = getFileContents(sysclassblock(_drive, 1)+"/start").trimmed().toUInt();
    uint sizeOfOurPartition  = getFileContents(sysclassblock(_drive, 1)+"/size").trimmed().toUInt();
    uint startOfExtended = startOfOurPartition+sizeOfOurPartition;

    // Align start of settings partition on 4 MiB boundary
    uint startOfSettings = startOfExtended + PARTITION_GAP;
    if (startOfSettings % PARTITION_ALIGNMENT != 0)
         startOfSettings += PARTITION_ALIGNMENT-(startOfSettings % PARTITION_ALIGNMENT);

    // Primary partitions
    partitionTable  = QByteArray::number(startOfOurPartition)+","+QByteArray::number(sizeOfOurPartition)+",0E\n"; /* FAT partition */
    partitionTable += QByteArray::number(startOfExtended)+",,E\n"; /* Extended partition with all remaining space */
    partitionTable += "0,0\n";
    partitionTable += "0,0\n";
    // Logical partitions
    partitionTable += QByteArray::number(startOfSettings)+","+QByteArray::number(SETTINGS_PARTITION_SIZE)+",L\n"; /* Settings partition */
    qDebug() << "Writing partition table" << partitionTable;

    /* Let sfdisk write a proper partition table */
    cmd = QString("/sbin/sfdisk -uS --force "+_drive);
    QProcess proc;
    proc.setProcessChannelMode(proc.MergedChannels);
    proc.start(cmd);
    proc.write(partitionTable);
    proc.closeWriteChannel();
    proc.waitForFinished(-1);
    if (proc.exitCode() != 0)
    {
        emit error(tr("Error creating extended partition")+"\n"+proc.readAll());
        return false;
    }
    qDebug() << "sfdisk done, output:" << proc.readAll();
    QThread::msleep(500);

    QProcess::execute("/sbin/mlabel -i "+partdev(_drive, 1)+" ::RECOVERY");

    return true;
}
Example #12
0
Task::future<bool>& zuluMountTask::encfsMount( const QString& p,const QString& m,const QString& k,bool ro )
{
	return Task::run< bool >( [ p,m,k,ro ](){

		auto _encfsMount = [ & ](){

			auto _mount = [ & ](){

				QString exe ;

				if( ro ){

					exe = QString( "/usr/bin/encfs -S %1 %2 -o ro" ).arg( p,m ) ;
				}else{
					exe = QString( "/usr/bin/encfs -S %1 %2" ).arg( p,m ) ;
				}

				QProcess e ;

				e.start( exe ) ;
				e.waitForStarted() ;
				e.write( k.toLatin1() + '\n' ) ;

				e.closeWriteChannel() ;

				if( e.waitForFinished( 10000 ) ){

					return e.exitCode() == 0 ;
				}else{
					return false ;
				}
			} ;

			if( _create_encfs_mount_point( m ) ){

				if( _mount() ) {

					return true ;
				}else{
					return _delete_encfs_m_point( m ) ;
				}
			}else{
				return false ;
			}
		} ;

		QDir d( p ) ;

		QStringList l = d.entryList( QDir::Hidden | QDir::Files ) ;

		for( const auto& it : l ){

			if( it.startsWith( ".encfs" ) && it.endsWith( ".xml" ) ){

				/*
				 * encfs folders usually have a config hidden file name named ".encfs6.xml"
				 * and we assume the folder contains encfs files only if this file
				 * is present.
				 */

				return _encfsMount() ;
			}
		}

		return false ;
	} ) ;
}
Example #13
0
bool MediaInfo::fillMediaInfo(const QString& path, MediaInfo& mediaInfo)
{
	QFileInfo file(path);
	QString width, height, len;
	QProcess ident;
	bool ok = true;
	bool audioEnc = false;

	QRegExp videoWidthRx("ID_VIDEO_WIDTH\\s*=\\s*(\\d+)");
	QRegExp videoHeightRx("ID_VIDEO_HEIGHT\\s*=\\s*(\\d+)");
	QRegExp lengthRx("ID_LENGTH\\s*=\\s*([\\d.]+)");
	QRegExp audioBitrateRx("ID_AUDIO_BITRATE\\s*=\\s*(\\d+)");
	QRegExp audioRateRx("ID_AUDIO_RATE\\s*=\\s*(\\d+)");
	QRegExp audioChannelsRx("ID_AUDIO_NCH\\s*=\\s*(\\d+)");

	QString audioEncLine("Opening audio decoder");

	if (!file.isFile())
		return false;

     ident.start(QString(MPLAYER_INDENTIFY).arg(file.absoluteFilePath()));
     if (!ident.waitForStarted())
         return false;

     ident.closeWriteChannel();
     if (!ident.waitForFinished())
         return false;

	 mediaInfo.fileSize = file.size();

	 mediaInfo.audioBitrate = -1;
	 mediaInfo.audioRate = -1;
	 mediaInfo.audioChannels = -1;

	 while (ident.canReadLine()) {
		 QString line = ident.readLine();

		 if (-1 != videoWidthRx.indexIn(line))
			 width = videoWidthRx.cap(1);
		 else if (-1 != videoHeightRx.indexIn(line))
			 height = videoHeightRx.cap(1);
		 else if (-1 != lengthRx.indexIn(line))
			 len = lengthRx.cap(1);
		 else if (!audioEnc && line.contains(audioEncLine))
			 audioEnc = true;
		 else if (audioEnc && -1 != audioBitrateRx.indexIn(line))
			 mediaInfo.audioBitrate = audioBitrateRx.cap(1).toInt(&ok);
		 else if (audioEnc && -1 != audioRateRx.indexIn(line))
			 mediaInfo.audioRate = audioRateRx.cap(1).toInt(&ok);
		 else if (audioEnc && -1 != audioChannelsRx.indexIn(line))
			 mediaInfo.audioChannels = audioChannelsRx.cap(1).toInt(&ok);

		 if (!ok)
			 return false;
	 }

	 if (!width.isEmpty() && !height.isEmpty())
		 mediaInfo.videoResolution = QString("%1x%2").arg(width).arg(height);
	 if (!len.isEmpty()) {
		 int secs = 0, msecs = 0;
		 QStringList lens = len.split(".");
		 if (!lens.size())
			 return false;
		 if (lens.size() > 0)
			 secs = lens[0].toInt(&ok);
		 if (lens.size() > 1)
			 msecs = lens[1].toInt(&ok);
		 if (!ok)
			 return false;

		 mediaInfo.duration = QString("%1:%2:%3:%4").
			 arg(secs / 3600,    2, 10, QChar('0')).
			 arg(secs / 60 % 60, 2, 10, QChar('0')).
			 arg(secs % 60,      2, 10, QChar('0')).
			 arg(msecs,          2, 10, QChar('0'));
	 }

	 return true;
}
Example #14
0
int main(int argc, char **argv)
{
	QApplication app(argc, argv, true);
	QTranslator custranldr;
	QTranslator translator;
	QString tnapplang;
	QString tnappcoun;
	QString clangcode = "";
	QStringList allappargs = app.arguments();
	QList<QPair<QString, QString> > oppairs;
	for (QList<QString>::const_iterator i = allappargs.constBegin(); i < allappargs.constEnd(); ++i)
	{
		if (i->count('=') == 1)
			oppairs.append(QPair<QString, QString>(i->section('=', 0, 0).simplified(), i->section('=',1, 1).simplified()));
	}
	for (QList<QPair<QString, QString> >::const_iterator i = oppairs.constBegin(); i < oppairs.constEnd(); ++i)
	{
		if (i->first.contains("lang", Qt::CaseInsensitive))
		{
			clangcode = i->second;
			tnapplang = clangcode.left(2);
			if (clangcode.contains('_') && clangcode.size() == 5)
			{
				tnappcoun = clangcode.section('_', -1, -1);
			}
			break;
		}
	}
	if (clangcode.isEmpty())
	{
		clangcode = QLocale::system().name();
		tnapplang = clangcode.left(2);
		if (clangcode.contains('_') && clangcode.size() == 5)
		{
			tnappcoun = clangcode.section('_', -1, -1);
		}
	}
	QDir applocdir(app.applicationDirPath());
	QStringList applocfiles = applocdir.entryList(QStringList() << "*.qm", QDir::Files);
	if (!applocfiles.isEmpty())
	{
		QString custqmfilepath = applocfiles.at(0);
		if (!applocfiles.filter("unetbootin").isEmpty())
		{
			custqmfilepath = applocfiles.filter("unetbootin").at(0);
			if (!applocfiles.filter("unetbootin").filter(tnapplang).isEmpty())
			{
				custqmfilepath = applocfiles.filter("unetbootin").filter(tnapplang).at(0);
				if (!tnappcoun.isEmpty() && !applocfiles.filter("unetbootin").filter(tnapplang).filter(tnappcoun).isEmpty())
					custqmfilepath = applocfiles.filter("unetbootin").filter(tnapplang).filter(tnappcoun).at(0);
			}
		}
		if (custranldr.load(custqmfilepath, app.applicationDirPath()))
			app.installTranslator(&custranldr);
	}
	if (!tnappcoun.isEmpty() && QFile::exists(QString("%1/unetbootin_%2_%3.qm").arg(app.applicationDirPath()).arg(tnapplang).arg(tnappcoun)) && translator.load(QString("%1/unetbootin_%2_%3.qm").arg(app.applicationDirPath()).arg(tnapplang).arg(tnappcoun)))
	{
		app.installTranslator(&translator);
	}
	else if (!tnappcoun.isEmpty() && QFile::exists(QString(":/unetbootin_%1_%2.qm").arg(tnapplang).arg(tnappcoun)) && translator.load(QString(":/unetbootin_%1_%2.qm").arg(tnapplang).arg(tnappcoun)))
	{
		app.installTranslator(&translator);
	}
	else if (!tnappcoun.isEmpty() && QFile::exists(QString("/usr/share/unetbootin/unetbootin_%1_%2.qm").arg(tnapplang).arg(tnappcoun)) && translator.load(QString("/usr/share/unetbootin/unetbootin_%1_%2.qm").arg(tnapplang).arg(tnappcoun)))
	{
		app.installTranslator(&translator);
	}
	else if (QFile::exists(QString("%1/unetbootin_%2.qm").arg(app.applicationDirPath(), tnapplang)) && translator.load(QString("%1/unetbootin_%2.qm").arg(app.applicationDirPath(), tnapplang)))
	{
		app.installTranslator(&translator);
	}
	else if (QFile::exists(QString(":/unetbootin_%1.qm").arg(tnapplang)) && translator.load(QString(":/unetbootin_%1.qm").arg(tnapplang)))
	{
		app.installTranslator(&translator);
	}
	else if (QFile::exists(QString("/usr/share/unetbootin/unetbootin_%1.qm").arg(tnapplang)) && translator.load(QString("/usr/share/unetbootin/unetbootin_%1.qm").arg(tnapplang)))
	{
		app.installTranslator(&translator);
	}
	else
	{
		tnapplang = "en";
		tnappcoun = "US";
		clangcode = "en_US";
	}
	app.installTranslator(&translator);
	if (QObject::tr("LeftToRight") == "RightToLeft")
		app.setLayoutDirection(Qt::RightToLeft);
	#ifdef Q_OS_UNIX
	bool disabledrootcheck = false;
	for (QList<QPair<QString, QString> >::const_iterator i = oppairs.constBegin(); i < oppairs.constEnd(); ++i)
	{
		if (i->first.contains("rootcheck", Qt::CaseInsensitive))
		{
			if (i->second.contains('n', Qt::CaseInsensitive))
				disabledrootcheck = true;
			break;
		}
	}
	if (!disabledrootcheck)
	{
		QProcess whoamip;
		whoamip.start("whoami");
		whoamip.waitForFinished();
		if (QString(whoamip.readAll()).remove("\r").remove("\n") != "root")
		{
			QString argsconc = "";
			for (int i = 1; i < allappargs.size(); ++i)
			{
				argsconc += QString("\"%1\" ").arg(allappargs.at(i));
			}
			argsconc += "'rootcheck=no'";
#ifdef Q_OS_LINUX
			QString gksulocation = checkforgraphicalsu("gksu");
			if (gksulocation != "REQCNOTFOUND")
			{
				QProcess::startDetached(QString("%1 %2 %3").arg(gksulocation).arg(app.applicationFilePath()).arg(argsconc));
				return 0;
			}
			QString kdesulocation = checkforgraphicalsu("kdesu");
			if (kdesulocation != "REQCNOTFOUND")
			{
				QProcess::startDetached(QString("%1 %2 %3").arg(kdesulocation).arg(app.applicationFilePath()).arg(argsconc));
				return 0;
			}
			QString gnomesulocation = checkforgraphicalsu("gnomesu");
			if (gnomesulocation != "REQCNOTFOUND")
			{
				QProcess::startDetached(QString("%1 %2 %3").arg(gnomesulocation).arg(app.applicationFilePath()).arg(argsconc));
				return 0;
			}
			QString kdesudolocation = checkforgraphicalsu("kdesudo");
			if (kdesudolocation != "REQCNOTFOUND")
			{
				QProcess::startDetached(QString("%1 %2 %3").arg(kdesudolocation).arg(app.applicationFilePath()).arg(argsconc));
				return 0;
			}
			QMessageBox rootmsgb;
			rootmsgb.setIcon(QMessageBox::Warning);
			rootmsgb.setWindowTitle(uninstaller::tr("Must run as root"));
			rootmsgb.setTextFormat(Qt::RichText);
			rootmsgb.setText(uninstaller::tr("%2 must be run as root. Close it, and re-run using either:<br/><b>sudo %1</b><br/>or:<br/><b>su - -c '%1'</b>").arg(app.applicationFilePath()).arg(UNETBOOTINB));
			rootmsgb.setStandardButtons(QMessageBox::Ok);
			switch (rootmsgb.exec())
			{
				case QMessageBox::Ok:
					break;
				default:
					break;
			}
#endif
#ifdef Q_OS_MAC
			QProcess osascriptProc;
			osascriptProc.start("osascript");
			osascriptProc.write(QString("do shell script \""+app.applicationFilePath()+"\" with administrator privileges\n").toAscii().data());
			osascriptProc.closeWriteChannel();
			osascriptProc.waitForFinished(-1);
			return 0;
#endif
		}
	}
	#endif
	#ifdef Q_OS_WIN32
	QSettings chkinst("HKEY_LOCAL_MACHINE\\Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\UNetbootin", QSettings::NativeFormat);
	#endif
	#ifdef Q_OS_LINUX
	QSettings chkinst(QSettings::SystemScope, "UNetbootin");
	#endif
#ifndef Q_OS_MAC
	if (chkinst.contains("Location"))
	{
		QMessageBox uninstmsgb;
		uninstmsgb.setIcon(QMessageBox::Information);
		uninstmsgb.setWindowTitle(uninstaller::tr("%1 Uninstaller").arg(UNETBOOTINB));
		uninstmsgb.setText(uninstaller::tr("%1 is currently installed. Remove the existing version?").arg(UNETBOOTINB));
 		uninstmsgb.setStandardButtons(QMessageBox::Ok | QMessageBox::Cancel);
 		switch (uninstmsgb.exec())
 		{
 			case QMessageBox::Ok:
 			{
 				ubnUninst();
			}
			case QMessageBox::Cancel:
				break;
	 		default:
				break;
 		}
		return 0;
	}
#endif
	unetbootin unetbootin;
	unetbootin.appNlang = tnapplang;
	unetbootin.appDir = QDir::toNativeSeparators(QString("%1/").arg(app.applicationDirPath()));
	unetbootin.appLoc = app.applicationFilePath();
	QIcon icon;
	icon.addFile(":/unetbootin_16.png", QSize(16,16));
	icon.addFile(":/unetbootin_22.png", QSize(22,22));
	icon.addFile(":/unetbootin_24.png", QSize(24,24));
	icon.addFile(":/unetbootin_32.png", QSize(32,32));
	icon.addFile(":/unetbootin_48.png", QSize(48,48));
#ifdef Q_OS_LINUX
	icon.addFile("/usr/share/pixmaps/unetbootin.png");
#endif
	unetbootin.setWindowIcon(icon);
	QObject::connect(&app, SIGNAL(lastWindowClosed()), &unetbootin, SLOT(killApplication()));
	bool automate = unetbootin.ubninitialize(oppairs);
	unetbootin.show();
	if (automate)
		QTimer::singleShot(0, &unetbootin, SLOT(on_okbutton_clicked()));
	return app.exec();
}
Example #15
0
bool QgsGrassRasterImport::import()
{
  QgsDebugMsg( "entered" );
  if ( !mPipe )
  {
    setError( "Pipe is null." );
    return false;
  }

  QgsRasterDataProvider * provider = mPipe->provider();
  if ( !provider )
  {
    setError( "Pipe has no provider." );
    return false;
  }

  if ( !provider->isValid() )
  {
    setError( "Provider is not valid." );
    return false;
  }

  int redBand = 0;
  int greenBand = 0;
  int blueBand = 0;
  for ( int band = 1; band <= provider->bandCount(); band++ )
  {
    QgsDebugMsg( QString( "band = %1" ).arg( band ) );
    int colorInterpretation = provider->colorInterpretation( band );
    if ( colorInterpretation ==  QgsRaster::RedBand )
    {
      redBand = band;
    }
    else if ( colorInterpretation ==  QgsRaster::GreenBand )
    {
      greenBand = band;
    }
    else if ( colorInterpretation ==  QgsRaster::BlueBand )
    {
      blueBand = band;
    }

    QGis::DataType qgis_out_type = QGis::UnknownDataType;
    RASTER_MAP_TYPE data_type = -1;
    switch ( provider->dataType( band ) )
    {
      case QGis::Byte:
      case QGis::UInt16:
      case QGis::Int16:
      case QGis::UInt32:
      case QGis::Int32:
        qgis_out_type = QGis::Int32;
        break;
      case QGis::Float32:
        qgis_out_type = QGis::Float32;
        break;
      case QGis::Float64:
        qgis_out_type = QGis::Float64;
        break;
      case QGis::ARGB32:
      case QGis::ARGB32_Premultiplied:
        qgis_out_type = QGis::Int32;  // split to multiple bands?
        break;
      case QGis::CInt16:
      case QGis::CInt32:
      case QGis::CFloat32:
      case QGis::CFloat64:
      case QGis::UnknownDataType:
        setError( tr( "Data type %1 not supported" ).arg( provider->dataType( band ) ) );
        return false;
    }

    QgsDebugMsg( QString( "data_type = %1" ).arg( data_type ) );

    QString module = QgsGrass::qgisGrassModulePath() + "/qgis.r.in";
    QStringList arguments;
    QString name = mGrassObject.name();
    if ( provider->bandCount() > 1 )
    {
      // raster.<band> to keep in sync with r.in.gdal
      name += QString( ".%1" ).arg( band );
    }
    arguments.append( "output=" + name );    // get list of all output names
    QTemporaryFile gisrcFile;
    QProcess* process = 0;
    try
    {
      process = QgsGrass::startModule( mGrassObject.gisdbase(), mGrassObject.location(), mGrassObject.mapset(), module, arguments, gisrcFile );
    }
    catch ( QgsGrass::Exception &e )
    {
      setError( e.what() );
      return false;
    }

    QDataStream outStream( process );

    outStream << mExtent << ( qint32 )mXSize << ( qint32 )mYSize;
    outStream << ( qint32 )qgis_out_type;

    // calculate reasonable block size (5MB)
    int maximumTileHeight = 5000000 / mXSize;
    maximumTileHeight = std::max( 1, maximumTileHeight );
    // smaller if reprojecting so that it can be canceled quickly
    if ( mPipe->projector() )
    {
      maximumTileHeight = std::max( 1, 100000 / mXSize );
    }

    QgsRasterIterator iter( mPipe->last() );
    iter.setMaximumTileWidth( mXSize );
    iter.setMaximumTileHeight( maximumTileHeight );

    iter.startRasterRead( band, mXSize, mYSize, mExtent );

    int iterLeft = 0;
    int iterTop = 0;
    int iterCols = 0;
    int iterRows = 0;
    QgsRasterBlock* block = 0;
    process->setReadChannel( QProcess::StandardOutput );
    while ( iter.readNextRasterPart( band, iterCols, iterRows, &block, iterLeft, iterTop ) )
    {
      for ( int row = 0; row < iterRows; row++ )
      {
        if ( !block->convert( qgis_out_type ) )
        {
          setError( tr( "Cannot convert block (%1) to data type %2" ).arg( block->toString() ).arg( qgis_out_type ) );
          delete block;
          return false;
        }
        // prepare null values
        double noDataValue;
        if ( block->hasNoDataValue() )
        {
          noDataValue = block->noDataValue();
        }
        else
        {
          switch ( qgis_out_type )
          {
            case QGis::Int32:
              noDataValue = -2147483648.0;
              break;
            case QGis::Float32:
              noDataValue = std::numeric_limits<float>::max() * -1.0;
              break;
            case QGis::Float64:
              noDataValue = std::numeric_limits<double>::max() * -1.0;
              break;
            default: // should not happen
              noDataValue = std::numeric_limits<double>::max() * -1.0;
          }
          for ( qgssize i = 0; i < ( qgssize )block->width()*block->height(); i++ )
          {
            if ( block->isNoData( i ) )
            {
              block->setValue( i, noDataValue );
            }
          }
        }

        char * data = block->bits( row, 0 );
        int size = iterCols * block->dataTypeSize();
        QByteArray byteArray = QByteArray::fromRawData( data, size ); // does not copy data and does not take ownership
        if ( isCanceled() )
        {
          outStream << true; // cancel module
          break;
        }
        outStream << false; // not canceled
        outStream << noDataValue;

        outStream << byteArray;

        // Without waitForBytesWritten() it does not finish ok on Windows (process timeout)
        process->waitForBytesWritten( -1 );

#ifndef Q_OS_WIN
        // wait until the row is written to allow quick cancel (don't send data to buffer)
        process->waitForReadyRead();
        bool result;
        outStream >> result;
#endif
      }
      delete block;
      if ( isCanceled() )
      {
        outStream << true; // cancel module
        break;
      }
    }

    // TODO: send something back from module and read it here to close map correctly in module

    process->closeWriteChannel();
    // TODO: best timeout?
    process->waitForFinished( 30000 );

    QString stdoutString = process->readAllStandardOutput().data();
    QString stderrString = process->readAllStandardError().data();

    QString processResult = QString( "exitStatus=%1, exitCode=%2, error=%3, errorString=%4 stdout=%5, stderr=%6" )
                            .arg( process->exitStatus() ).arg( process->exitCode() )
                            .arg( process->error() ).arg( process->errorString() )
                            .arg( stdoutString.replace( "\n", ", " ) ).arg( stderrString.replace( "\n", ", " ) );
    QgsDebugMsg( "processResult: " + processResult );

    if ( process->exitStatus() != QProcess::NormalExit )
    {
      setError( process->errorString() );
      delete process;
      return false;
    }

    if ( process->exitCode() != 0 )
    {
      setError( stderrString );
      delete process;
      return false;
    }

    delete process;
  }
  QgsDebugMsg( QString( "redBand = %1 greenBand = %2 blueBand = %3" ).arg( redBand ).arg( greenBand ).arg( blueBand ) );
  if ( redBand > 0 && greenBand > 0 && blueBand > 0 )
  {
    // TODO: check if the group exists
    // I_find_group()
    QString name = mGrassObject.name();

    G_TRY
    {
      QgsGrass::setMapset( mGrassObject.gisdbase(), mGrassObject.location(), mGrassObject.mapset() );
      struct Ref ref;
      I_get_group_ref( name.toUtf8().data(), &ref );
      QString redName = name + QString( ".%1" ).arg( redBand );
      QString greenName = name + QString( ".%1" ).arg( greenBand );
      QString blueName = name + QString( ".%1" ).arg( blueBand );
      I_add_file_to_group_ref( redName.toUtf8().data(), mGrassObject.mapset().toUtf8().data(), &ref );
      I_add_file_to_group_ref( greenName.toUtf8().data(), mGrassObject.mapset().toUtf8().data(), &ref );
      I_add_file_to_group_ref( blueName.toUtf8().data(), mGrassObject.mapset().toUtf8().data(), &ref );
      I_put_group_ref( name.toUtf8().data(), &ref );
    }
    G_CATCH( QgsGrass::Exception &e )
    {
      QgsDebugMsg( QString( "Cannot create group: %1" ).arg( e.what() ) );
    }
Example #16
0
void Common::mailTo( const QUrl &url )
{
#if defined(Q_OS_WIN32)
	QString file = url.queryItemValue( "attachment" );
	QByteArray filePath = QDir::toNativeSeparators( file ).toLatin1();
	QByteArray fileName = QFileInfo( file ).fileName().toLatin1();
	QByteArray subject = url.queryItemValue( "subject" ).toLatin1();

	MapiFileDesc doc[1];
	doc[0].ulReserved = 0;
	doc[0].flFlags = 0;
	doc[0].nPosition = -1;
	doc[0].lpszPathName = const_cast<char*>(filePath.constData());
	doc[0].lpszFileName = const_cast<char*>(fileName.constData());
	doc[0].lpFileType = NULL;

	// Create message
	MapiMessage message;
	message.ulReserved = 0;
	message.lpszSubject = const_cast<char*>(subject.constData());
	message.lpszNoteText = "";
	message.lpszMessageType = NULL;
	message.lpszDateReceived = NULL;
	message.lpszConversationID = NULL;
	message.flFlags = 0;
	message.lpOriginator = NULL;
	message.nRecipCount = 0;
	message.lpRecips = NULL;
	message.nFileCount = 1;
	message.lpFiles = (lpMapiFileDesc)&doc;

	QLibrary lib("mapi32");
	typedef ULONG (PASCAL *SendMail)(ULONG,ULONG,MapiMessage*,FLAGS,ULONG);
	SendMail mapi = (SendMail)lib.resolve("MAPISendMail");
	if( mapi )
	{
		mapi( NULL, 0, &message, MAPI_LOGON_UI|MAPI_DIALOG, 0 );
		return;
	}
#elif defined(Q_OS_MAC)
	CFURLRef emailUrl = CFURLCreateWithString( kCFAllocatorDefault, CFSTR("mailto:"), 0 );
	CFURLRef appUrl = 0;
	CFStringRef appPath = 0;
	if( LSGetApplicationForURL( emailUrl, kLSRolesAll, NULL, &appUrl ) == noErr )
	{
		appPath = CFURLCopyFileSystemPath( appUrl, kCFURLPOSIXPathStyle );
		CFRelease( appUrl );
	}
	CFRelease( emailUrl );

	if( appPath )
	{
		QProcess p;
		p.start( "/usr/bin/osascript", QStringList() << "-" << url.queryItemValue("attachment") << url.queryItemValue("subject") );
		p.waitForStarted();
		QTextStream s( &p );
		if( CFStringCompare( appPath, CFSTR("/Applications/Mail.app"), 0 ) == kCFCompareEqualTo )
		{
			s << "on run argv" << endl
				<< "set vattachment to (item 1 of argv)" << endl
				<< "set vsubject to (item 2 of argv)" << endl
				<< "tell application \"Mail\"" << endl
				<< "set composeMessage to make new outgoing message at beginning with properties {visible:true}" << endl
				<< "tell composeMessage" << endl
				<< "set subject to vsubject" << endl
				<< "set content to \" \"" << endl
				<< "tell content" << endl
				<< "make new attachment with properties {file name: vattachment} at after the last word of the last paragraph" << endl
				<< "end tell" << endl
				<< "end tell" << endl
				<< "activate" << endl
				<< "end tell" << endl
				<< "end run" << endl;
		}
		else if( CFStringFind( appPath, CFSTR("Entourage"), 0 ).location != kCFNotFound )
		{
			s << "on run argv" << endl
				<< "set vattachment to (item 1 of argv)" << endl
				<< "set vsubject to (item 2 of argv)" << endl
				<< "tell application \"Microsoft Entourage\"" << endl
				<< "set vmessage to make new outgoing message with properties" << endl
				<< "{subject:vsubject, attachments:vattachment}" << endl
				<< "open vmessage" << endl
				<< "activate" << endl
				<< "end tell" << endl
				<< "end run" << endl;
		}
#if 0
		else if(CFStringCompare(appPath, CFSTR("/Applications/Thunderbird.app"), 0) == kCFCompareEqualTo)
		{
			// TODO: Handle Thunderbird here? Impossible?
		}
#endif
		CFRelease( appPath );
		p.closeWriteChannel();
		p.waitForFinished();
		if( p.exitCode() == 0 )
			return;
	}
#elif defined(Q_OS_LINUX)
	QByteArray thunderbird;
	QProcess p;
	QStringList env = QProcess::systemEnvironment();
	if( env.indexOf( QRegExp("KDE_FULL_SESSION.*") ) != -1 )
	{
		p.start( "kreadconfig", QStringList()
			<< "--file" << "emaildefaults"
			<< "--group" << "PROFILE_Default"
			<< "--key" << "EmailClient" );
		p.waitForFinished();
		QByteArray data = p.readAllStandardOutput().trimmed();
		if( data.contains("thunderbird") )
			thunderbird = data;
	}
	else if( env.indexOf( QRegExp("GNOME_DESKTOP_SESSION_ID.*") ) != -1 )
	{
		p.start( "gconftool-2", QStringList()
			<< "--get" << "/desktop/gnome/url-handlers/mailto/command" );
		p.waitForFinished();
		QByteArray data = p.readAllStandardOutput();
		if( data.contains("thunderbird") )
			thunderbird = data.split(' ').value(0);
	}
	/*
	else
	{
		p.start( "xprop", QStringList() << "-root" << "_DT_SAVE_MODE" );
		p.waitForFinished();
		if( p.readAllStandardOutput().contains("xfce4") )
		{}
	}*/

	if( !thunderbird.isEmpty() )
	{
		if( p.startDetached( thunderbird, QStringList() << "-compose"
			<< QString( "subject='%1',attachment='%2'" )
				.arg( url.queryItemValue( "subject" ) )
				.arg( QUrl::fromLocalFile( url.queryItemValue( "attachment" ) ).toString() ) ) );
			return;
	}
	else
	{
		if( p.startDetached( "xdg-email", QStringList()
				<< "--subject" << url.queryItemValue( "subject" )
				<< "--attach" << url.queryItemValue( "attachment" ) ) )
			return;
	}
#endif
	QDesktopServices::openUrl( url );
}
Example #17
0
ItemSaverPtr ItemEncryptedLoader::loadItems(const QString &, QAbstractItemModel *model, QIODevice *file, int maxItems)
{
    // This is needed to skip header.
    if ( !canLoadItems(file) )
        return nullptr;

    if (status() == GpgNotInstalled) {
        emit error( ItemEncryptedLoader::tr("GnuPG must be installed to view encrypted tabs.") );
        return nullptr;
    }

    importGpgKey();

    QProcess p;
    startGpgProcess( &p, QStringList("--decrypt"), QIODevice::ReadWrite );

    char encryptedBytes[4096];

    QDataStream stream(file);
    while ( !stream.atEnd() ) {
        const int bytesRead = stream.readRawData(encryptedBytes, 4096);
        if (bytesRead == -1) {
            emitDecryptFailed();
            COPYQ_LOG("ItemEncrypted ERROR: Failed to read encrypted data");
            return nullptr;
        }
        p.write(encryptedBytes, bytesRead);
    }

    p.closeWriteChannel();

    // Wait for password entry dialog.
    p.waitForFinished(-1);

    if ( !verifyProcess(&p) ) {
        emitDecryptFailed();
        return nullptr;
    }

    const QByteArray bytes = p.readAllStandardOutput();
    if ( bytes.isEmpty() ) {
        emitDecryptFailed();
        COPYQ_LOG("ItemEncrypt ERROR: Failed to read encrypted data.");
        verifyProcess(&p);
        return nullptr;
    }

    QDataStream stream2(bytes);

    quint64 length;
    stream2 >> length;
    if ( length <= 0 || stream2.status() != QDataStream::Ok ) {
        emitDecryptFailed();
        COPYQ_LOG("ItemEncrypt ERROR: Failed to parse item count!");
        return nullptr;
    }
    length = qMin(length, static_cast<quint64>(maxItems)) - static_cast<quint64>(model->rowCount());

    const auto count = length < maxItemCount ? static_cast<int>(length) : maxItemCount;
    for ( int i = 0; i < count && stream2.status() == QDataStream::Ok; ++i ) {
        if ( !model->insertRow(i) ) {
            emitDecryptFailed();
            COPYQ_LOG("ItemEncrypt ERROR: Failed to insert item!");
            return nullptr;
        }
        QVariantMap dataMap;
        stream2 >> dataMap;
        model->setData( model->index(i, 0), dataMap, contentType::data );
    }

    if ( stream2.status() != QDataStream::Ok ) {
        emitDecryptFailed();
        COPYQ_LOG("ItemEncrypt ERROR: Failed to decrypt item!");
        return nullptr;
    }

    return createSaver();
}
Example #18
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 #19
0
void wrapInFunction()
{

//! [0]
QProcess builder;
builder.setProcessChannelMode(QProcess::MergedChannels);
builder.start("make", QStringList() << "-j2");

if (!builder.waitForFinished())
    qDebug() << "Make failed:" << builder.errorString();
else
    qDebug() << "Make output:" << builder.readAll();
//! [0]


//! [1]
QProcess more;
more.start("more");
more.write("Text to display");
more.closeWriteChannel();
// QProcess will emit readyRead() once "more" starts printing
//! [1]


//! [2]
command1 | command2
//! [2]


//! [3]
QProcess process1;
QProcess process2;

process1.setStandardOutputProcess(&process2);

process1.start("command1");
process2.start("command2");
//! [3]


//! [4]
class SandboxProcess : public QProcess
{
    ...
 protected:
     void setupChildProcess();
    ...
};

void SandboxProcess::setupChildProcess()
{
    // Drop all privileges in the child process, and enter
    // a chroot jail.
#if defined Q_OS_UNIX
    ::setgroups(0, 0);
    ::chroot("/etc/safe");
    ::chdir("/");
    ::setgid(safeGid);
    ::setuid(safeUid);
    ::umask(0);
#endif
}

//! [4]


//! [5]
QProcess process;
process.start("del /s *.txt");
// same as process.start("del", QStringList() << "/s" << "*.txt");
...
//! [5]


//! [6]
QProcess process;
process.start("dir \"My Documents\"");
//! [6]


//! [7]
QProcess process;
process.start("dir \"\"\"My Documents\"\"\"");
//! [7]


//! [8]
QStringList environment = QProcess::systemEnvironment();
// environment = {"PATH=/usr/bin:/usr/local/bin",
//                "USER=greg", "HOME=/home/greg"}
//! [8]

}
Example #20
0
bool PlotXrd::executeGenXrdPattern(const QStringList& args,
                                   const QByteArray& input, QByteArray& output,
                                   QString& err)
{
  QString program;
  // If the GENXRDPATTERN_EXECUTABLE environment variable is set, then
  // use that
  QByteArray xrdExec = qgetenv("GENXRDPATTERN_EXECUTABLE");
  if (!xrdExec.isEmpty()) {
    program = xrdExec;
  } else {
// Otherwise, search in the current directory, and then ../bin
#ifdef _WIN32
    QString executable = "genXrdPattern.exe";
#else
    QString executable = "genXrdPattern";
#endif
    QString path = QCoreApplication::applicationDirPath();
    if (QFile::exists(path + "/" + executable))
      program = path + "/" + executable;
    else if (QFile::exists(path + "/../bin/" + executable))
      program = path + "/../bin/" + executable;
    else {
      err = tr("Error: could not find genXrdPattern executable!");
      qDebug() << err;
      return false;
    }
  }

  QProcess p;
  p.start(program, args);

  if (!p.waitForStarted()) {
    err = tr("Error: " + program.toLocal8Bit() + " failed to start");
    qDebug() << err;
    return false;
  }

  // Give it the input!
  p.write(input.data());

  // Close the write channel
  p.closeWriteChannel();

  if (!p.waitForFinished()) {
    err = tr("Error: " + program.toLocal8Bit() + " failed to finish");
    qDebug() << err;
    output = p.readAll();
    qDebug() << "Output is as follows:\n" << output;
    return false;
  }

  int exitStatus = p.exitStatus();
  output = p.readAll();

  if (exitStatus == QProcess::CrashExit) {
    err = tr("Error: " + program.toLocal8Bit() + " crashed!");
    qDebug() << err;
    qDebug() << "Output is as follows:\n" << output;
    return false;
  }

  if (exitStatus != QProcess::NormalExit) {
    err = tr("Error: " + program.toLocal8Bit() +
             " finished abnormally with exit code " +
             QString::number(exitStatus).toLocal8Bit());
    qDebug() << err;
    qDebug() << "Output is as follows:\n" << output;
    return false;
  }

  // We did it!
  return true;
}
Example #21
0
void QProcessProto::closeWriteChannel()
{
  QProcess *item = qscriptvalue_cast<QProcess*>(thisObject());
  if (item)
    item->closeWriteChannel();
}
Example #22
0
void GitCommand::run()
{
    if (Git::Constants::debug)
        qDebug() << "GitCommand::run" << m_workingDirectory << m_jobs.size();
    QProcess process;
    if (!m_workingDirectory.isEmpty())
        process.setWorkingDirectory(m_workingDirectory);

    process.setEnvironment(m_environment);

    QByteArray stdOut;
    QByteArray stdErr;
    QString error;

    const int count = m_jobs.size();
    int exitCode = -1;
    bool ok = true;
    for (int j = 0; j < count; j++) {
        if (Git::Constants::debug)
            qDebug() << "GitCommand::run" << j << '/' << count << m_jobs.at(j).arguments;

        process.start(m_binaryPath, m_basicArguments + m_jobs.at(j).arguments);
        if(!process.waitForStarted()) {
            ok = false;
            error += QString::fromLatin1("Error: \"%1\" could not be started: %2").arg(m_binaryPath, process.errorString());
            break;
        }

        process.closeWriteChannel();
        const int timeOutSeconds = m_jobs.at(j).timeout;
        if (!Utils::SynchronousProcess::readDataFromProcess(process, timeOutSeconds * 1000,
                                                            &stdOut, &stdErr)) {
            Utils::SynchronousProcess::stopProcess(process);
            ok = false;
            error += msgTimeout(timeOutSeconds);
            break;
        }

        error += QString::fromLocal8Bit(stdErr);
        exitCode = process.exitCode();
        switch (m_reportTerminationMode) {
        case NoReport:
            break;
        case ReportStdout:
            stdOut += msgTermination(exitCode, m_binaryPath, m_jobs.at(j).arguments).toUtf8();
            break;
        case ReportStderr:
            error += msgTermination(exitCode, m_binaryPath, m_jobs.at(j).arguments);
            break;
        }
    }

    // Special hack: Always produce output for diff
    if (ok && stdOut.isEmpty() && m_jobs.front().arguments.at(0) == QLatin1String("diff")) {
        stdOut += "No difference to HEAD";
    } else {
        // @TODO: Remove, see below
        if (ok && m_jobs.front().arguments.at(0) == QLatin1String("status"))
            removeColorCodes(&stdOut);
    }

    if (ok && !stdOut.isEmpty())
        emit outputData(stdOut);

    if (!error.isEmpty())
        emit errorText(error);

    emit finished(ok, exitCode, m_cookie);
    if (ok)
        emit success();
    // As it is used asynchronously, we need to delete ourselves
    this->deleteLater();
}
Example #23
0
void ServerThread::maybeSendBacktrace()
{
    QFile coreFile("core");

    if (!coreFile.exists()) {
        qDebug() << "No core dump found";
        return;
    }

    char *receiver = getenv("CRASH_REPORT_RECEIVER");
    if (!receiver) {
        qDebug() << "CRASH_REPORT_RECEIVER environment variable not set";
        return;
    }

    QProcess gdb;
    gdb.start(QString("gdb %1 core -q -x print-backtrace.gdb")
            .arg(mExecutable));

    if (!gdb.waitForStarted()) {
        qDebug() << "Failed to launch gdb";
        coreFile.remove();
        return;
    }

    if (!gdb.waitForFinished()) {
        qDebug() << "gdb process is not finishing, killing";
        gdb.kill();
        coreFile.remove();
        return;
    }

    coreFile.remove();

    const QByteArray gdbOutput = gdb.readAllStandardOutput();
    qDebug() << "gdb output:\n" << gdbOutput.constData();

    QTime current = QTime::currentTime();
    if (!mLastCrash.isNull() && mLastCrash.secsTo(current) < 60 * 10) {
        qDebug() << "Sent a crash report less than 10 minutes ago, "
            "dropping this one";
        return;
    }

    mLastCrash = current;

    QProcess mail;
    mail.start(QString("mail -s \"Crash report for %1\" %2")
            .arg(mExecutable, QString::fromLocal8Bit(receiver)));

    if (!mail.waitForStarted()) {
        qDebug() << "Failed to launch mail";
        return;
    }

    mail.write(gdbOutput);
    mail.closeWriteChannel();

    if (mail.waitForFinished()) {
        qDebug() << "Crash report sent to" << receiver;
    } else {
        qDebug() << "mail process is not finishing, killing";
        mail.kill();
    }
}
Example #24
0
bool FsInfo::Check()
{
    QProcess p;

    //check that we have the program to convert windows paths to proper cygwin paths
    p.start( "cygpath -v" );
    if( !p.waitForStarted() )
    {
		qCritical() << "failed to start cygpath ( check )";
		return false;
    }

    if( !p.waitForFinished() )
    {
		qCritical() << "!p.waitForFinished() ( winfs stuff )";
		return false;
    }
    if( p.exitCode() != QProcess::NormalExit )
    {
		qCritical() << "exit status ( winfs stuff )" << p.exitCode() << QProcess::NormalExit;
		return false;
    }

    QString output = p.readAll();
    if( !output.contains( "Cygwin pathconv" ) && !output.contains( "Path Conversion Utility" ) )//LITE and full versions
    {
		qCritical() << "cygpath text output wrong ( winfs stuff ):" << output;
		return false;
    }

    //check that we can access wmic to query the filesystems
    //just query the operating system for a test
    p.start( "wmic", QStringList() << "/output:stdout" << "/interactive:off" << "/locale:ms_409" <<\
			 "OS" << "GET" << "caption" );
    if( !p.waitForStarted() )
    {
		qCritical() << "failed to start wmic ( check )";
		return false;
    }
    p.closeWriteChannel();

    if( !p.waitForFinished() )
    {
		qCritical() << "!p.waitForFinished() wmic ( winfs stuff )";
		return false;
    }
    if( p.exitCode() != QProcess::NormalExit )
    {
		qCritical() << "exit status wmic ( winfs stuff )";
		return false;
    }

    output = p.readAll();
    if( !output.contains( "Windows" ) )
    {
		qCritical() << "wmic text output wrong ( winfs stuff ):" << output;
		return false;
    }

    //build a list of the did drive letters so we can skip them later
    for( int j = 0; j < 15; j++ )
    {
        bool ok = false;
        QString tmp = ToWinPath( QString( "/dev/sr%1" ).arg( j ), &ok );
        if( !tmp.endsWith( ":" ) )
            break;

        dvdLetters << tmp;
    }
    return true;
}
void GRASS_EXPORT QgsGrass::init( void )
{
  // Warning!!!
  // G_set_error_routine() once called from plugin
  // is not valid in provider -> call it always

  // Set error function
  G_set_error_routine( &error_routine );

  if ( initialized )
    return;

  QSettings settings;

  // Is it active mode ?
  if ( getenv( "GISRC" ) )
  {
    active = true;
    // Store default values
    defaultGisdbase = G_gisdbase();
    defaultLocation = G_location();
    defaultMapset = G_mapset();
  }
  else
  {
    active = false;
  }

  // Don't use GISRC file and read/write GRASS variables (from location G_VAR_GISRC) to memory only.
  G_set_gisrc_mode( G_GISRC_MODE_MEMORY );

  // Init GRASS libraries (required)
  G_no_gisinit();  // Doesn't check write permissions for mapset compare to G_gisinit("libgrass++");

  // I think that mask should not be used in QGIS as it can only confuses people,
  // anyway, I don't think anybody is using MASK
  G_suppress_masking();

  // Set program name
  G_set_program_name( "QGIS" );

  // Require GISBASE to be set. This should point to the location of
  // the GRASS installation. The GRASS libraries use it to know
  // where to look for things.

  // Look first to see if GISBASE env var is already set.
  // This is set when QGIS is run from within GRASS
  // or when set explicitly by the user.
  // This value should always take precedence.
#if WIN32
  QString gisBase = getenv( "WINGISBASE" ) ? getenv( "WINGISBASE" ) : getenv( "GISBASE" );
  gisBase = shortPath( gisBase );
#else
  QString gisBase = getenv( "GISBASE" );
#endif
  QgsDebugMsg( QString( "GRASS gisBase from GISBASE env var is: %1" ).arg( gisBase ) );
  if ( !isValidGrassBaseDir( gisBase ) )
  {
    // Look for gisbase in QSettings
    gisBase = settings.value( "/GRASS/gisbase", "" ).toString();
    QgsDebugMsg( QString( "GRASS gisBase from QSettings is: %1" ).arg( gisBase ) );
  }

  if ( !isValidGrassBaseDir( gisBase ) )
  {
    // Erase gisbase from settings because it does not exists
    settings.setValue( "/GRASS/gisbase", "" );

#ifdef WIN32
    // Use the applicationDirPath()/grass
    gisBase = shortPath( QCoreApplication::applicationDirPath() + "/grass" );
    QgsDebugMsg( QString( "GRASS gisBase = %1" ).arg( gisBase ) );
#else
    // Use the location specified --with-grass during configure
    gisBase = GRASS_BASE;
    QgsDebugMsg( QString( "GRASS gisBase from configure is: %1" ).arg( gisBase ) );
#endif
  }

  bool userGisbase = false;
  bool valid = false;
  while ( !( valid = isValidGrassBaseDir( gisBase ) ) )
  {

    // ask user if he wants to specify GISBASE
    QMessageBox::StandardButton res = QMessageBox::warning( 0, QObject::tr( "GRASS plugin" ),
                                      QObject::tr( "QGIS couldn't find your GRASS installation.\n"
                                                   "Would you like to specify path (GISBASE) to your GRASS installation?" ),
                                      QMessageBox::Ok | QMessageBox::Cancel );

    if ( res != QMessageBox::Ok )
    {
      userGisbase = false;
      break;
    }

    // XXX Need to subclass this and add explantory message above to left side
    userGisbase = true;
    // For Mac, GISBASE folder may be inside GRASS bundle. Use Qt file dialog
    // since Mac native dialog doesn't allow user to browse inside bundles.
    gisBase = QFileDialog::getExistingDirectory(
                0, QObject::tr( "Choose GRASS installation path (GISBASE)" ), gisBase,
                QFileDialog::DontUseNativeDialog );
    if ( gisBase == QString::null )
    {
      // User pressed cancel. No GRASS for you!
      userGisbase = false;
      break;
    }
#if defined(WIN32)
    gisBase = shortPath( gisBase );
#endif
  }

  if ( !valid )
  {
    // warn user
    QMessageBox::information( 0, QObject::tr( "GRASS plugin" ),
                              QObject::tr( "GRASS data won't be available if GISBASE is not specified." ) );
  }

  if ( userGisbase )
  {
    settings.setValue( "/GRASS/gisbase", gisBase );
  }

  QgsDebugMsg( QString( "Valid GRASS gisBase is: %1" ).arg( gisBase ) );
  putEnv( "GISBASE", gisBase );

  // Add path to GRASS modules
#ifdef WIN32
  QString sep = ";";
#else
  QString sep = ":";
#endif
  QString path = gisBase + "/bin";
  path.append( sep + gisBase + "/scripts" );
  path.append( sep +  QgsApplication::pkgDataPath() + "/grass/scripts/" );

  // On windows the GRASS libraries are in
  // QgsApplication::prefixPath(), we have to add them
  // to PATH to enable running of GRASS modules
  // and database drivers
#ifdef WIN32
  // It seems that QgsApplication::prefixPath()
  // is not initialized at this point
  path.append( sep + shortPath( QCoreApplication::applicationDirPath() ) );

  // Add path to MSYS bin
  // Warning: MSYS sh.exe will translate this path to '/bin'
  if ( QFileInfo( QCoreApplication::applicationDirPath() + "/msys/bin/" ).isDir() )
    path.append( sep + shortPath( QCoreApplication::applicationDirPath() + "/msys/bin/" ) );
#endif

  QString p = getenv( "PATH" );
  path.append( sep + p );

  QgsDebugMsg( QString( "set PATH: %1" ).arg( path ) );
  putEnv( "PATH", path );

  // Set PYTHONPATH
  QString pythonpath = gisBase + "/etc/python";
  QString pp = getenv( "PYTHONPATH" );
  pythonpath.append( sep + pp );
  QgsDebugMsg( QString( "set PYTHONPATH: %1" ).arg( pythonpath ) );
  putEnv( "PYTHONPATH", pythonpath );

  // Set GRASS_PAGER if not set, it is necessary for some
  // modules printing to terminal, e.g. g.list
  // We use 'cat' because 'more' is not present in MSYS (Win)
  // and it doesn't work well in built in shell (Unix/Mac)
  // and 'less' is not user friendly (for example user must press
  // 'q' to quit which is definitely difficult for normal user)
  // Also scroling can be don in scrollable window in both
  // MSYS terminal and built in shell.
  if ( !getenv( "GRASS_PAGER" ) )
  {
    QString pager;
    QStringList pagers;
    //pagers << "more" << "less" << "cat"; // se notes above
    pagers << "cat";

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

      QProcess p;
      p.start( pagers.at( i ) );
      p.waitForStarted();
      state = p.state();
      p.write( "\004" ); // Ctrl-D
      p.closeWriteChannel();
      p.waitForFinished( 1000 );
      p.kill();

      if ( state == QProcess::Running )
      {
        pager = pagers.at( i );
        break;
      }
    }

    if ( pager.length() > 0 )
    {
      putEnv( "GRASS_PAGER", pager );
    }
  }

  initialized = 1;
}
void StdCmdExportGraphviz::activated(int iMsg)
{
    App::Document* doc = App::GetApplication().getActiveDocument();
    std::stringstream str;
    doc->exportGraphviz(str);

    ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/Paths");
    QProcess proc;
    QStringList args;
    args << QLatin1String("-Tpng");
#ifdef FC_OS_LINUX
    QString path = QString::fromUtf8(hGrp->GetASCII("Graphviz", "/usr/bin").c_str());
#else
    QString path = QString::fromUtf8(hGrp->GetASCII("Graphviz").c_str());
#endif
    bool pathChanged = false;
#ifdef FC_OS_WIN32
    QString exe = QString::fromAscii("\"%1/dot\"").arg(path);
#else
    QString exe = QString::fromAscii("%1/dot").arg(path);
#endif
    proc.setEnvironment(QProcess::systemEnvironment());
    do {
        proc.start(exe, args);
        if (!proc.waitForStarted()) {
            int ret = QMessageBox::warning(getMainWindow(),
                                           qApp->translate("Std_ExportGraphviz","Graphviz not found"),
                                           qApp->translate("Std_ExportGraphviz","Graphviz couldn't be found on your system.\n"
                                                   "Do you want to specify its installation path if it's already installed?"),
                                           QMessageBox::Yes, QMessageBox::No);
            if (ret == QMessageBox::No)
                return;
            path = QFileDialog::getExistingDirectory(Gui::getMainWindow(),
                    qApp->translate("Std_ExportGraphviz","Graphviz installation path"));
            if (path.isEmpty())
                return;
            pathChanged = true;
#ifdef FC_OS_WIN32
            exe = QString::fromAscii("\"%1/dot\"").arg(path);
#else
            exe = QString::fromAscii("%1/dot").arg(path);
#endif
        }
        else {
            if (pathChanged)
                hGrp->SetASCII("Graphviz", (const char*)path.toUtf8());
            break;
        }
    }
    while(true);

    proc.write(str.str().c_str(), str.str().size());
    proc.closeWriteChannel();
    if (!proc.waitForFinished())
        return;

    QPixmap px;
    if (px.loadFromData(proc.readAll(), "PNG")) {
        Gui::ImageView* view = new Gui::ImageView(px);
        view->setWindowTitle(qApp->translate("Std_ExportGraphviz","Dependency graph"));
        getMainWindow()->addWindow(view);
    }
    else {
        QMessageBox::warning(getMainWindow(),
                             qApp->translate("Std_ExportGraphviz","Graphviz failed"),
                             qApp->translate("Std_ExportGraphviz","Graphviz failed to create an image file"));
    }
}
Example #27
0
AbstractCommand::ReturnCodes Record::record()
{
    if (! checkInRepository())
        return NotInRepo;
    moveToRoot(CheckFileSystem);

    if (m_mode != Unset)
        m_all = m_mode == AllChanges;
    const bool needHunks = !m_all || m_patchName.isEmpty();

    ChangeSet changeSet;
    changeSet.fillFromCurrentChanges(rebasedArguments(), needHunks);

    changeSet.waitForFinishFirstFile();
    bool shouldDoRecord = changeSet.count() > 0;
    if (!shouldDoRecord) {
        Logger::warn() << "No changes!" << endl;
        return Ok;
    }

    QString email = m_author;
    if (email.isEmpty())
        email = getenv("EMAIL");
    QStringList environment;
    if (! email.isEmpty()) {
        QRegExp re("(.*) <([@\\S]+)>");
        if (re.exactMatch(email)) { // meaning its an email AND name
            environment << "GIT_AUTHOR_NAME="+ re.cap(1);
            environment << "GIT_COMMITTER_NAME="+ re.cap(1);
            environment << "GIT_AUTHOR_EMAIL="+ re.cap(2);
            environment << "GIT_COMMITTER_EMAIL="+ re.cap(2);
        }
        else if (m_author.isEmpty()) { // if its an account or shell wide option; just use the git defs.
            environment << "GIT_AUTHOR_EMAIL="+ email;
            environment << "GIT_COMMITTER_EMAIL="+ email;
        }
        else {
            Logger::error() << "Author format invalid. Please provide author formatted like; `name <email@host>\n";
            return InvalidOptions;
        }
    }

    if (shouldDoRecord && !m_all && m_mode != Index) { // then do interview
        HunksCursor cursor(changeSet);
        cursor.setConfiguration(m_config);
        Interview interview(cursor, name());
        interview.setUsePager(shouldUsePager());
        if (! interview.start()) {
            Logger::warn() << "Cancelled." << endl;
            return UserCancelled;
        }
    }

    if (shouldDoRecord && !m_all && m_mode != Index) { // check if there is anything selected
        shouldDoRecord = changeSet.hasAcceptedChanges();
        if (! shouldDoRecord) {
            Logger::warn() << "Ok, if you don't want to record anything, that's fine!" <<endl;
            return UserCancelled;
        }
    }
    if (dryRun())
        return Ok;

    if ((m_editComment || m_patchName.isEmpty()) && getenv("EDITOR")) {
        class Deleter : public QObject {
        public:
            Deleter() : commitMessage(0) { }
            ~Deleter() {
                if (commitMessage)
                    commitMessage->remove();
            }
            QFile *commitMessage;
        };
        Deleter parent;
        QFile *commitMessage;
        int i = 0;
        do {
            commitMessage = new QFile(QString("vng-record-%1").arg(i++), &parent);
        } while (commitMessage->exists());
        parent.commitMessage = commitMessage; // make sure the file is removed from FS.
        if (! commitMessage->open(QIODevice::WriteOnly)) {
            Logger::error() << "Vng failed. Could not create a temporary file for the record message '"
                << commitMessage->fileName() << "`\n";
            return WriteError;
        }
        const char * defaultCommitMessage1 = "\n***END OF DESCRIPTION***"; // we will look for this string later
        const char * defaultCommitMessage2 = "\nPlace the long patch description above the ***END OF DESCRIPTION*** marker.\n\nThis patch contains the following changes:\n\n";
        if (! m_patchName.isEmpty())
            commitMessage->write(m_patchName);
        else
            commitMessage->write("\n", 1);
        commitMessage->write(defaultCommitMessage1, strlen(defaultCommitMessage1));
        commitMessage->write(defaultCommitMessage2, strlen(defaultCommitMessage2));
        QBuffer buffer;
        changeSet.writeDiff(buffer, m_all ? ChangeSet::AllHunks : ChangeSet::UserSelection);
        ChangeSet actualChanges;
        actualChanges.fillFromDiffFile(buffer);
        QTextStream out (commitMessage);
        for (int i=0; i < actualChanges.count(); ++i) {
            File file = actualChanges.file(i);
            file.outputWhatsChanged(out, m_config, true, false);
        }
        for (int i=0; i < changeSet.count(); ++i) {
            File file = changeSet.file(i);
            if (file.isBinary() && (m_all || file.binaryChangeAcceptance() == Vng::Accepted))
                out << "M " << QString::fromLocal8Bit(file.fileName());
            else if (file.fileName().isEmpty() && (m_all || file.renameAcceptance() == Vng::Accepted))
                out << "D " << QString::fromLocal8Bit(file.oldFileName());
        }
        out.flush();

        commitMessage->close();
        QDateTime modification = QFileInfo(*commitMessage).lastModified();
        QString command = QString("%1 %2").arg(getenv("EDITOR")).arg(commitMessage->fileName());
        int rc = system(command.toAscii().data());
        if (rc != 0) {
            // this will keep patchName empty and we fall through to the interview.
            Logger::warn() << "Vng-Warning: Could not start editor '" << getenv("EDITOR") << "`\n";
            Logger::warn().flush();
        }
        else if (modification == QFileInfo(*commitMessage).lastModified()) {
            Logger::warn() << "unchanged, won't record\n";
            return UserCancelled;
        }
        else {
            // get data until the separator line.
            commitMessage->open(QIODevice::ReadOnly);
            m_patchName = commitMessage->readAll();
            commitMessage->close();
            int cuttoff = m_patchName.indexOf(defaultCommitMessage1);
            if (cuttoff > 0)
                m_patchName.truncate(cuttoff);
            for (int i = m_patchName.length()-1; i >= 0; --i) {
                if (m_patchName[i] == '\n' || m_patchName[i] == '\r' || m_patchName[i] == ' ')
                    m_patchName.resize(i); // shrink
                else break;
            }
        }
    }
    if (m_patchName.isEmpty())
        m_patchName = Interview::ask("What is the patch name? ").toUtf8();

    ReturnCodes rc = addFilesPerAcceptance(changeSet, m_all);
    if (rc != Ok)
        return rc;

    QProcess git;
    QStringList arguments;
    arguments << "write-tree";
    GitRunner runner(git, arguments);
    rc = runner.start(GitRunner::WaitForStandardOutput);
    if (rc != Ok) {
        Logger::error() << "Git write-tree failed!, aborting record\n";
        return rc;
    }
    char buf[1024];
    Vng::readLine(&git, buf, sizeof(buf));
    QString tree(buf);
    git.waitForFinished(); // patiently wait for it to finish..
    Logger::debug() << "The tree got git ref; " << tree;
    Logger::debug().flush(); // flush since we do an ask next

    arguments.clear();
    git.setEnvironment(environment);

    arguments << "commit-tree" << tree.left(40);
    if (!m_config.isEmptyRepo())
        arguments << "-p" << "HEAD" ;

    runner.setArguments(arguments);
    rc = runner.start(GitRunner::WaitUntilReadyForWrite);
    if (rc != Ok) {
        Logger::error() << "Git commit-tree failed!, aborting record\n";
        return rc;
    }
    git.write(m_patchName);
    git.write("\n");
    git.closeWriteChannel();
    Vng::readLine(&git, buf, sizeof(buf));
    QString commit(buf);
    Logger::debug() << "commit is ref; " << commit;
    git.waitForFinished(); // patiently wait for it to finish..
    if (commit.isEmpty()) {
        Logger::error() << "Git update-ref failed to produce a reference!, aborting record\n";
        return GitFailed;
    }
    m_sha1 = commit.left(40);

    arguments.clear();
    arguments << "update-ref" << "HEAD" << m_sha1;
    runner.setArguments(arguments);
    rc = runner.start(GitRunner::WaitUntilFinished);
    if (rc != Ok) {
        Logger::error() << "Git update-ref failed!, aborting record\n";
        return rc;
    }

    // We removed files from the index in case they were freshly added, but the user didn't want it in this commit.
    // we have to re-add those files.
    arguments.clear();
    arguments << "update-index" << "--add";
    for (int i=0; i < changeSet.count(); ++i) {
        File file = changeSet.file(i);
        if (! file.oldFileName().isEmpty())
            continue; // not a new added file.
        if (file.renameAcceptance() == Vng::Rejected)
            arguments.append(file.fileName());
    }
    if (arguments.count() > 2) {
        runner.setArguments(arguments);
        runner.start(GitRunner::WaitUntilFinished);
    }

    int endOfLine = m_patchName.indexOf('\n');
    if (endOfLine > 0)
        m_patchName.truncate(endOfLine);
    Logger::warn() << "Finished recording patch `" << m_patchName << "'" << endl;
    return Ok;
}
Example #28
0
bool BabelFileFormat::read(std::istream &input, chemkit::MoleculeFile *file)
{
    // get input format to use
    std::string format = option("format").toString();
    if(format.empty()){
        setErrorString("No format set for Babel conversion.");
        return false;
    }

    // setup babel arguments
    QStringList arguments;
    arguments.append(QString("-i") + format.c_str());
    arguments.append("-");
    arguments.append("-ocml");
    arguments.append("-");

    // create and start the babel process
    QProcess babel;
    babel.start("babel", arguments);
    if(!babel.waitForStarted()){
        setErrorString("Failed to start Babel process.");
        return false;
    }

    // write input data to babel via stdin
    while(!input.eof()){
        char buffer[1024];
        input.read(buffer, sizeof(buffer));
        babel.write(buffer, input.gcount());
    }

    babel.closeWriteChannel();

    // wait until the babel process is finished
    if(!babel.waitForFinished()){
        setErrorString("Babel process never finished.");
        return false;
    }

    // check babel's exit status
    if(babel.exitCode() != QProcess::NormalExit){
        setErrorString("Babel process crashed.");
        return false;
    }

    // read output data to string buffer
    std::stringstream buffer;
    buffer << babel.readAll().constData();

    // parse cml output file
    chemkit::MoleculeFile outputFile;
    outputFile.setFormat("cml");
    bool ok = outputFile.read(buffer);
    if(!ok){
        setErrorString("Failed to parse Babel's CML output: " + outputFile.errorString());
        return false;
    }

    // add molecules to file
    foreach(const boost::shared_ptr<chemkit::Molecule> &molecule, outputFile.molecules()){
        file->addMolecule(molecule);
    }

    return true;
}
Example #29
0
int main(int argc, char *argv[]) {

	QString input;
	QString output;
	QByteArray onlyStartingWith;
	QByteArray onlyEndingWith;
	bool removePrefix = false;
	QCoreApplication app(argc, argv);
	if (argc == 1) {
		printUsage();
		return 0;
	}
	QStringList args = app.arguments();
	for (QStringList::Iterator i = ++args.begin(); i != args.end(); i++) {
		QString arg = *i;
		if (arg.startsWith('-')) { //option
			if (arg.length() == 1) {
				cerr << "Error: Invalid option '-'\n";
				return 1;
			}

			if (arg.length() == 2) {
				switch (arg[1].toLatin1()) {
					case 'o':
						if (i + 1 != args.end()) {
							if (!output.isEmpty()) {
								cerr << "Error: Output file is defined multiple times\n";
								return 1;
							}
							output = *(++i);
							continue;
						}
						else {
							cerr << "Error: Expecting a parameter after '-o'\n";
							return 1;
						}
					case 's':
						if (i + 1 != args.end()) {
							if (!onlyStartingWith.isEmpty()) {
								cerr << "Error: -s flag is defined multiple times\n";
								return 1;
							}
							onlyStartingWith = (*(++i)).toLatin1();
							continue;
						}
						else {
							cerr << "Error: Expecting a parameter after '-s'\n";
							return 1;
						}
					case 'e':
						if (i + 1 != args.end()) {
							if (!onlyEndingWith.isEmpty()) {
								cerr << "Error: -e is defined multiple times\n";
								return 1;
							}
							onlyEndingWith = (*(++i)).toLatin1();
							continue;
						}
						else {
							cerr << "Error: Expecting a parameter after '-e'\n";
							return 1;
						}
					case 'h':
						printUsage();
						return 0;
					case 'p':
						removePrefix = true;
						continue;
					/*case 'c':
						exportClasses = true;
						continue; */
				}
			}
			cerr << "Error: Invalid parameter '" << qPrintable(arg) << "'\n";
			return 1;
		} else {
			if (!input.isEmpty()) {
				cerr << "Error: Input file already defined";
				return 1;
			}
			input = arg;
		}
	}

	if (input.isEmpty()) {
		cerr << "Error: Input file is not specified\n";
		return 1;
	}
	else {
		cout << "Input file: " << qPrintable(input) << endl;
	}

	if (output.isEmpty()) {
		output = input + ".out";
	}
	cout << "Output file: " << qPrintable(output) << endl;

	if (!onlyStartingWith.isEmpty()) {
		cout << "Outputting only names starting with " << qPrintable(onlyStartingWith) << endl;
	}

	if (!onlyEndingWith.isEmpty()) {
		cout << "Outputting only names ending with " << qPrintable(onlyEndingWith) << endl;
	}

	llvm::SMDiagnostic diagnostic;
	llvm::Module *module = llvm::ParseIRFile(input.toStdString(), diagnostic, llvm::getGlobalContext());
	if (!module) {
		cerr << diagnostic.getMessage().data() << endl;
		return 2;
	}

	cout << "Starting exporting" << endl;

	QList<QByteArray> mangledNames;
	for (llvm::Module::FunctionListType::iterator i = module->getFunctionList().begin(); i != module->getFunctionList().end(); i++) {
		QByteArray n = QByteArray(i->getName().data());
		mangledNames.append(n);
		//cout << n.data() << '\n';
	}

	QProcess process;
	process.start("c++filt -s gnu-v3");
	if (!process.waitForStarted()) {
		cerr << "Can't start c++filt";
		return 0;
	}
	cout << "c++filt started" << endl;
	int counter = 0;
	QList<QByteArray> demangledNames;
	for (QList<QByteArray>::ConstIterator i = mangledNames.begin(); i != mangledNames.end(); i++) {
#ifdef Q_OS_WIN32
		if (i->startsWith('_')) {
			process.write('_' + *i + '\n');
		}
		else {
			process.write(*i + '\n');
		}
#else
		process.write(*i + '\n');
#endif
		if (counter == 100) {
			cout << "Waiting for writing" << endl;
			process.waitForBytesWritten();
			cout << "Waiting for reading" << endl;
			process.waitForReadyRead();
			QByteArray s = process.readAll();
			demangledNames.append(s.split('\n'));
			counter = 0;
		}
		counter++;
	}
	cout << "Waiting for writing" << endl;
	process.waitForBytesWritten();
	process.closeWriteChannel();
	if (counter > 0) {
		cout << "Waiting for reading" << endl;
		process.waitForReadyRead();
	}
	process.waitForFinished();
	QByteArray s = process.readAll();
	demangledNames.append(s.split('\n'));
	QFile file(output);
	if (!file.open(QFile::WriteOnly)) {
		cerr << "Can't open output file " << qPrintable(output) << endl;
		return -1;
	}


	cout << "Demangled items: "  << demangledNames.size();
	int index = -1;
	for (QByteArray name : demangledNames) {
		if (name.isEmpty()) continue;
		index++;
		//cout <<  name.data();
		if (!onlyStartingWith.isEmpty()) {
			if (!name.startsWith(onlyStartingWith)) {
				continue;
			} else if (removePrefix) {
				name = name.mid(onlyStartingWith.length());
			}
		}

		int parameterListStart = name.indexOf('(');
		int templateParamListStart = name.indexOf('<');
		if (parameterListStart == -1) {
			cerr << "Invalid mangled name: " << name.data() << endl;
			continue;
		}
		if (templateParamListStart != -1 && templateParamListStart < parameterListStart)
			name = name.left(templateParamListStart);
		else
			name = name.left(parameterListStart).trimmed();

		if (!onlyEndingWith.isEmpty() && !name.endsWith(onlyEndingWith)) {
			continue;
		}
		file.write(name  + "=" + mangledNames[index] + "\n");
	}
	file.close();

	cout << "Exporting succeeded" << endl;
	return 0;
}
Example #30
0
int main(int argc, char *argv[])
{
    try {

        QApplication app(argc, argv);

        QString commands;
        //Mac specific Terminal command
         commands = "system_profiler SPHardwareDataType";

         //commands = "cat abc"; /* Wrong cat file -- testing */
        //commands = " abc";   /* Wrong Terminal command -- testing */


        /* For Linux and Ubuntu we use  --  cat /proc/cpuinfo*/

            QQmlApplicationEngine engine;
            engine.load(QUrl(QStringLiteral("qrc:/main.qml")));


            QProcess *process = new QProcess(0);
            process->setProcessChannelMode(QProcess::MergedChannels);
            //process->start("system_profiler SPHardwareDataType");

            process->start(commands);
            QByteArray arrSysInfo;

            process->write(arrSysInfo);
            process->closeWriteChannel();


             if(!process->waitForStarted()){
                qDebug() << "Could not wait to start..."
                        << process->error()
                        << process->errorString();
            }

            if(!process->waitForFinished()) {
               qDebug() << "Could not wait to finish..."
               << process->error()
               << process->errorString();
            }
            else{

             mySysInfo output;  /*  interface */
             output.setData( process->readAll());

             QObject *rootObject = engine.rootObjects().first();


             QObject* lstview = rootObject->findChild<QObject*>("lstview");
             if (lstview)
                 lstview->setProperty("placeholderText", output.getData());//quick fix

            }

           return app.exec();

        } catch(std::exception e) {\
                qDebug() << "Exception caught in main()"
                << e.what();


        }

}