void closeAllVolumesThread::run()
{
	m_table->setEnabled( false );
	sleep( 1 ) ; // for ui effect
	int i = m_table->rowCount() ;

	if( i < 1 ){
		m_table->setEnabled( true );
		return ;
	}

	int j = -1 ;

	QVector<QTableWidgetItem*> tableItems( 0 ) ;

	QTableWidgetItem * deviceItem ;

	while( ++j < i ){
		tableItems.append( m_table->item( j,0 ) );
	}
	
	QProcess p ;
	QString exe ;
	QString device ;

	for( j = 0 ; j < i ; j++ ){
		deviceItem = tableItems.at( j ) ;
		device = deviceItem->text().replace( "\"","\"\"\"" ) ;
		exe = QString( "%1 -q -d \"%2\"" ).arg( ZULUCRYPTzuluCrypt ).arg( device ) ;
		p.start( exe );
		p.waitForFinished() ;
		emit close( deviceItem,p.exitCode() ) ;
		p.close();
		sleep( 1 ) ; // for ui effect
	}
	
	m_table->setEnabled( true );
}
Example #2
0
OutputList Class::transform(const QStringList &input, Options &options) const
{
	Output ret;
	ret.setFiles(input);
	
	QProcess compiler;
	QString output = (options.contains(OUTPUT_DIR) ? options[OUTPUT_DIR].toString() : QFileInfo(input[0]).absolutePath() + "/a.jar");
	
	compiler.start(jarPath(), (QStringList() << "cvf" << output) + input);
	if(!compiler.waitForStarted()) {
		ret = Output(Platform::ccPath(), 1, "", "error: couldn't start the java archiver");
		return OutputList() << ret;
	}
	compiler.waitForFinished();
	
	ret.setExitCode(compiler.exitCode());
	ret.setOutput(compiler.readAllStandardOutput());
	ret.setError(compiler.readAllStandardError());
	ret.setGeneratedFiles(QStringList() << output);
  ret.setTerminal(Output::BinaryTerminal);
	
	return OutputList() << ret;
}
Example #3
0
int main(int argc, char** argv)
{
    QCoreApplication app(argc, argv);
    app.setApplicationName("Flush");
    QStringList args=app.arguments();
    args.removeFirst();
    QString appl=args.at(0);
    args.removeFirst();
    QProcess p;
    p.setProcessChannelMode(QProcess::ForwardedChannels);
    p.start(appl,args);
    p.waitForFinished(-1);
    Phonon::MediaObject *mediaObject = new Phonon::MediaObject();
    Phonon::AudioOutput *audioOutput = new Phonon::AudioOutput(Phonon::MusicCategory);
    Phonon::createPath(mediaObject, audioOutput);
    if(p.exitCode()==0)
      mediaObject->setCurrentSource(Phonon::MediaSource(":/flush.ogg"));
    else
      mediaObject->setCurrentSource(Phonon::MediaSource(":/sadtrombone.ogg"));
    mediaObject->play();
    QObject::connect(mediaObject,SIGNAL(finished()),&app,SLOT(quit()));
    return app.exec();
}
/*!
   \param program The program to execute.
   \param arguments The arguments to be passed to the program.
   \return The exit code of the executed program.
    Starts a program with arguments in a new process, waits for it to finish, and then returns
    the exit code of the process. Any data the new process writes to the console is forwarded to
    the calling process.

    The environment and working directory are inherited by the calling process.

    On Windows, arguments that contain spaces are wrapped in quotes.
*/
int TSystem::execute(const QString &program, const QStringList &arguments) const
{
    QDEBUG_METHOD_NAME;

    QProcess process;

    // As seen in http://jira.codehaus.org/browse/IZPACK-20 and http://labs.trolltech.com/forums/topic/156, the method
    // execute() from QProcess is not used.

    qDebug() << TDebug::indentation << "Going to execute: " << program << " with arguments: " << arguments;

    process.setReadChannelMode(QProcess::ForwardedChannels);
    process.start(program, arguments);
    process.waitForFinished(-1);

    int exitCode = process.exitCode();
    if (process.error() == QProcess::FailedToStart)
    {
       exitCode = -1;
    }

    return exitCode;
}
Example #5
0
Utils::Port IosSimulator::nextPort() const
{
    for (int i = 0; i < 100; ++i) {
        // use qrand instead?
        if (++m_lastPort >= Constants::IOS_SIMULATOR_PORT_END)
            m_lastPort = Constants::IOS_SIMULATOR_PORT_START;
        QProcess portVerifier;
        // this is a bit too broad (it does not check just listening sockets, but also connections
        // to that port from this computer)
        portVerifier.start(QLatin1String("lsof"), QStringList() << QLatin1String("-n")
                         << QLatin1String("-P") << QLatin1String("-i")
                         << QString::fromLatin1(":%1").arg(m_lastPort));
        if (!portVerifier.waitForStarted())
            break;
        portVerifier.closeWriteChannel();
        if (!portVerifier.waitForFinished() && portVerifier.state() == QProcess::Running)
            break;
        if (portVerifier.exitStatus() != QProcess::NormalExit
                || portVerifier.exitCode() != 0)
            break;
    }
    return Utils::Port(m_lastPort);
}
Example #6
0
bool MainForm::useTesseract(const QString &inputFile)
{
    QProcess proc;
    proc.setWorkingDirectory(workingDir);
    QStringList sl;
    sl.append(inputFile);
    sl.append(outputBase);
    sl.append("-l");
    sl.append(tesMap->value(settings.getLanguage()));
    QProcessEnvironment env = QProcessEnvironment::systemEnvironment();
    env.insert("TESSDATA_PREFIX", settings.getTessdataPath());
    proc.setProcessEnvironment(env);
    proc.start("tesseract", sl);
    proc.waitForFinished(-1);
    if (proc.exitCode()) {
        QByteArray stdout = proc.readAllStandardOutput();
        QByteArray stderr = proc.readAllStandardError();
        QString output = QString(stdout) + QString(stderr);
        QMessageBox::critical(this, trUtf8("Starting tesseract failed"), trUtf8("The system said: ") + (output != "" ? output : trUtf8("program not found")));
        return false;
    }
    return true;
}
Example #7
0
bool MTest::compareFiles(const QString& saveName, const QString& compareWith) const
      {
      QString cmd = "diff";
      QStringList args;
      args.append("-u");
      args.append("--strip-trailing-cr");
      args.append(saveName);
      args.append(root + "/" + compareWith);
      QProcess p;
qDebug() << "Running " << cmd << " with arg1:" << saveName << " and arg2: " << compareWith;
      p.start(cmd, args);
      if (!p.waitForFinished() || p.exitCode()) {
            QByteArray ba = p.readAll();
            //qDebug("%s", qPrintable(ba));
            //qDebug("   <diff -u %s %s failed", qPrintable(saveName),
            //   qPrintable(QString(root + "/" + compareWith)));
            QTextStream outputText(stdout);
            outputText << QString(ba);
            outputText << QString("   <diff -u %1 %2 failed").arg(QString(saveName)).arg(QString(root + "/" + compareWith));
            return false;
            }
      return true;
      }
