Example #1
0
/** Runs the specified command (should be ffmpeg) and allows for progress feedback.
 *
 *  @param[in]  strCmd A string containing the command to execute and
 *              all of its arguments
 *  @param[out] progress A function that takes one float argument
 *              (the percentage of the ffmpeg operation complete) and
 *              may display the output to the user in any way it
 *              sees fit.
 *
 *  executeFFMpeg does not allow for writing direct input, the only
 *  input through the "-i" argument to specify input files on the disk.
 *
 *  @return Returns Status::OK if everything went well, and Status::FAIL
 *  and error is detected (usually a non-zero exit code for ffmpeg).
 */
Status MovieExporter::executeFFMpeg(QString strCmd, std::function<void(float)> progress)
{
    qDebug() << strCmd;

    QProcess ffmpeg;
    ffmpeg.setReadChannel(QProcess::StandardOutput);
    // FFmpeg writes to stderr only for some reason, so we just read both channels together
    ffmpeg.setProcessChannelMode(QProcess::MergedChannels);
    ffmpeg.start(strCmd);
    if (ffmpeg.waitForStarted() == true)
    {
        while(ffmpeg.state() == QProcess::Running)
        {
            if(!ffmpeg.waitForReadyRead()) break;

            QString output(ffmpeg.readAll());
            QStringList sList = output.split(QRegExp("[\r\n]"), QString::SkipEmptyParts);
            for (const QString& s : sList)
            {
                qDebug() << "[stdout]" << s;
            }

            if(output.startsWith("frame="))
            {
                QString frame = output.mid(6, output.indexOf(' '));

                progress(frame.toInt() / static_cast<float>(mDesc.endFrame - mDesc.startFrame));
            }
        }

        QString output(ffmpeg.readAll());
        QStringList sList = output.split(QRegExp("[\r\n]"), QString::SkipEmptyParts);
        for (const QString& s : sList)
        {
            qDebug() << "[ffmpeg]" << s;
        }

        if(ffmpeg.exitStatus() != QProcess::NormalExit)
        {
            qDebug() << "ERROR: FFmpeg crashed";
            return Status::FAIL;
        }
    }
    else
    {
        qDebug() << "ERROR: Could not execute FFmpeg.";
        return Status::FAIL;
    }
    return Status::OK;
}
Example #2
0
int qc_run_program_or_command(const QString &prog, const QStringList &args, const QString &command, QByteArray *out, bool showOutput)
{
	if(out)
		out->clear();

	QProcess process;
	process.setReadChannel(QProcess::StandardOutput);

	if(!prog.isEmpty())
		process.start(prog, args);
	else if(!command.isEmpty())
		process.start(command);
	else
		return -1;

	if(!process.waitForStarted(-1))
		return -1;

	QByteArray buf;

	while(process.waitForReadyRead(-1))
	{
		buf = process.readAllStandardOutput();
		if(out)
			out->append(buf);
		if(showOutput)
			fprintf(stdout, "%s", buf.data());

		buf = process.readAllStandardError();
		if(showOutput)
			fprintf(stderr, "%s", buf.data());
	}

	buf = process.readAllStandardError();
	if(showOutput)
		fprintf(stderr, "%s", buf.data());

	// calling waitForReadyRead will cause the process to eventually be
	//   marked as finished, so we should not need to separately call
	//   waitForFinished. however, we will do it anyway just to be safe.
	//   we won't check the return value since false could still mean
	//   success (if the process had already been marked as finished).
	process.waitForFinished(-1);

	if(process.exitStatus() != QProcess::NormalExit)
		return -1;

	return process.exitCode();
}
Example #3
0
void Tmpl::ready()
{
    for (QList<TmplExpand>::iterator it = tmpls.begin(); it != tmpls.end(); ++it){
        QProcess *p = it->process;
        if (p && p->state() == QProcess::NotRunning){
            if (p->exitStatus() == QProcess::NormalExit){
                it->bReady = true;
                p->setReadChannel(QProcess::StandardOutput);
                it->res += QString::fromLocal8Bit(p->readAll());
                QTimer::singleShot(0, this, SLOT(clear()));
                return;
            }
        }
    }
}
bool AbstractTool::startProcess(QProcess &process, const QString &program, const QStringList &args, bool mergeChannels)
{
	QMutexLocker lock(&s_mutexStartProcess);
	log(commandline2string(program, args) + "\n");

	process.setWorkingDirectory(QDir::tempPath());

	if(mergeChannels)
	{
		process.setProcessChannelMode(QProcess::MergedChannels);
		process.setReadChannel(QProcess::StandardOutput);
	}
	else
	{
		process.setProcessChannelMode(QProcess::SeparateChannels);
		process.setReadChannel(QProcess::StandardError);
	}

	process.start(program, args);
	
	if(process.waitForStarted())
	{
		m_jobObject->addProcessToJob(&process);
		MUtils::OS::change_process_priority(&process, m_preferences->getProcessPriority());
		lock.unlock();
		return true;
	}

	log("Process creation has failed :-(");
	QString errorMsg= process.errorString().trimmed();
	if(!errorMsg.isEmpty()) log(errorMsg);

	process.kill();
	process.waitForFinished(-1);
	return false;
}
Example #5
0
QString execute(QString command, QStringList arguments, bool mergeErrorStream)
{
    QProcess process;
    process.setReadChannel(QProcess::StandardOutput);
    if (mergeErrorStream)
        process.setProcessChannelMode(QProcess::MergedChannels);
    process.start(command, arguments);
    if (!process.waitForStarted())
        return QString();
    if (!process.waitForFinished())
        return QString();

    QByteArray result = process.readAll();
    return QString::fromUtf8(result);
}
Example #6
0
QString Nepomuk2::OfficeExtractor::textFromFile(const QUrl &fileUrl, const QString &command, QStringList &arguments)
{
    arguments << fileUrl.toLocalFile();

    // Start a process and read its standard output
    QProcess process;

    process.setReadChannel(QProcess::StandardOutput);
    process.start(command, arguments, QIODevice::ReadOnly);
    process.waitForFinished();

    if (process.exitStatus() != QProcess::NormalExit || process.exitCode() != 0)
        return QString();
    else
        return QString::fromUtf8(process.readAll());
}
Example #7
0
bool PackageInfo::ReadFromFile(QString sName)
{
	QProcess procInfo;

	procInfo.setReadChannel(QProcess::StandardOutput);
	procInfo.start("dpkg-deb", QStringList() << "-f" << sName);
	procInfo.waitForFinished(3000);

	if (procInfo.exitStatus() == QProcess::NormalExit) {
		m_qsFilename = sName;
		return ParsePackageInfo(&procInfo);
	}
	else {
		qDebug() << procInfo.readAllStandardError();
	}

	return false;
}
void OscapScannerBase::watchStdErr(QProcess& process)
{
    process.setReadChannel(QProcess::StandardError);

    QString errorMessage("");

    while (process.canReadLine())
    {
        // Trailing \n is returned by QProcess::readLine
        errorMessage += process.readLine();
    }

    if (!errorMessage.isEmpty())
    {
        emit warningMessage(QObject::tr("The 'oscap' process has written the following content to stderr:\n"
                                        "%1").arg(errorMessage));
    }
}
Example #9
0
QString VersionChecker::getVersion()
{
	QProcess process;
	process.start(m_app, QStringList() << "--version");

	process.setReadChannel(QProcess::StandardOutput);
	if (process.waitForStarted() && process.waitForFinished())
	{
		QRegExp rx(VERSION_REGEX);
		QString text = process.readLine();
		if (rx.indexIn(text) != -1)
		{
			return rx.cap(1);
		}
	}

	return tr("Unknown");
}
Example #10
0
// when create is pressed
void MainWindow::on_Create_clicked()
{
    // declarations
    QMessageBox Finished;
    QString Message;
    QProcess bximage;
    QStringList arguments;
    int size2;
    bool ok;
    size_t BufSize = 1024;
    char buf[BufSize];
    QString currentPath;

    // make size argument
    size2 = Size.toInt(&ok, 10);
    snprintf(buf, BufSize, "-size=%i", size2);
    Size = QString::fromAscii(buf);

    // put bximage arugments in arguments
    arguments << type << format;
    arguments << Size << "-q";
    arguments << path;

    // print arguments
    for(int count = 0; count < 5; count++)
        qDebug() << arguments[count];

    // print current path
    currentPath = QDir::currentPath();
    qDebug() << currentPath;

    // start bximage
    bximage.setReadChannel(QProcess::StandardOutput);
    bximage.setWorkingDirectory(QString(QDir::currentPath()));
    bximage.start("bximage", arguments);
    bximage.waitForStarted(-1);

    // make messagebox
    Message = path + QString(" has been created");
    Finished.setWindowTitle("Finished");
    Finished.setText(Message);
    Finished.setIcon(QMessageBox::Information);
    Finished.exec();
}
Example #11
0
/*
 * Setup QPorcess object
 */
