void UncrustifySettings::createDocumentationFile() const
{
    QProcess process;
    process.start(command(), QStringList() << QLatin1String("--show-config"));
    process.waitForFinished(2000); // show config should be really fast.
    if (process.error() != QProcess::UnknownError)
        return;

    QFile file(documentationFilePath());
    const QFileInfo fi(file);
    if (!fi.exists())
        fi.dir().mkpath(fi.absolutePath());
    if (!file.open(QIODevice::WriteOnly | QIODevice::Truncate | QIODevice::Text))
        return;

    bool contextWritten = false;
    QXmlStreamWriter stream(&file);
    stream.setAutoFormatting(true);
    stream.writeStartDocument(QLatin1String("1.0"), true);
    stream.writeComment(QLatin1String("Created ")
                        + QDateTime::currentDateTime().toString(Qt::ISODate));
    stream.writeStartElement(QLatin1String(Constants::DOCUMENTATION_XMLROOT));

    const QStringList lines = QString::fromUtf8(process.readAll()).split(QLatin1Char('\n'));
    const int totalLines = lines.count();
    for (int i = 0; i < totalLines; ++i) {
        const QString &line = lines.at(i);
        if (line.startsWith(QLatin1Char('#')) || line.trimmed().isEmpty())
            continue;

        const int firstSpace = line.indexOf(QLatin1Char(' '));
        const QString keyword = line.left(firstSpace);
        const QString options = line.right(line.size() - firstSpace).trimmed();
        QStringList docu;
        while (++i < totalLines) {
            const QString &subline = lines.at(i);
            if (line.startsWith(QLatin1Char('#')) || subline.trimmed().isEmpty()) {
                const QString text = QLatin1String("<p><span class=\"option\">") + keyword
                        + QLatin1String("</span> <span class=\"param\">") + options
                        + QLatin1String("</span></p><p>")
                        + (docu.join(QLatin1Char(' ')).toHtmlEscaped())
                        + QLatin1String("</p>");
                stream.writeStartElement(QLatin1String(Constants::DOCUMENTATION_XMLENTRY));
                stream.writeTextElement(QLatin1String(Constants::DOCUMENTATION_XMLKEY), keyword);
                stream.writeTextElement(QLatin1String(Constants::DOCUMENTATION_XMLDOC), text);
                stream.writeEndElement();
                contextWritten = true;
                break;
            } else {
                docu << subline;
            }
        }
    }

    stream.writeEndElement();
    stream.writeEndDocument();

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

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

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

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

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

  QTextStream out(stdout, QIODevice::WriteOnly);

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

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

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

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

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

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

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

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

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

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

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

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

    return EXIT_SUCCESS;
  }


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

  ctkCLModuleExplorerMainWindow mainWindow;

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

  mainWindow.show();

  return myApp.exec();
}
Example #4
0
CompressedFileMangaVolume::CompressedFileMangaVolume(const QString & filepath, QObject *parent, bool do_cleanup)
    : DirectoryMangaVolume(parent), m_do_cleanup(do_cleanup) {
    QStringList path_split = filepath.split("/");
    QString filename = path_split.last();
    QStringList filename_split = filename.split(".");
    if (filename_split.length() > 1) {
        filename_split.pop_back();
    }

    QDir dir;
    do {
        // keep trying hashes until dir exists.
        // no one could have taken all hashes
        QTime time = QTime::currentTime();
        QString toHash = filepath+time.toString();
        qWarning() <<  toHash;
        QString hash = QString(QCryptographicHash::hash(
                                   toHash.toAscii(),
                                   QCryptographicHash::Sha1).toHex());
        m_file_dir = tr("/tmp/") + filename_split.join(tr("."))
                + tr("-") + hash;
        qWarning() << "Making directory: " << m_file_dir;
        dir = QDir(m_file_dir);
    } while (dir.exists());
    dir.mkpath(".");

    QString program = "";
    QStringList arguments;
    if (filename.endsWith(tr(".zip"))) {
        program = tr("unzip");
        arguments << tr("-d") << m_file_dir;
        arguments << filepath;
    } else if (filename.endsWith(tr(".rar"))) {
        program = tr("unrar");
        arguments << tr("x");
        arguments << filepath;
        arguments << m_file_dir;
    } else {
        qWarning() << "Unknown filetype for file " << filename;
        return;
    }

    qWarning() << "Open file?: " << filename;
    QProcess * myProcess = new QProcess(this);

    // Start the extraction program
    myProcess->start(program, arguments);

    // Check to make sure it started correctly
    if (!myProcess->waitForStarted()) {
        switch (myProcess->error()) {
        case QProcess::FailedToStart:
            qWarning() << "Failed to start program" << program << ". Is it installed correctly?";
            break;
        case QProcess::Crashed:
            qWarning() << "Program" << program << "crashed.";
            break;
        default:
            qWarning() << "QProcess::ProcessError code " << myProcess->error();
        }
        return;
    }

    // Check to make sure it finished correctly
    if (!myProcess->waitForFinished()) {
        qWarning() << program << "was unable to extract file " << filepath;
        // TODO(umbrant): capture stdout/stderr to show the user
        return;
    }

    // Successful extraction
    qWarning() << "Extracted successfully";
    m_do_cleanup = true;
    readImages(m_file_dir);
    for (const MangaPage& page: m_pages) {
        page.getFilename().size();
        // TODO(mtao): processing?
    }
}
Example #5
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 #6
0
bool generate(const ToolListType & tools, const String & prefix, const String & binary_directory)
{
  bool errors_occured = false;
  for (ToolListType::const_iterator it = tools.begin(); it != tools.end(); ++it)
  {
    //start process
    QProcess process;
    process.setProcessChannelMode(QProcess::MergedChannels);
    QStringList env = QProcess::systemEnvironment();
    env << String("COLUMNS=110").toQString(); // Add an environment variable (used by each TOPP tool to determine width of help text (see TOPPBase))
    process.setEnvironment(env);

    String command = binary_directory + it->first;
#if defined(__APPLE__)
    if (it->first == "TOPPView" || it->first == "TOPPAS")
    {
      command = binary_directory + it->first + ".app/Contents/MacOS/" + it->first;
    }
#endif
#ifdef OPENMS_WINDOWSPLATFORM
	command += ".exe"; // otherwise File::exists() will fail
#endif

    ofstream f((String("output/") + prefix + it->first + ".cli").c_str());
	if (!File::exists(command))
	{
	  stringstream ss;
	  ss << "Errors occurred while generating the command line documentation for " << it->first << "!" << endl;
      ss << "Tool could not be found at '" << command << "'\n " << command << endl;
	  f << ss.str();
	  cerr << ss.str();
      errors_occured = true;
	  f.close();
	  continue;
 	}
	else
	{
      process.start(String(command + " --help").toQString());
	  process.waitForFinished();

	  std::string lines = QString(process.readAll()).toStdString();
	  if (process.error() != QProcess::UnknownError)
	  {
	    // error while generation cli docu
	    stringstream ss;
	    f << "Errors occurred while generating the command line documentation for " << it->first << "!" << endl;
	    f << "Output was: \n" << lines << endl;
	    f << "Command line was: \n " << command << endl;
	    f << ss.str();
	    cerr << ss.str();
        errors_occured = true;
	    f.close();
	    continue;
	  }
	  else
	  {
	  // write output
	    f << lines;
	  }
	}
    f.close();

    //////
    // get the INI file and convert it into HTML
    //////
    if (it->first == "GenericWrapper")
      continue;                                  // does not support -write_ini without a type
    if (it->first == "TOPPView")
      continue;                            // does not support -write_ini
    if (it->first == "TOPPAS")
      continue;                          // does not support -write_ini
    String tmp_file = File::getTempDirectory() + "/" + File::getUniqueName() + "_" + it->first + ".ini";
    process.start((command + " -write_ini " + tmp_file).toQString());
    process.waitForFinished();
    Param p;
    ParamXMLFile pf;
    pf.load(tmp_file, p);
    File::remove(tmp_file);
    ofstream f_html((String("output/") + prefix + it->first + ".html").c_str());
    convertINI2HTML(p, f_html);
    f_html.close();
  }
  return errors_occured;
}
Example #7
0
// actually execute the command here
int AdminThread::executeScript(const QString &command)
{
    // Qt standard stream output
    QTextStream out(stdout);
    //out << tr("Qt signing out from thread!!") << endl;

    int i;
    int &ref = i;
    QString str;
    emit signalOutput(command);
    emit signalOutput("\n");

    // debugging output in threads works
    //qDebug("Hello world from thread!");

    // C++ standard stream output
    //cout << "Goodbye World from thread!!" << endl;
    //str = tr("Goodbye World 2!");
    //cout << str.toStdString() << endl;
    //fflush(stdout);

    out << tr("about to start: %1").arg(command) << endl;

    QProcess process;
    //process.start("/home/oliver/projects/vm/test");
    process.start(command);

    // now read the output line by line
    // and send to calling thread
    //char buf[1024];
    //qint64 lineLength;
    QString stdout;

    if (!process.waitForStarted())
        return false;

    // signal process is now running
    running = true;
    emit signalRunning(running);

    out << tr("started: %1").arg(command) << endl;

    while (!stop && !abort) {
        // wait for output on timeout or process finished for some reason
        if (!process.waitForReadyRead()) {
            // process finished for some reason so exit from output loop
            out << tr("nothing left to read") << endl;
            break;
        }
        stdout = process.readAllStandardOutput();
        //lineLength = process.readLine(buf, sizeof(buf));
        //if (lineLength == -1) {
            // end of stream
        //    break;
        //}
        emit signalOutput(stdout);
        out << tr("line...") << endl;
        //emit signalOutput("zzz\n");
    }

    int  ec = process.exitCode();
    int  es = process.exitStatus();
    int  er = process.error();
    int  st = process.state();

    out << "Exit code: " + QString::number(ec) << endl;
    out << "Exit status: " + QString::number(es) << endl;
    out << "Error: " + QString::number(er) << endl;
    out << "State: " + QString::number(st) << endl;

    // wait for process to terminate, if it hasn't stopped already
    process.close();

    out << tr("finished: %1").arg(command) << endl;

    ec = process.exitCode();    // exit code from process run eg
                                // 0 - exit OK
                                // 1 - exit with some error
    es = process.exitStatus();  // 0 - OK
                                // 1 - crash/kill
    er = process.error();       // 0 - failed to start
                                // 1 - crashed
                                // 2 - timedout - can recall waitFor
                                // 3 - write error
                                // 4 - read error
                                // 5 - unknown (default)
    st = process.state();       // 0 - not running
                                // 1 - starting
                                // 2 - running

    out << "Exit code: " + QString::number(ec) << endl;
    out << "Exit status: " + QString::number(es) << endl;
    out << "Error: " + QString::number(er) << endl;
    out << "State: " + QString::number(st) << endl;

    //if (!process.waitForFinished())
    //    return false;

    //process.waitForFinished(-1); // will wait forever until finished
    //QString stdout = process.readAllStandardOutput();
    //QString stderr = process.readAllStandardError();

    //emit signalStatus(i);
    //emit signalOutput(stdout);

    // signal process is now stopped
    running = false;
    emit signalRunning(running);

    // successful execution - return 0
    emit signalResult(0);
    return 0;
}
Example #8
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();


        }

}
void TestBinRunner::_run_stuff()
{
    ///
    /// initialization

    // get arguments
    // avoid first argument (i.e., parent binary)
    QStringList args;
    for (int i = 1; i < _argc; i++)
        args << _argv[i];

    // declare process and output binder
    QProcess* pro;
    QtOutputBinder* qob;

    ///
    /// execute tests binaries
    for (std::list<TestSuiteDescriptor>::const_iterator ci = _testbins.begin();
         ci != _testbins.end();
         ++ci){

        // get path and name
        QString binid((*ci).id.c_str());
        QString binpath((*ci).path.c_str());
        QString bindesc((*ci).description.c_str());

        _running_instance = (*ci);

        std::cout << "+---------------------------------------------------------" << std::endl
                  << "  Executing: " << binpath.toStdString() << std::endl;

        // execute test bin

        // create process and connect output
        pro = new QProcess();
        qob = new QtOutputBinder(pro);
        qob->set_enabled(true);// enable for debugging

        // connect signal handlers
        pro->connect(pro,SIGNAL(error(QProcess::ProcessError)),this, SLOT(_qprocess_error_handler(QProcess::ProcessError)));
        //pro->connect(pro,SIGNAL(finished(int,QProcess::ExitStatus)),this, SLOT(_qprocess_finished_handler(int,QProcess::ExitStatus)));

        // execute binary and wait for it
        pro->start(binpath,args,QIODevice::ReadWrite | QIODevice::Text);

        if(!pro->waitForFinished()) // beware the timeout default parameter
        {
            std::cerr << "Error: Executing program failed with exit code " << pro->exitCode() << std::endl;
            _qprocess_error_handler(pro->error());
        }

        // do output stuff
        std::cout << "  Collecting output" << std::endl;
        _do_output_options();

        // clean
        pro->close();
        delete pro; delete qob;
        std::cout << "  Finished" << std::endl;

        // sleep if set
        _check_pause_between();
    }
}