Example #8
0
void ChibiTest::selectSticker(int stickerNum)
{
    QProcess s;

    emit testMessage(testName(), setStickerNum, stickerNum, "");

    if (stickerNum > 4)
        return;

    s.start("./select_sticker", QStringList() << QString::number(stickerNum));

    if (!s.waitForStarted()) {
        testError("Unable to select sticker");
        return;
    }

    s.closeWriteChannel();
    s.waitForFinished();
    if (s.exitCode()) {
        testError(QString("select_sticker returned an error: ") + s.readAll());
        return;
    }
}
Example #9
0
unsigned int AndroidDeployStep::remoteModificationTime(const QString &fullDestination, QHash<QString, unsigned int> *cache)
{
    QString destination = QFileInfo(fullDestination).absolutePath();
    QProcess process;
    QHash<QString, unsigned int>::const_iterator it = cache->find(fullDestination);
    if (it != cache->constEnd())
        return *it;
    QStringList arguments = AndroidDeviceInfo::adbSelector(m_deviceSerialNumber);
    arguments << QLatin1String("ls") << destination;
    process.start(AndroidConfigurations::instance().adbToolPath().toString(), arguments);
    process.waitForFinished(-1);
    if (process.error() != QProcess::UnknownError
            || process.exitCode() != 0)
        return -1;
    QByteArray output = process.readAll();
    output.replace("\r\n", "\n");
    QList<QByteArray> lines = output.split('\n');
    foreach (const QByteArray &line, lines) {
        // do some checks if we got what we expected..
        if (line.count() < (3 * 8 + 3))
            continue;
        if (line.at(8) != ' '
                || line.at(17) != ' '
                || line.at(26) != ' ')
            continue;
        bool ok;
        int time = line.mid(18, 8).toUInt(&ok, 16);
        if (!ok)
            continue;
        QString fileName = QString::fromLocal8Bit(line.mid(27));
        cache->insert(destination + QLatin1Char('/') + fileName, time);
    }
    it = cache->find(fullDestination);
    if (it != cache->constEnd())
        return *it;
    return 0;
}
Example #10
0
bool openInNativeExtension(const QString &path) {
#if defined(Q_OS_WIN32)
    //call ShellExecute internally
    return QDesktopServices::openUrl(QUrl::fromLocalFile(path));
#elif defined(Q_OS_MAC)
    // mac's open program, it will fork to open the file in a subprocess
    // so we will wait for it to check whether it succeeds or not
    QProcess subprocess;
    subprocess.start(QLatin1String("open"), QStringList(path));
    subprocess.waitForFinished(-1);
    return subprocess.exitCode() == 0;
#elif defined(Q_OS_LINUX)
    // unlike mac's open program, xdg-open won't fork a new subprocess to open
    // the file will block until the application returns, so we won't wait for it
    // and we need another approach to check if it works

    // find out if the file can be opened by xdg-open, xdg-mime
    // usually they are installed in xdg-utils installed by default
    QString mime_type;
    if (!getMimeTypeFromXdgUtils(path, &mime_type))
        return false;
    // don't open this type of files from xdg-mime
    if (mime_type == "application/octet-stream")
        return false;
    // in fact we need to filter out files like application/x-executable
    // but it is not necessary since getMimeTypeFromXdg will return false for
    // it!
    QString application;
    if (!getOpenApplicationFromXdgUtils(mime_type, &application))
        return false;

    return QProcess::startDetached(QLatin1String("xdg-open"),
                                   QStringList(path));
#else
    return false;
#endif
}
Example #11
0
// Reruns this program through callgrind, storing callgrind result files in the
// current directory.
// Returns true upon success, otherwise false.
bool QBenchmarkValgrindUtils::runCallgrindSubProcess(const QStringList &origAppArgs, int &exitCode)
{
    const QString execFile(origAppArgs.at(0));
    QStringList args;
    args << QLatin1String("--tool=callgrind") << QLatin1String("--instr-atstart=yes")
         << QLatin1String("--quiet")
         << execFile << QLatin1String("-callgrindchild");

#if (defined Q_WS_QWS)
    // While running the child process, we aren't processing events, and hence aren't
    // acting as the QWS server. Therefore it's necessary to tell the child to act
    // as its own server instead of connecting to us.
    args << QLatin1String("-qws");
#endif

    // pass on original arguments that make sense (e.g. avoid wasting time producing output
    // that will be ignored anyway) ...
    for (int i = 1; i < origAppArgs.size(); ++i) {
        const QString arg(origAppArgs.at(i));
        if (arg == QLatin1String("-callgrind"))
            continue;
        args << arg; // ok to pass on
    }

    QProcess process;
    process.start(QLatin1String("valgrind"), args);
    process.waitForStarted(-1);
    QBenchmarkGlobalData::current->callgrindOutFileBase =
        QBenchmarkValgrindUtils::outFileBase(process.pid());
    const bool finishedOk = process.waitForFinished(-1);
    exitCode = process.exitCode();

    dumpOutput(process.readAllStandardOutput(), stdout);
    dumpOutput(process.readAllStandardError(), stderr);

    return finishedOk;
}
Example #12
0
int System(const QString exename, const QStringList & args, const QString fileStdErr, const QString fileStdOut, bool* cancel)
{
	QProcess proc;
	if (!fileStdOut.isEmpty())
		proc.setStandardOutputFile(fileStdOut);
	if (!fileStdErr.isEmpty())
		proc.setStandardErrorFile(fileStdErr);
	proc.start(exename, args);
	if (proc.waitForStarted(15000))
	{
		while (!proc.waitForFinished(15000))
		{
			qApp->processEvents();
			if (cancel && (*cancel == true))
			{
				proc.kill();
				break;
			}
		}
	}
	if (cancel && (*cancel == true))
		return -1;
	return proc.exitCode();
}
Example #13
0
/**
 * Returns the complete python version
 * eg 2.7.9
 * Make sure to have setup python first
 */