void lamexp_init_process(QProcess &process, const QString &wokringDir, const bool bReplaceTempDir)
{
	//Environment variable names
	static const char *const s_envvar_names_temp[] =
	{
		"TEMP", "TMP", "TMPDIR", "HOME", "USERPROFILE", "HOMEPATH", NULL
	};
	static const char *const s_envvar_names_remove[] =
	{
		"WGETRC", "SYSTEM_WGETRC", "HTTP_PROXY", "FTP_PROXY", "NO_PROXY", "GNUPGHOME", "LC_ALL", "LC_COLLATE", "LC_CTYPE", "LC_MESSAGES", "LC_MONETARY", "LC_NUMERIC", "LC_TIME", "LANG", NULL
	};

	//Initialize environment
	QProcessEnvironment env = process.processEnvironment();
	if(env.isEmpty()) env = QProcessEnvironment::systemEnvironment();

	//Clean a number of enviroment variables that might affect our tools
	for(size_t i = 0; s_envvar_names_remove[i]; i++)
	{
		env.remove(QString::fromLatin1(s_envvar_names_remove[i]));
		env.remove(QString::fromLatin1(s_envvar_names_remove[i]).toLower());
	}

	const QString tempDir = QDir::toNativeSeparators(lamexp_temp_folder2());

	//Replace TEMP directory in environment
	if(bReplaceTempDir)
	{
		for(size_t i = 0; s_envvar_names_temp[i]; i++)
		{
			env.insert(s_envvar_names_temp[i], tempDir);
		}
	}

	//Setup PATH variable
	const QString path = env.value("PATH", QString()).trimmed();
	env.insert("PATH", path.isEmpty() ? tempDir : QString("%1;%2").arg(tempDir, path));
	
	//Setup QPorcess object
	process.setWorkingDirectory(wokringDir);
	process.setProcessChannelMode(QProcess::MergedChannels);
	process.setReadChannel(QProcess::StandardOutput);
	process.setProcessEnvironment(env);
}
Example #12
0
static ProbeABI qtVersionFromExec(const QString &path)
{
    ProbeABI abi;

    // yep, you can actually execute QtCore.so...
    QProcess proc;
    proc.setReadChannelMode(QProcess::SeparateChannels);
    proc.setReadChannel(QProcess::StandardOutput);
    proc.start(path);
    proc.waitForFinished();
    const QByteArray line = proc.readLine();
    const int pos = line.lastIndexOf(' ');
    const QList<QByteArray> version = line.mid(pos).split('.');
    if (version.size() < 3)
        return abi;

    abi.setQtVersion(version.at(0).toInt(), version.at(1).toInt());

    return abi;
}
Example #13
0
// we use syntool to authenticate because Qt's http library is very
// unreliable, and since we're writing platform specific code, use the
// synergy code since there we can use integ tests.
QString PremiumAuth::request(const QString& email, const QString& password)
{
	QString program(QCoreApplication::applicationDirPath() + "/syntool");
	QStringList args("--premium-auth");

	QProcess process;
	process.setReadChannel(QProcess::StandardOutput);
	process.start(program, args);
	bool success = process.waitForStarted();

	QString out, error;
	if (success)
	{
		// hash password in case it contains interesting chars.
		QString credentials(email + ":" + hash(password) + "\n");
		process.write(credentials.toStdString().c_str());

		if (process.waitForFinished()) {
			out = process.readAllStandardOutput();
			error = process.readAllStandardError();
		}
	}

	out = out.trimmed();
	error = error.trimmed();

	if (out.isEmpty() ||
		!error.isEmpty() ||
		!success ||
		process.exitCode() != 0)
	{
		throw std::runtime_error(
			QString("Code: %1\nError: %2")
				.arg(process.exitCode())
				.arg(error.isEmpty() ? "Unknown" : error)
				.toStdString());
	}

	return out;
}
Example #14
0
void makeShader() {
       QStringList files;
       files << "i420_to_rgb_simple.cpp" << "i420_to_rgb_filter.cpp" << "i420_to_rgb_kernel.cpp";
       for (int i=0; i<files.size(); ++i) {
	       qDebug() << "Interpret" << files[i];
	       QProcess proc;
	       proc.setReadChannel(QProcess::StandardOutput);
	       QStringList args;
	       args << "-E" << files[i];
	       proc.start("g++", args, QProcess::ReadOnly);
	       const bool ready = proc.waitForReadyRead();
	       Q_ASSERT(ready);
	       QList<QByteArray> lines = proc.readAllStandardOutput().split('\n');
	       QByteArray output;
	       for (int j=0; j<lines.size(); ++j) {
		       if (!lines[j].startsWith('#')) {
			       output += lines[j];
			       output += '\n';
		       }
	       }

	       if (!proc.waitForFinished())
		       proc.kill();
	       Interpreter interpreter;
	       if (!interpreter.interpret(output))
		       qFatal("Interpreter Error: %s", qPrintable(interpreter.errorMessage()));
	       const QFileInfo info(files[i]);
	       const QString base = info.completeBaseName();
	       QFile fp(base + ".fp");
	       fp.open(QFile::WriteOnly | QFile::Truncate);
	       Q_ASSERT(fp.isOpen());
	       fp.write(interpreter.code());
	       fp.close();
	       args.clear();
	       args << "-i" << (base + ".fp") << ("../" + base + ".hpp");
	       proc.start("xxd", args, QProcess::ReadOnly);
	       if (!proc.waitForFinished())
		       proc.kill();
       }
}
void PlatformPicaxe::upload(QWidget *source, const QString &port, const QString &board, const QString &fileLocation)
{
    // see http://www.picaxe.com/docs/beta_compiler.pdf
    QProcess * process = new QProcess(this);
    process->setProcessChannelMode(QProcess::MergedChannels);
    process->setReadChannel(QProcess::StandardOutput);

    connect(process, SIGNAL(finished(int, QProcess::ExitStatus)), source, SLOT(programProcessFinished(int, QProcess::ExitStatus)));
    connect(process, SIGNAL(readyReadStandardOutput()), source, SLOT(programProcessReadyRead()));

    QFileInfo cmdFileInfo(getCommandLocation());
    QString cmd(cmdFileInfo.absoluteDir().absolutePath().append("/").append(getBoards().value(board)));

    QStringList args;
    args.append(QString("-c%1").arg(port));
    args.append(fileLocation);

    ProgramTab *tab = qobject_cast<ProgramTab *>(source);
    if (tab)
        tab->appendToConsole(tr("Running %1 %2").arg(cmd).arg(args.join(" ")));
    process->start(cmd, args);
}
Example #16
0
void PlatformArduino::upload(QWidget *source, const QString &port, const QString &board, const QString &fileLocation)
{
    QProcess * process = new QProcess(this);
    process->setProcessChannelMode(QProcess::MergedChannels);
    process->setReadChannel(QProcess::StandardOutput);
    connect(process, SIGNAL(finished(int, QProcess::ExitStatus)), source, SLOT(programProcessFinished(int, QProcess::ExitStatus)));
    connect(process, SIGNAL(readyReadStandardOutput()), source, SLOT(programProcessReadyRead()));

    // Make sure .ino is in its own folder with same name (as required by Arduino compiler),
    // otherwise create a subfolder and copy the file there.
    QFileInfo fileInfo(fileLocation);
    QString tmpFilePath = fileInfo.absoluteFilePath();
    QString dirName = fileInfo.dir().dirName();
    QString sketchName = fileInfo.baseName();
    if (dirName.compare(sketchName, Qt::CaseInsensitive) != 0) {
        QString tmpSketchName(sketchName.append("_TMP"));
        fileInfo.dir().mkdir(tmpSketchName);
        tmpFilePath = fileInfo.absolutePath().append("/").append(tmpSketchName).append("/")
                      .append(fileInfo.baseName().append("_TMP.").append(fileInfo.suffix()));
        if (QFile::exists(tmpFilePath)) QFile::remove(tmpFilePath);
        QFile::copy(fileInfo.absoluteFilePath(), tmpFilePath);
    }

    QStringList args;
    // see https://github.com/arduino/Arduino/blob/ide-1.5.x/build/shared/manpage.adoc
    //args.append(QString("--verbose"));
    args.append(QString("--board"));
    args.append(getBoards().value(board));
    args.append(QString("--port"));
    args.append(port);
    args.append(QString("--upload"));
    args.append(QDir::toNativeSeparators(tmpFilePath));

    ProgramTab *tab = qobject_cast<ProgramTab *>(source);
    if (tab)
        tab->appendToConsole(tr("Running %1 %2").arg(getCommandLocation()).arg(args.join(" ")));
    process->start(getCommandLocation(), args);
}
static QString qtCoreFromOtool(const QString &path)
{
  QProcess proc;
  proc.setProcessChannelMode(QProcess::SeparateChannels);
  proc.setReadChannel(QProcess::StandardOutput);
  proc.start("otool", QStringList() << "-L" << path);
  proc.waitForFinished();

  forever {
    const QByteArray line = proc.readLine();
    if (line.isEmpty())
      break;

    if (ProbeABIDetector::containsQtCore(line)) {
      const int pos = line.lastIndexOf(" (");
      if (pos <= 0)
        continue;
      return QString::fromLocal8Bit(line.left(pos).trimmed());
    }
  }

  return QString();
}
bool CalculateVelocityHandler::GetEvLockInfo(EventInfo evinfo, EvLocInfo &evlocinfo)
{
    QString dir;
    GetMainDir(dir);

    QStringList arguments;
    arguments <<"./TimegridInfo" <<"./locPar" <<"./obs";
    QProcess proc;

    proc.start("./nllocTest", arguments);

    while (proc.state() != QProcess::NotRunning)
    {
        QCoreApplication::processEvents();
        usleep(100);
    }

    proc.setReadChannel(QProcess::StandardError);
    QByteArray array = proc.readAllStandardError();

    DeelLocInfo(array, evlocinfo);

    float x2 = pow((evinfo.position.east - evlocinfo.info.position.east), 2);
    float y2 = pow((evinfo.position.north - evlocinfo.info.position.north), 2);
    float z2 = pow((evinfo.position.deep - evlocinfo.info.position.deep), 2);

    if (ConfigManager::GetInstance()->AppSetting().z_join_calculate())
    {
        evlocinfo.residual = sqrt(x2 + y2 + z2);
    }
    else
    {
        evlocinfo.residual = sqrt(x2 + y2);
    }

    return true;
}
Example #19
0
static QString qtCoreFromLdd(const QString &path)
{
    QProcess proc;
    proc.setProcessChannelMode(QProcess::SeparateChannels);
    proc.setReadChannel(QProcess::StandardOutput);
    proc.start(QStringLiteral("ldd"), QStringList() << path);
    proc.waitForFinished();

    forever {
        const QByteArray line = proc.readLine();
        if (line.isEmpty())
            break;

        if (ProbeABIDetector::containsQtCore(line)) {
            const int begin = line.indexOf("=> ");
            const int end = line.lastIndexOf(" (");
            if (begin <= 0 || end <= 0 || end <= begin)
                continue;
            return QString::fromLocal8Bit(line.mid(begin + 3, end - begin - 3).trimmed());
        }
    }

    return QString();
}
Example #20
0
QString CoreInterface::run(const QStringList& args, const QString& input)
{
	QString program(
		QCoreApplication::applicationDirPath()
		+ "/" + kCoreBinary);

	QProcess process;
	process.setReadChannel(QProcess::StandardOutput);
	process.start(program, args);
	bool success = process.waitForStarted();

	QString output, error;
	if (success)
	{
		if (!input.isEmpty()) {
			process.write(input.toStdString().c_str());
		}

		if (process.waitForFinished()) {
			output = process.readAllStandardOutput().trimmed();
			error = process.readAllStandardError().trimmed();
		}
	}

	int code = process.exitCode();
	if (!error.isEmpty() || !success || code != 0)
	{
		throw std::runtime_error(
			QString("Code: %1\nError: %2")
				.arg(process.exitCode())
				.arg(error.isEmpty() ? "Unknown" : error)
				.toStdString());
	}

	return output;
}
Example #21
0
//------------------------------------------------------------------------------
//
std::auto_ptr<XxDiffs> XxBuilderDirs2::process( 
   const QString& command,
   XxBuffer&      buffer1,
   XxBuffer&      buffer2
)
{
   initLines();

   QString path1 = buffer1.getName();
   QString path2 = buffer2.getName();

   QStringList filenames;
   filenames.append( path1 );
   filenames.append( path2 );
   QStringList out_args;
   QString executable;
   XxUtil::splitArgs( command, filenames, executable, out_args );

   QProcess diffProc;
   diffProc.start( executable, out_args );
   if ( ! diffProc.waitForStarted() ) {
      throw XxIoError( XX_EXC_PARAMS );
   }
   diffProc.waitForReadyRead();
   diffProc.setReadChannel( QProcess::StandardOutput );

   std::vector<DirDiffType> types1;
   std::vector<DirDiffType> types2;

   QTextStream errors( &_errors );

   // Note: for now we don't support recursive diffs built against a directory.
   if ( _buildSolelyFromOutput || _isDiffRecursive ) {
      buildSolelyFromOutput(
         diffProc, errors, buffer1, buffer2, types1, types2
      );
   }
   else {
      buildAgainstReadDirectory( 
         diffProc, errors, buffer1, buffer2, types1, types2
      );
   }

#ifdef LOCAL_TRACE
   XX_TRACE( "------------------------------" );
   for ( unsigned int ii = 0; ii < types1.size(); ++ii ) {
      XX_TRACE( typeString[ types1[ii] ] );
   }
   XX_TRACE( "------------------------------" );
   XX_TRACE( "------------------------------" );
   for ( unsigned int ii = 0; ii < types2.size(); ++ii ) {
      XX_TRACE( typeString[ types2[ii] ] );
   }
   XX_TRACE( "------------------------------" );
#endif
      
   XxFln fline1 = 1;
   XxFln fline2 = 1;
   {
      // Create regions with it. Hopefully our searches resulted in something
      // coherent w.r.t. to the quantities and pair matching of entries. Barf if
      // it doesn't.
      std::vector<DirDiffType>::const_iterator it1 = types1.begin();
      std::vector<DirDiffType>::const_iterator it2 = types2.begin();
   
      while ( it1 != types1.end() || it2 != types2.end() ) {
         if ( it1 == types1.end() ) {
            if ( *it2 != ONLY_IN ) {
               throw XxInternalError( XX_EXC_PARAMS );
            }
            XxLine line( XxLine::INSERT_2, -1, fline2++ );
            addLine( line );
            ++it2;
            continue;
         }
         if ( it2 == types2.end() ) {
            if ( *it1 != ONLY_IN ) {
               throw XxInternalError( XX_EXC_PARAMS );
            }
            XxLine line( XxLine::INSERT_1, fline1++, -1 );
            addLine( line );
            ++it1;
            continue;
         }

         if ( *it1 == ONLY_IN ) {
            XxLine line( XxLine::INSERT_1, fline1++, -1 );
            addLine( line );
            ++it1;
         }
         else if ( *it2 == ONLY_IN ) {
            XxLine line( XxLine::INSERT_2, -1, fline2++ );
            addLine( line );
            ++it2;
         }
         else if ( *it1 == DIFFER ) {
            if ( *it2 != *it1 ) {
               throw XxInternalError( XX_EXC_PARAMS );
            }
            XxLine::Type dtype = 
               _ignoreFileChanges == true ? XxLine::SAME : XxLine::DIFF_ALL;
            XxLine line( dtype, fline1++, fline2++ );
            addLine( line );
            ++it1;
            ++it2;
         }
         else if ( *it1 == IDENTICAL ) {
            if ( *it2 != *it1 ) {
               throw XxInternalError( XX_EXC_PARAMS );
            }
            XxLine line( XxLine::SAME, fline1++, fline2++ );
            addLine( line );
            ++it1;
            ++it2;
         }
         else if ( *it1 == COMMON_SUBDIR ) {
            if ( *it2 != *it1 ) {
               throw XxInternalError( XX_EXC_PARAMS );
            }
            XxLine line( XxLine::DIRECTORIES, fline1++, fline2++ );
            addLine( line );
            ++it1;
            ++it2;
         }
         else {
            XX_ASSERT( false );
         }
      }
   }

   // Create hunks.
   if ( _lines.size() > 0 ) {
      XxHunk curHunk = 0;
      XxLine::Type prevType = _lines[0].getType();
      _lines[0].setHunkId( curHunk );
      for ( XxDln ii = 1; ii < XxDln(_lines.size()); ++ii ) {
         XxLine& cline = _lines[ii];
         if ( prevType != cline.getType() ) {
            ++curHunk;
            prevType = cline.getType();
         }
         cline.setHunkId( curHunk );
      }
   }

   diffProc.waitForFinished();

   // Collect stderr.
   QString errstr = diffProc.readAllStandardError();
   if ( ! errstr.isEmpty() ) {
      errors << errstr << endl;
   }
   _status = ( diffProc.exitStatus() == QProcess::NormalExit ) ? diffProc.exitCode() : 2;

   // Saved error text.
   errors << flush;
   XX_LOCAL_TRACE( "Errors: " << _errors );

   // If we've read no lines and there are diff errors then blow off
   if ( ( fline1 == 1 ) && ( fline2 == 1 ) && hasErrors() ) {
      throw XxIoError( XX_EXC_PARAMS );
   }

   std::auto_ptr<XxDiffs> ap( new XxDiffs( _lines, true ) );
   return ap;
}
void OscapScannerBase::readStdOut(QProcess& process)
{
    process.setReadChannel(QProcess::StandardOutput);

    while (tryToReadStdOutChar(process));
}
Example #23
0
/**
 * Starting point for the retracing thread.
 *
 * Overrides QThread::run().
 */
void Retracer::run()
{
    QString msg = QLatin1String("Replay finished!");

    /*
     * Construct command line
     */

    QString prog;
    QStringList arguments;

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

    arguments << retraceArguments() << m_fileName;

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

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

    /*
     * Start the process.
     */

    {
        QDebug debug(QtDebugMsg);
        debug << "Running:";
        debug << prog;
        foreach (const QString &argument, arguments) {
            debug << argument;
        }
    }

    QProcess process;

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

    /*
     * Process standard output
     */

    ImageHash thumbnails;
    QVariantMap parsedJson;
    trace::Profile* profile = NULL;

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

        if (m_captureState) {
            parsedJson = decodeUBJSONObject(&io).toMap();
            process.waitForFinished(-1);
        } else if (m_captureThumbnails) {
            /*
             * Parse concatenated PNM images from output.
             */

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

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

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

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

                    headerSize += headerRead;
                }

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

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

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

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

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

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

                QImage thumb = thumbnail(snapshot);
                thumbnails.insert(info.commentNumber, thumb);
            }

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

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

                lineLength = io.readLine(line, 256);

                if (lineLength == -1)
                    break;

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

    /*
     * Wait for process termination
     */

    process.waitForFinished(-1);

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

    /*
     * Parse errors.
     */

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

    /*
     * Emit signals
     */

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

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

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

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

    emit finished(msg);
}
Example #24
0
int main( int argc, char **argv )
{
	// UTF-8 Encoding
	QTextCodec::setCodecForCStrings(QTextCodec::codecForName("UTF-8"));
	QTextCodec::setCodecForTr(QTextCodec::codecForName("UTF-8"));
	QTextCodec::setCodecForLocale(QTextCodec::codecForName("UTF-8"));
	
	QApplication app( argc, argv );
	
	QWidget w;
	QHBoxLayout *layoutH = new QHBoxLayout(&w); // Layout
		
		QSplitter *general = new QSplitter(Qt::Horizontal,&w);

		QTextEdit *affichage = new QTextEdit(&w);
		QWidget *wdroite = new QWidget(&w);
			QVBoxLayout *droite = new QVBoxLayout(wdroite);
			QSplitter *etatActuel = new QSplitter(Qt::Vertical,wdroite);
				QWidget *wregle = new QWidget(wdroite);
					QVBoxLayout *Bregle = new QVBoxLayout(wregle);
						QLabel *labelRegle = new QLabel("Base de règle:");
						QTextEdit *regle = new QTextEdit(wregle);
				
				QWidget *wfait = new QWidget(wdroite);
					QVBoxLayout *Bfait = new QVBoxLayout(wfait);
						QLabel *labelFait = new QLabel("Base de fait:");
						QTextEdit *fait = new QTextEdit(wdroite);
						QWidget *woptions = new QWidget(wdroite);
						
							QHBoxLayout *Boptions = new QHBoxLayout(woptions); 	
								QWidget *wboutons = new QWidget(woptions);
									QVBoxLayout *Bboutons = new QVBoxLayout(wboutons);
										QPushButton *lanceAvant = new QPushButton("Lancer le chainage avant", wdroite);
										QPushButton *lanceArriere = new QPushButton("Lancer le chainage arrière", wdroite);
								QWidget *wintervalle = new QWidget(woptions);
									QVBoxLayout *Bintervalle = new QVBoxLayout(wintervalle);
										QLabel *labelIntervalle = new QLabel("Intervalle des étapes (en secondes):", wintervalle);
										QSpinBox *intervalle = new QSpinBox(wintervalle);
					
		intervalle->setValue(2);
		intervalle->setMinimum(0);

		affichage->setText("");
		affichage->setReadOnly(true);

		regle->setText("");
		regle->setReadOnly(true);

		fait->setText("");
		fait->setReadOnly(true);


	QProcess *main = new QProcess();
		main->setReadChannel(QProcess::StandardOutput);

	afficheur *ui = new afficheur(affichage,regle,fait,intervalle,main);
	
	QObject::connect(main,SIGNAL(readyReadStandardOutput()),ui,SLOT(affiche()));
	QObject::connect(lanceAvant,SIGNAL(clicked()),ui,SLOT(runAvant()));	
	QObject::connect(lanceArriere,SIGNAL(clicked()),ui,SLOT(runArriere()));	

	Bintervalle->addWidget(labelIntervalle);
	Bintervalle->addWidget(intervalle);

	Bboutons->addWidget(lanceAvant);
	Bboutons->addWidget(lanceArriere);

	Boptions->addWidget(wboutons);
	Boptions->addWidget(wintervalle);

	Bregle->addWidget(labelRegle);
	Bregle->addWidget(regle);
	Bregle->addWidget(woptions);
	etatActuel->addWidget(wregle);

	Bfait->addWidget(labelFait);
	Bfait->addWidget(fait);
	etatActuel->addWidget(wfait);

	droite->addWidget(etatActuel);

	general->addWidget(affichage);
	general->addWidget(wdroite);
	general->setStretchFactor(0,2);

	layoutH->addWidget(general);

	w.setMinimumSize(700,500);
	w.setWindowState(w.windowState() ^ Qt::WindowMaximized);
	w.show();

	return app.exec();
}
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 #26
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 #27
0
/**
 * Starting point for the retracing thread.
 *
 * Overrides QThread::run().
 */