QString Utils::Misc::pythonVersionComplete() {
    static QString version;
    if (version.isEmpty()) {
        if (pythonExecutable().isEmpty())
            return version;
        QProcess pythonProc;
        pythonProc.start(pythonExecutable(), QStringList() << "--version", QIODevice::ReadOnly);
        if (pythonProc.waitForFinished() && pythonProc.exitCode() == 0) {
            QByteArray output = pythonProc.readAllStandardOutput();
            if (output.isEmpty())
                output = pythonProc.readAllStandardError();

            // Software 'Anaconda' installs its own python interpreter
            // and `python --version` returns a string like this:
            // `Python 3.4.3 :: Anaconda 2.3.0 (64-bit)`
            const QList<QByteArray> verSplit = output.split(' ');
            if (verSplit.size() > 1) {
                version = verSplit.at(1).trimmed();
                Logger::instance()->addMessage(QCoreApplication::translate("misc", "Python version: %1").arg(version), Log::INFO);
            }
        }
    }
    return version;
}
Example #14
0
/*! Close the current backup (encrypted or unencrypted)
 *
 * \return success, failed or what else
 */
Backup::Status Backup::close()
{
    QProcess process;
    QDir dir;

    if (!isOpen()) {
        return Backup::Success;
    }

    switch (m_encryption) {
        case Backup::NotEncrypted:
            break;

        case Backup::EncFSEncrypted:
            process.start("fusermount", QStringList() << "-u" << m_location);
            process.waitForStarted();
            process.waitForFinished();

            m_errorString = process.readAllStandardError();
            m_rc = process.exitCode();

            if (m_rc != 0) {
                return Backup::Failed;
            }

            dir.rmdir(m_location);
            break;

        default:
            return Backup::Failed;
            break;
    }

    m_isOpen = false;
    return Backup::Success;
}
Example #15
0
void HgCreateDialog::done(int r)
{
    if (r == KDialog::Accepted) {
        QProcess process;
        QStringList args;
        args << QLatin1String("init");
        if (!m_repoNameEdit->text().isEmpty()) {
            args << m_repoNameEdit->text();
        }
        process.setWorkingDirectory(m_workingDirectory);
        process.start(QLatin1String("hg"), args);
        process.waitForFinished();
        
        if (process.exitCode() == 0 && process.exitStatus() == QProcess::NormalExit) {
            KDialog::done(r);
        }
        else {
            KMessageBox::error(this, i18nc("error message", "Error creating repository!"));
        }
    }
    else {
        KDialog::done(r);
    }
}
void tst_QProcess_and_GuiEventLoop::waitForAndEventLoop()
{
#if defined(Q_OS_ANDROID) && !defined(Q_OS_ANDROID_NO_SDK)
    QSKIP("Not supported on Android");
#endif

    // based on testcase provided in QTBUG-39488
    QByteArray msg = "Hello World";

    QProcess process;
    process.start("write-read-write/write-read-write", QStringList() << msg);
    QVERIFY(process.waitForStarted(5000));
    QVERIFY(process.waitForReadyRead(5000));
    QCOMPARE(process.readAll().trimmed(), msg);

    // run the GUI event dispatcher once
    QSignalSpy spy(&process, SIGNAL(readyRead()));
    qApp->processEvents(QEventLoop::AllEvents, 100);

    // we mustn't have read anything in the event loop
    QCOMPARE(spy.count(), 0);

    // ensure the process hasn't died
    QVERIFY(!process.waitForFinished(250));

    // we mustn't have read anything during waitForFinished either
    QCOMPARE(spy.count(), 0);

    // release the child for the second write
    process.write("\n");
    QVERIFY(process.waitForFinished(5000));
    QCOMPARE(int(process.exitStatus()), int(QProcess::NormalExit));
    QCOMPARE(process.exitCode(), 0);
    QCOMPARE(spy.count(), 1);
    QCOMPARE(process.readAll().trimmed(), msg);
}
Example #17
0
bool startCreatorAsDebugger(bool asClient, QString *errorMessage)
{
    const QString dir = QApplication::applicationDirPath();
    const QString binary = dir + QLatin1Char('/') + QLatin1String(creatorBinaryC);
    QStringList args;
    // Send to running Creator: Unstable with directly linked CDB engine.
    if (asClient)
        args << QLatin1String("-client");
    args << QLatin1String("-wincrashevent")
        << QString::fromLatin1("%1:%2").arg(argWinCrashEvent).arg(argProcessId);
    if (debug)
        qDebug() << binary << args;
    QProcess p;
    p.setWorkingDirectory(dir);
    QTime executionTime;
    executionTime.start();
    p.start(binary, args, QIODevice::NotOpen);
    if (!p.waitForStarted()) {
        *errorMessage = QString::fromLatin1("Unable to start %1!").arg(binary);
        return false;
    }
    // Short execution time: indicates that -client was passed on attach to
    // another running instance of Qt Creator. Keep alive as long as user
    // does not close the process. If that fails, try to launch 2nd instance.
    const bool waitResult = p.waitForFinished(-1);
    const bool ranAsClient = asClient && (executionTime.elapsed() < 10000);
    if (waitResult && p.exitStatus() == QProcess::NormalExit && ranAsClient) {
        if (p.exitCode() == 0) {
            waitForProcess(argProcessId);
        } else {
            errorMessage->clear();
            return startCreatorAsDebugger(false, errorMessage);
        }
    }
    return true;
}
Example #18
0
//Return CLI output (and success/failure)
QString General::RunCommand(bool &success, QString command, QStringList arguments, QString workdir, QStringList env){
  QProcess proc;
    proc.setProcessChannelMode(QProcess::MergedChannels); //need output
  //First setup the process environment as necessary
  QProcessEnvironment PE = QProcessEnvironment::systemEnvironment();
    if(!env.isEmpty()){
      for(int i=0; i<env.length(); i++){
    if(!env[i].contains("=")){ continue; }
        PE.insert(env[i].section("=",0,0), env[i].section("=",1,100));
      }
    }
    proc.setProcessEnvironment(PE);
  //if a working directory is specified, check it and use it
  if(!workdir.isEmpty()){
    proc.setWorkingDirectory(workdir);
  }
  //Now run the command (with any optional arguments)
  if(arguments.isEmpty()){ proc.start(command); }
  else{ proc.start(command, arguments); }
  //Wait for the process to finish (but don't block the event loop)
  while( !proc.waitForFinished(500) ){ QCoreApplication::processEvents(); }
  success = (proc.exitCode()==0); //return success/failure
  return QString(proc.readAllStandardOutput());
}
Example #19
0
bool DeviceLock::runPlugin(const QStringList &args)
{
    QSettings settings("/usr/share/lipstick/devicelock/devicelock.conf", QSettings::IniFormat);
    QString pluginName = settings.value("DeviceLock/pluginName").toString();

    if (pluginName.isEmpty()) {
        qWarning("No plugin configuration set in /usr/share/lipstick/devicelock/devicelock.conf");
        return false;
    }

    QProcess process;
    process.start(pluginName, args);
    if (!process.waitForFinished()) {
        qWarning("Plugin did not finish in time");
        return false;
    }

#ifdef DEBUG_DEVICELOCK
    qDebug() << process.readAllStandardOutput();
    qWarning() << process.readAllStandardError();
#endif

    return process.exitCode() == 0;
}
Example #20
0
bool FLACEncoder::encode(const QString &sourceFile, const AudioFileModel &metaInfo, const QString &outputFile, volatile bool *abortFlag)
{
	QProcess process;
	QStringList args;

	args << QString("-%1").arg(QString::number(qBound(0, m_configBitrate, 8)));
	args << "--channel-map=none";

	if(!metaInfo.fileName().isEmpty()) args << "-T" << QString("title=%1").arg(cleanTag(metaInfo.fileName()));
	if(!metaInfo.fileArtist().isEmpty()) args << "-T" << QString("artist=%1").arg(cleanTag(metaInfo.fileArtist()));
	if(!metaInfo.fileAlbum().isEmpty()) args << "-T" << QString("album=%1").arg(cleanTag(metaInfo.fileAlbum()));
	if(!metaInfo.fileGenre().isEmpty()) args << "-T" << QString("genre=%1").arg(cleanTag(metaInfo.fileGenre()));
	if(!metaInfo.fileComment().isEmpty()) args << "-T" << QString("comment=%1").arg(cleanTag(metaInfo.fileComment()));
	if(metaInfo.fileYear()) args << "-T" << QString("date=%1").arg(QString::number(metaInfo.fileYear()));
	if(metaInfo.filePosition()) args << "-T" << QString("track=%1").arg(QString::number(metaInfo.filePosition()));
	if(!metaInfo.fileCover().isEmpty()) args << QString("--picture=%1").arg(metaInfo.fileCover());

	//args << "--tv" << QString().sprintf("Encoder=LameXP v%d.%02d.%04d [%s]", lamexp_version_major(), lamexp_version_minor(), lamexp_version_build(), lamexp_version_release());

	if(!m_configCustomParams.isEmpty()) args << m_configCustomParams.split(" ", QString::SkipEmptyParts);

	args << "-f" << "-o" << QDir::toNativeSeparators(outputFile);
	args << QDir::toNativeSeparators(sourceFile);

	if(!startProcess(process, m_binary, args))
	{
		return false;
	}

	bool bTimeout = false;
	bool bAborted = false;
	int prevProgress = -1;

	QRegExp regExp("\\b(\\d+)% complete");

	while(process.state() != QProcess::NotRunning)
	{
		if(*abortFlag)
		{
			process.kill();
			bAborted = true;
			emit messageLogged("\nABORTED BY USER !!!");
			break;
		}
		process.waitForReadyRead(m_processTimeoutInterval);
		if(!process.bytesAvailable() && process.state() == QProcess::Running)
		{
			process.kill();
			qWarning("FLAC process timed out <-- killing!");
			emit messageLogged("\nPROCESS TIMEOUT !!!");
			bTimeout = true;
			break;
		}
		while(process.bytesAvailable() > 0)
		{
			QByteArray line = process.readLine().replace('\b', char(0x20));
			QString text = QString::fromUtf8(line.constData()).simplified();
			if(regExp.lastIndexIn(text) >= 0)
			{
				bool ok = false;
				int progress = regExp.cap(1).toInt(&ok);
				if(ok && (progress > prevProgress))
				{
					emit statusUpdated(progress);
					prevProgress = qMin(progress + 2, 99);
				}
			}
			else if(!text.isEmpty())
			{
				emit messageLogged(text);
			}
		}
	}

	process.waitForFinished();
	if(process.state() != QProcess::NotRunning)
	{
		process.kill();
		process.waitForFinished(-1);
	}
	
	emit statusUpdated(100);
	emit messageLogged(QString().sprintf("\nExited with code: 0x%04X", process.exitCode()));

	if(bTimeout || bAborted || process.exitCode() != EXIT_SUCCESS)
	{
		return false;
	}
	
	return true;
}
Example #21
0
bool FLACDecoder::decode(const QString &sourceFile, const QString &outputFile, volatile bool *abortFlag)
{
    QProcess process;
    QStringList args;

    args << "-d" << "-F" << "-f";
    args << "-o" << QDir::toNativeSeparators(outputFile);
    args << QDir::toNativeSeparators(sourceFile);

    if(!startProcess(process, m_binary, args))
    {
        return false;
    }

    bool bTimeout = false;
    bool bAborted = false;

    QRegExp regExp("\\b(\\d+)% complete");

    while(process.state() != QProcess::NotRunning)
    {
        if(*abortFlag)
        {
            process.kill();
            bAborted = true;
            emit messageLogged("\nABORTED BY USER !!!");
            break;
        }
        process.waitForReadyRead(m_processTimeoutInterval);
        if(!process.bytesAvailable() && process.state() == QProcess::Running)
        {
            process.kill();
            qWarning("FLAC process timed out <-- killing!");
            emit messageLogged("\nPROCESS TIMEOUT !!!");
            bTimeout = true;
            break;
        }
        while(process.bytesAvailable() > 0)
        {
            QByteArray line = process.readLine().replace('\b', char(0x20));
            QString text = QString::fromUtf8(line.constData()).simplified();
            if(regExp.lastIndexIn(text) >= 0)
            {
                bool ok = false;
                int progress = regExp.cap(1).toInt(&ok);
                if(ok) emit statusUpdated(progress);
            }
            else if(!text.isEmpty())
            {
                emit messageLogged(text);
            }
        }
    }

    process.waitForFinished();
    if(process.state() != QProcess::NotRunning)
    {
        process.kill();
        process.waitForFinished(-1);
    }

    emit statusUpdated(100);
    emit messageLogged(QString().sprintf("\nExited with code: 0x%04X", process.exitCode()));

    if(bTimeout || bAborted || process.exitCode() != EXIT_SUCCESS || QFileInfo(outputFile).size() == 0)
    {
        return false;
    }

    return true;
}
Example #22
0
bool OpusEncoder::encode(const QString &sourceFile, const AudioFileModel_MetaInfo &metaInfo, const unsigned int duration, const QString &outputFile, volatile bool *abortFlag)
{
	QProcess process;
	QStringList args;

	switch(m_configRCMode)
	{
	case SettingsModel::VBRMode:
		args << "--vbr";
		break;
	case SettingsModel::ABRMode:
		args << "--cvbr";
		break;
	case SettingsModel::CBRMode:
		args << "--hard-cbr";
		break;
	default:
		MUTILS_THROW("Bad rate-control mode!");
		break;
	}

	args << "--comp" << QString::number(m_configEncodeComplexity);

	switch(m_configFrameSize)
	{
	case 0:
		args << "--framesize" << "2.5";
		break;
	case 1:
		args << "--framesize" << "5";
		break;
	case 2:
		args << "--framesize" << "10";
		break;
	case 3:
		args << "--framesize" << "20";
		break;
	case 4:
		args << "--framesize" << "40";
		break;
	case 5:
		args << "--framesize" << "60";
		break;
	}

	args << QString("--bitrate") << QString::number(qBound(8, (m_configBitrate + 1) * 8, 256));

	if(!metaInfo.title().isEmpty()) args << "--title" << cleanTag(metaInfo.title());
	if(!metaInfo.artist().isEmpty()) args << "--artist" << cleanTag(metaInfo.artist());
	if(!metaInfo.album().isEmpty()) args << "--album" << cleanTag(metaInfo.album());
	if(!metaInfo.genre().isEmpty()) args << "--genre" << cleanTag(metaInfo.genre());
	if(metaInfo.year()) args << "--date" << QString::number(metaInfo.year());
	if(metaInfo.position()) args << "--comment" << QString("tracknumber=%1").arg(QString::number(metaInfo.position()));
	if(!metaInfo.comment().isEmpty()) args << "--comment" << QString("comment=%1").arg(cleanTag(metaInfo.comment()));
	
	if(!m_configCustomParams.isEmpty()) args << m_configCustomParams.split(" ", QString::SkipEmptyParts);

	args << QDir::toNativeSeparators(sourceFile);
	args << QDir::toNativeSeparators(outputFile);

	if(!startProcess(process, m_binary, args))
	{
		return false;
	}

	bool bTimeout = false;
	bool bAborted = false;
	int prevProgress = -1;

	QRegExp regExp("\\((\\d+)%\\)");

	while(process.state() != QProcess::NotRunning)
	{
		if(*abortFlag)
		{
			process.kill();
			bAborted = true;
			emit messageLogged("\nABORTED BY USER !!!");
			break;
		}
		process.waitForReadyRead(m_processTimeoutInterval);
		if(!process.bytesAvailable() && process.state() == QProcess::Running)
		{
			process.kill();
			qWarning("Opus process timed out <-- killing!");
			emit messageLogged("\nPROCESS TIMEOUT !!!");
			bTimeout = true;
			break;
		}
		while(process.bytesAvailable() > 0)
		{
			QByteArray line = process.readLine();
			QString text = QString::fromUtf8(line.constData()).simplified();
			if(regExp.lastIndexIn(text) >= 0)
			{
				bool ok = false;
				int progress = regExp.cap(1).toInt(&ok);
				if(ok && (progress > prevProgress))
				{
					emit statusUpdated(progress);
					prevProgress = qMin(progress + 2, 99);
				}
			}
			else if(!text.isEmpty())
			{
				emit messageLogged(text);
			}
		}
	}

	process.waitForFinished();
	if(process.state() != QProcess::NotRunning)
	{
		process.kill();
		process.waitForFinished(-1);
	}
	
	emit statusUpdated(100);
	emit messageLogged(QString().sprintf("\nExited with code: 0x%04X", process.exitCode()));

	if(bTimeout || bAborted || process.exitCode() != EXIT_SUCCESS)
	{
		return false;
	}
	
	return true;
}
Example #23
0
void JudgingThread::runProgram()
{
    result = CorrectAnswer;
    int extraTime = qCeil(qMax(2000, timeLimit * 2) * extraTimeRatio);
    
#ifdef Q_OS_WIN32
    SetErrorMode(SEM_NOGPFAULTERRORBOX);
    
    STARTUPINFO si;
    PROCESS_INFORMATION pi;
    SECURITY_ATTRIBUTES sa;
    
    ZeroMemory(&si, sizeof(si));
    si.cb = sizeof(si);
    si.dwFlags = STARTF_USESTDHANDLES;
    ZeroMemory(&pi, sizeof(pi));
    ZeroMemory(&sa, sizeof(sa));
    sa.bInheritHandle = TRUE;
    
    if (task->getStandardInputCheck())
        si.hStdInput = CreateFile((const WCHAR*)(inputFile.utf16()), GENERIC_READ,
                                  FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, &sa,
                                  OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
    
    if (task->getStandardOutputCheck())
        si.hStdOutput = CreateFile((const WCHAR*)((workingDirectory + "_tmpout").utf16()), GENERIC_WRITE,
                                   FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, &sa,
                                   CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
    
    si.hStdError = CreateFile((const WCHAR*)((workingDirectory + "_tmperr").utf16()), GENERIC_WRITE,
                              FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, &sa,
                              CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
    
    QString values = environment.toStringList().join('\0') + '\0';
    if (! CreateProcess(NULL, (WCHAR*)(QString("\"%1\" %2").arg(executableFile, arguments).utf16()), NULL, &sa,
                        TRUE, HIGH_PRIORITY_CLASS | CREATE_NO_WINDOW, (LPVOID)(values.toLocal8Bit().data()),
                        (const WCHAR*)(workingDirectory.utf16()), &si, &pi)) {
        if (task->getStandardInputCheck()) CloseHandle(si.hStdInput);
        if (task->getStandardOutputCheck()) CloseHandle(si.hStdOutput);
        CloseHandle(si.hStdError);
        score = 0;
        result = CannotStartProgram;
        return;
    }
    
    PROCESS_MEMORY_COUNTERS_EX info;
    ZeroMemory(&info, sizeof(info));
    info.cb = sizeof(info);
    if (memoryLimit != -1) {
        GetProcessMemoryInfo(pi.hProcess, (PROCESS_MEMORY_COUNTERS*)&info, sizeof(info));
        if (qMax(info.PrivateUsage, info.PeakWorkingSetSize) > memoryLimit * 1024 * 1024) {
            TerminateProcess(pi.hProcess, 0);
            if (task->getStandardInputCheck()) CloseHandle(si.hStdInput);
            if (task->getStandardOutputCheck()) CloseHandle(si.hStdOutput);
            CloseHandle(si.hStdError);
            CloseHandle(pi.hProcess);
            CloseHandle(pi.hThread);
            score = 0;
            result = MemoryLimitExceeded;
            memoryUsed = timeUsed = -1;
            return;
        }
    }
    
	if (memoryLimit != -1)
        SetProcessWorkingSetSize(pi.hProcess, memoryLimit * 1024 * 1024 / 4, memoryLimit * 1024 * 1024);
    
    bool flag = false;
    QElapsedTimer timer;
    timer.start();
    
    while (timer.elapsed() <= timeLimit + extraTime) {
        if (WaitForSingleObject(pi.hProcess, 0) == WAIT_OBJECT_0) {
            flag = true;
            break;
        }
        if (memoryLimit != -1) {
            GetProcessMemoryInfo(pi.hProcess, (PROCESS_MEMORY_COUNTERS*)&info, sizeof(info));
            if (qMax(info.PrivateUsage, info.PeakWorkingSetSize) > memoryLimit * 1024 * 1024) {
                TerminateProcess(pi.hProcess, 0);
                if (task->getStandardInputCheck()) CloseHandle(si.hStdInput);
                if (task->getStandardOutputCheck()) CloseHandle(si.hStdOutput);
                CloseHandle(si.hStdError);
                CloseHandle(pi.hProcess);
                CloseHandle(pi.hThread);
                score = 0;
                result = MemoryLimitExceeded;
                memoryUsed = timeUsed = -1;
                return;
            }
        }
        QCoreApplication::processEvents();
        if (stopJudging) {
            TerminateProcess(pi.hProcess, 0);
            if (task->getStandardInputCheck()) CloseHandle(si.hStdInput);
            if (task->getStandardOutputCheck()) CloseHandle(si.hStdOutput);
            CloseHandle(si.hStdError);
            CloseHandle(pi.hProcess);
            CloseHandle(pi.hThread);
            return;
        }
        Sleep(10);
    }
    
    if (! flag) {
        TerminateProcess(pi.hProcess, 0);
        if (task->getStandardInputCheck()) CloseHandle(si.hStdInput);
        if (task->getStandardOutputCheck()) CloseHandle(si.hStdOutput);
        CloseHandle(si.hStdError);
        CloseHandle(pi.hProcess);
        CloseHandle(pi.hThread);
        score = 0;
        result = TimeLimitExceeded;
        timeUsed = -1;
        return;
    }
    
    unsigned long exitCode;
    GetExitCodeProcess(pi.hProcess, &exitCode);
    if (exitCode != 0) {
        if (task->getStandardInputCheck()) CloseHandle(si.hStdInput);
        if (task->getStandardOutputCheck()) CloseHandle(si.hStdOutput);
        CloseHandle(si.hStdError);
        CloseHandle(pi.hProcess);
        CloseHandle(pi.hThread);
        score = 0;
        result = RunTimeError;
        QFile file(workingDirectory + "_tmperr");
        if (file.open(QFile::ReadOnly)) {
            QTextStream stream(&file);
            message = stream.readAll();
            file.close();
        }
        memoryUsed = timeUsed = -1;
        return;
    }
    
    FILETIME creationTime, exitTime, kernelTime, userTime;
    GetProcessTimes(pi.hProcess, &creationTime, &exitTime, &kernelTime, &userTime);
    
    SYSTEMTIME realTime;
    FileTimeToSystemTime(&userTime, &realTime);
    
    timeUsed = realTime.wMilliseconds
               + realTime.wSecond * 1000
               + realTime.wMinute * 60 * 1000
               + realTime.wHour * 60 * 60 * 1000;
    
    GetProcessMemoryInfo(pi.hProcess, (PROCESS_MEMORY_COUNTERS*)&info, sizeof(info));
    memoryUsed = info.PeakWorkingSetSize;
    
    if (task->getStandardInputCheck()) CloseHandle(si.hStdInput);
    if (task->getStandardOutputCheck()) CloseHandle(si.hStdOutput);
    CloseHandle(si.hStdError);
    CloseHandle(pi.hProcess);
    CloseHandle(pi.hThread);
#endif
    
#ifdef Q_OS_LINUX
    QFile::copy(":/watcher/watcher_unix", workingDirectory + "watcher");
    QProcess::execute(QString("chmod +wx \"") + workingDirectory + "watcher" + "\"");
    
    QProcess *runner = new QProcess(this);
    QStringList argumentsList;
    argumentsList << QString("\"%1\" %2").arg(executableFile, arguments);
    if (task->getStandardInputCheck())
        argumentsList << QFileInfo(inputFile).absoluteFilePath();
    else
        argumentsList << "";
    if (task->getStandardOutputCheck())
        argumentsList << "_tmpout";
    else
        argumentsList << "";
    argumentsList << "_tmperr";
    argumentsList << QString("%1").arg(timeLimit + extraTime);
    argumentsList << QString("%1").arg(memoryLimit);
    runner->setProcessEnvironment(environment);
    runner->setWorkingDirectory(workingDirectory);
    runner->start(workingDirectory + "watcher", argumentsList);
    if (! runner->waitForStarted(-1)) {
        delete runner;
        score = 0;
        result = CannotStartProgram;
        return;
    }
    
    bool flag = false;
    QElapsedTimer timer;
    timer.start();
    
    while (timer.elapsed() <= timeLimit + extraTime) {
        if (runner->state() != QProcess::Running) {
            flag = true;
            break;
        }
        QCoreApplication::processEvents();
        if (stopJudging) {
            runner->terminate();
            runner->waitForFinished(-1);
            delete runner;
            return;
        }
        msleep(10);
    }
    
    if (! flag) {
        runner->terminate();
        runner->waitForFinished(-1);
        delete runner;
        score = 0;
        result = TimeLimitExceeded;
        timeUsed = memoryUsed = -1;
        return;
    }
    
    int code = runner->exitCode();
    
    if (code == 1) {
        delete runner;
        score = 0;
        result = CannotStartProgram;
        timeUsed = memoryUsed = -1;
        return;
    }
    
    if (code == 2) {
        delete runner;
        score = 0;
        result = RunTimeError;
        QFile file(workingDirectory + "_tmperr");
        if (file.open(QFile::ReadOnly)) {
            QTextStream stream(&file);
            message = stream.readAll();
            file.close();
        }
        timeUsed = memoryUsed = -1;
        return;
    }
    
    QString out = QString::fromLocal8Bit(runner->readAllStandardOutput().data());
    QTextStream stream(&out, QIODevice::ReadOnly);
    stream >> timeUsed >> memoryUsed;
    
    if (memoryUsed <= 0) memoryLimit = -1;
    
    if (code == 3) {
        delete runner;
        score = 0;
        result = TimeLimitExceeded;
        timeUsed = -1;
        return;
    }
    
    if (code == 4) {
        delete runner;
        score = 0;
        result = MemoryLimitExceeded;
        memoryUsed = -1;
        return;
    }
    
    delete runner;
#endif
}
Example #24
0
void JudgingThread::specialJudge(const QString &fileName)
{
    if (! QFileInfo(inputFile).exists()) {
        score = 0;
        result = FileError;
        message = tr("Cannot find standard input file");
        return;
    }
    
    if (! QFileInfo(fileName).exists()) {
        score = 0;
        result = FileError;
        message = tr("Cannot find contestant\'s output file");
        return;
    }
    
    if (! QFileInfo(outputFile).exists()) {
        score = 0;
        result = FileError;
        message = tr("Cannot find standard output file");
        return;
    }
    
    QProcess *judge = new QProcess(this);
    QStringList arguments;
    arguments << inputFile << fileName << outputFile << QString("%1").arg(fullScore);
    arguments << workingDirectory + "_score";
    arguments << workingDirectory + "_message";
    judge->start(Settings::dataPath() + task->getSpecialJudge(), arguments);
    if (! judge->waitForStarted(-1)) {
        score = 0;
        result = InvalidSpecialJudge;
        delete judge;
        return;
    }
    
    QElapsedTimer timer;
    timer.start();
    bool flag = false;
    while (timer.elapsed() < specialJudgeTimeLimit) {
        if (judge->state() != QProcess::Running) {
            flag = true;
            break;
        }
        QCoreApplication::processEvents();
        if (stopJudging) {
            judge->kill();
            delete judge;
            return;
        }
        msleep(10);
    }
    if (! flag) {
        judge->kill();
        score = 0;
        result = SpecialJudgeTimeLimitExceeded;
        delete judge;
        return;
    } else
        if (judge->exitCode() != 0) {
            score = 0;
            result = SpecialJudgeRunTimeError;
            delete judge;
            return;
        }
    delete judge;
    
    QFile scoreFile(workingDirectory + "_score");
    if (! scoreFile.open(QFile::ReadOnly)) {
        score = 0;
        result = InvalidSpecialJudge;
        return;
    }
    
    QTextStream scoreStream(&scoreFile);
    scoreStream >> score;
    if (scoreStream.status() == QTextStream::ReadCorruptData) {
        score = 0;
        result = InvalidSpecialJudge;
        return;
    }
    scoreFile.close();
    
    if (score < 0) {
        score = 0;
        result = InvalidSpecialJudge;
        return;
    }
    
    QFile messageFile(workingDirectory + "_message");
    if (messageFile.open(QFile::ReadOnly)) {
        QTextStream messageStream(&messageFile);
        message = messageStream.readAll();
        messageFile.close();
    }
    
    if (score == 0) result = WrongAnswer;
    if (0 < score && score < fullScore) result = PartlyCorrect;
    if (score >= fullScore) result = CorrectAnswer;
    
    scoreFile.remove();
    messageFile.remove();
}
Example #25
0
// Index any files that are attached.
void IndexRunner::indexAttachment(qint32 lid, Resource &r) {
    if (!officeFound)
        return;
    QLOG_DEBUG() << "indexing attachment to note " << lid;
    if (!keepRunning || pauseIndexing) {
        //indexTimer->start();
        return;
    }
    ResourceTable rtable(db);
    qint32 reslid = rtable.getLid(r.guid);
    if (lid <= 0) {
        //indexTimer->start();
        return;
    }
    QLOG_DEBUG() << "Resource " << reslid;
    QString extension = "";
    ResourceAttributes attributes;
    if (r.attributes.isSet())
        attributes = r.attributes;
    if (attributes.fileName.isSet()) {
        extension = attributes.fileName;
        int i = extension.indexOf(".");
	if (i != -1)
	  extension = extension.mid(i);
    }
    if (extension != ".doc"  && extension != ".xls"  && extension != ".ppt" &&
        extension != ".docx" && extension != ".xlsx" && extension != ".pptx" &&
        extension != ".pps"  && extension != ".pdf"  && extension != ".odt"  &&
        extension != ".odf"  && extension != ".ott"  && extension != ".odm"  &&
        extension != ".html" && extension != ".txt"  && extension != ".oth"  &&
        extension != ".ods"  && extension != ".ots"  && extension != ".odg"  &&
        extension != ".otg"  && extension != ".odp"  && extension != ".otp"  &&
        extension != ".odb"  && extension != ".oxt"  && extension != ".htm"  &&
        extension != ".docm")
                return;

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

    QString outDir = global.fileManager.getTmpDirPath();

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

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

    QLOG_DEBUG() << "Starting soffice ";
    sofficeProcess.waitForStarted();
    QLOG_DEBUG() << "Waiting for completion";
    sofficeProcess.waitForFinished();
    int rc = sofficeProcess.exitCode();
    QLOG_DEBUG() << "soffice Errors:" << sofficeProcess.readAllStandardError();
    QLOG_DEBUG() << "soffice Output:" << sofficeProcess.readAllStandardOutput();
    QLOG_DEBUG() << "return code:" << rc;
    if (rc == 255) {
        QLOG_ERROR() << "soffice not found.  Disabling attachment indexing.";
        this->officeFound = false;
        return;
    }
    QFile txtFile(outDir+QString::number(reslid) +".txt");
    if (txtFile.open(QIODevice::ReadOnly)) {
        QString text;
        text = txtFile.readAll();
        NSqlQuery sql(db);
        db->lockForWrite();
        sql.prepare("Insert into SearchIndex (lid, weight, source, content) values (:lid, :weight, 'recognition', :content)");
        sql.bindValue(":lid", lid);
        sql.bindValue(":weight", 100);
        if (!global.forceSearchLowerCase)
            sql.bindValue(":content", text);
        else
            sql.bindValue(":content", text.toLower());
        QLOG_DEBUG() << "Adding note resource to index DB";
        sql.exec();
        db->unlock();
        txtFile.close();
    }
    QDir dir;
    dir.remove(outDir+QString::number(reslid) +".txt");
}
Example #26
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 = KbManager::parseVersionString(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;
    }
Example #27
0
AbstractFilter::FilterResult ToneAdjustFilter::apply(const QString &sourceFile, const QString &outputFile, AudioFileModel_TechInfo *const formatInfo, volatile bool *abortFlag)
{
	QProcess process;
	QStringList args;

	args << "-V3" << "-S";
	args << "--guard" << "--temp" << ".";
	args << QDir::toNativeSeparators(sourceFile);
	args << QDir::toNativeSeparators(outputFile);

	if(m_bass != 0)
	{
		args << "bass" << QString().sprintf("%s%.2f", ((m_bass < 0) ? "-" : "+"), static_cast<double>(abs(m_bass)) / 100.0);
	}
	if(m_treble != 0)
	{
		args << "treble" << QString().sprintf("%s%.2f", ((m_treble < 0) ? "-" : "+"), static_cast<double>(abs(m_treble)) / 100.0);
	}

	if(!startProcess(process, m_binary, args, QFileInfo(outputFile).canonicalPath()))
	{
		return AbstractFilter::FILTER_FAILURE;
	}

	bool bTimeout = false;
	bool bAborted = false;

	QRegExp regExp("In:(\\d+)(\\.\\d+)*%");

	while(process.state() != QProcess::NotRunning)
	{
		if(*abortFlag)
		{
			process.kill();
			bAborted = true;
			emit messageLogged("\nABORTED BY USER !!!");
			break;
		}
		process.waitForReadyRead(m_processTimeoutInterval);
		if(!process.bytesAvailable() && process.state() == QProcess::Running)
		{
			process.kill();
			qWarning("SoX process timed out <-- killing!");
			emit messageLogged("\nPROCESS TIMEOUT !!!");
			bTimeout = true;
			break;
		}
		while(process.bytesAvailable() > 0)
		{
			QByteArray line = process.readLine();
			QString text = QString::fromUtf8(line.constData()).simplified();
			if(regExp.lastIndexIn(text) >= 0)
			{
				bool ok = false;
				int progress = regExp.cap(1).toInt(&ok);
				if(ok) emit statusUpdated(progress);
			}
			else if(!text.isEmpty())
			{
				emit messageLogged(text);
			}
		}
	}

	process.waitForFinished();
	if(process.state() != QProcess::NotRunning)
	{
		process.kill();
		process.waitForFinished(-1);
	}
	
	emit statusUpdated(100);
	emit messageLogged(QString().sprintf("\nExited with code: 0x%04X", process.exitCode()));

	if(bTimeout || bAborted || process.exitCode() != EXIT_SUCCESS || QFileInfo(outputFile).size() == 0)
	{
		return AbstractFilter::FILTER_FAILURE;
	}
	
	return AbstractFilter::FILTER_SUCCESS;
}
Example #28
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);
}
bool DICOMDIRBurningApplication::burnIsoImageFile()
{
    // Es comprova que el fitxer iso que es vol gravar en CD o DVD existeixi
    if (!QFile::exists(m_isoPath))
    {
        m_lastErrorDescription = QObject::tr("The ISO image \"%1\" to burn does not exist.").arg(m_isoPath);
        m_lastError = IsoPathNotFound;
        return false;
    }

    Settings settings;
    QString burningApplicationPath = (settings.getValue(InputOutputSettings::DICOMDIRBurningApplicationPathKey)).toString();

    // Es comprova que el path de l'aplicació de gravar sigui correcte, tot i que en principi s'ha validat en la configuració del DICOMDIR
    if (!QFile::exists(burningApplicationPath))
    {
        m_lastErrorDescription = QObject::tr("The burn application path \"%1\" does not exist.").arg(burningApplicationPath);
        m_lastError = BurnApplicationPathNotFound;
        return false;
    }

    QProcess process;
    QStringList processParameters;

    // Si està activada la opció d'entrar diferents paràmetres segons si es vol gravar un CD o un DVD caldrà afegir-los al processParameters
    if ((settings.getValue(InputOutputSettings::DICOMDIRBurningApplicationHasDifferentCDDVDParametersKey)).toBool())
    {
        switch (m_currentDevice)
        {
            case CreateDicomdir::CdRom:
                processParameters << (settings.getValue(InputOutputSettings::DICOMDIRBurningApplicationCDParametersKey)).toString()
                                     .arg(QDir::toNativeSeparators(m_isoPath)).split(" ");
                break;
            case CreateDicomdir::DvdRom:
                processParameters << (settings.getValue(InputOutputSettings::DICOMDIRBurningApplicationDVDParametersKey)).toString()
                                     .arg(QDir::toNativeSeparators(m_isoPath)).split(" ");
                break;
            default:
                break;
        }
    }
    else
    {
        processParameters << (settings.getValue(InputOutputSettings::DICOMDIRBurningApplicationParametersKey)).toString()
                             .arg(QDir::toNativeSeparators(m_isoPath)).split(" ");
    }

    process.start(burningApplicationPath, processParameters);
    process.waitForFinished(-1);

    if (process.exitCode() != 0)
    {
        m_lastErrorDescription = QObject::tr("An error occurred during the ISO image file burn process.");
        m_lastError = InternalError;

        ERROR_LOG("Error al gravar la imatge ISO amb comanda: " + burningApplicationPath + "; Amb paràmetres: " + processParameters.join(" ") +
                  "; Exit code qprocess: " + process.exitCode());
        return false;
    }
    return true;
}
Example #30
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;
}