void Retracer::run()
{
    QString msg = QLatin1String("Replay finished!");

    /*
     * Construct command line
     */

    QString prog;
    QStringList arguments;

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

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

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

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

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

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

    arguments << m_fileName;

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

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

    /*
     * Start the process.
     */

    QProcess process;

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

    /*
     * Process standard output
     */

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

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

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

            bool ok = false;
            QJson::Parser jsonParser;

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

            while (!io.atEnd()) {
                unsigned channels = 0;
                unsigned width = 0;
                unsigned height = 0;

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

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

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

                    headerSize += headerRead;
                }

                const char *headerEnd = image::readPNMHeader(header, headerSize, &channels, &width, &height);

                // if invalid PNM header was encountered, ...
                if (header == headerEnd) {
                    qDebug() << "error: invalid snapshot stream encountered";
                    break;
                }

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

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

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

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

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

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

                lineLength = io.readLine(line, 256);

                if (lineLength == -1)
                    break;

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

    /*
     * Wait for process termination
     */

    process.waitForFinished(-1);

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

    /*
     * Parse errors.
     */

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

    /*
     * Emit signals
     */

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

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

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

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

    emit finished(msg);
}
Example #28
0
void QProcessProto::setReadChannel(QProcess::ProcessChannel channel)
{
  QProcess *item = qscriptvalue_cast<QProcess*>(thisObject());
  if (item)
    item->setReadChannel(channel);
}
Example #29
0
// Function to get the default Python version if any by running the python process.
static QString getDefaultPythonVersionIfAny() {
  QString defaultPythonVersion;
  QProcess pythonProcess;

  QString pythonCommand = "python";

// This is a hack for MinGW to allow the debugging of Tulip through GDB when compiled with Python 3.X installed in a non standard way.
#ifdef __MINGW32__
  char *pythonDirEv = getenv("PYTHONDIR");

  if (pythonDirEv) {
    pythonCommand = QString(pythonDirEv) + "/" + pythonCommand;
  }

#endif

  // Before Python 3.4, the version number was printed on the standard error output.
  // Starting Python 3.4 the version number is printed on the standard output.
  // So merge the output channels of the process.
  pythonProcess.setReadChannelMode(QProcess::MergedChannels);
  pythonProcess.setReadChannel(QProcess::StandardOutput);
  pythonProcess.start(pythonCommand, QStringList() << "--version");
  pythonProcess.waitForFinished(-1);

  if (pythonProcess.exitStatus() == QProcess::NormalExit) {

    QString result = pythonProcess.readAll();

    QRegExp versionRegexp(".*([0-9]*\\.[0-9]*)\\..*");

    if (versionRegexp.exactMatch(result)) {
      defaultPythonVersion = versionRegexp.cap(1);

// This is a hack for MinGW to allow the debugging of Tulip through GDB when compiled with Python 3.X installed in a non standard way.
#ifdef __MINGW32__

      if (pythonDirEv) {
        QProcessEnvironment env = QProcessEnvironment::systemEnvironment();
        env.insert("PYTHONHOME", QString(pythonDirEv));
        pythonProcess.setProcessEnvironment(env);
      }

#endif

      // Check the binary type of the python executable (32 or 64 bits)
      pythonProcess.start(pythonCommand, QStringList() << "-c" << "import struct;import sys;sys.stdout.write(str(struct.calcsize('P')*8))");
      pythonProcess.waitForFinished(-1);
      QString arch = pythonProcess.readAll();

#ifdef I64

      if (arch != "64") {
        defaultPythonVersion = "";
      }

#else

      if (arch != "32") {
        defaultPythonVersion = "";
      }

#endif

    }
  }

  return defaultPythonVersion;
}
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();
}