Example #1
0
void dtkComposerGraphView::update(void)
{
    if (!d->graphviz_avail)
        return;

    QByteArray content = d->graph->toString().append("\n").toLocal8Bit() ;
    // run dot
    QStringList arglist;
    arglist << "-Tsvg";
    QString command = "dot";
    QProcess cmd;
    QStringList PATH =  QProcessEnvironment::systemEnvironment().value("PATH").split(":") ;
    QDir::setSearchPaths("bin",PATH);
    if(QFile("bin:"+command).exists()) {

        dtkTrace() << "run graphviz dot" ;
        cmd.start(command, arglist, QProcess::Unbuffered | QProcess::ReadWrite);
        cmd.write(content);
        cmd.closeWriteChannel();
        cmd.waitForBytesWritten();
        qlonglong timeout = 3000;
        QString stdout_data;
        if (cmd.waitForFinished(timeout)) {
            QByteArray svg = cmd.readAllStandardOutput();
            this->load(svg);
        } else {
            dtkWarn() << "graphviz timeout !";
        }
    } else {
        d->graphviz_avail = false;
        dtkWarn() << "can't find 'dot' binary in PATH, graphviz probably not installed";
    }
}
Example #2
0
TTSStatus TTSFestival::voice(QString text, QString wavfile, QString* errStr)
{
    qDebug() << "[Festival] Voicing " << text << "->" << wavfile;

    QString path = RbSettings::subValue("festival-client",
            RbSettings::TtsPath).toString();
    QString cmd = QString("%1 --server localhost --otype riff --ttw --withlisp"
            " --output \"%2\" --prolog \"%3\" - ").arg(path).arg(wavfile).arg(prologPath);
    qDebug() << "[Festival] Client cmd: " << cmd;

    QProcess clientProcess;
    clientProcess.start(cmd);
    clientProcess.write(QString("%1.\n").arg(text).toAscii());
    clientProcess.waitForBytesWritten();
    clientProcess.closeWriteChannel();
    clientProcess.waitForReadyRead();
    QString response = clientProcess.readAll();
    response = response.trimmed();
    if(!response.contains("Utterance"))
    {
        qDebug() << "[Festival] Could not voice string: " << response;
        *errStr = tr("engine could not voice string");
        return Warning;
        /* do not stop the voicing process because of a single string
        TODO: needs proper settings */
    }
    clientProcess.closeReadChannel(QProcess::StandardError);
    clientProcess.closeReadChannel(QProcess::StandardOutput);
    clientProcess.terminate();
    clientProcess.kill();

    return NoError;
}
Example #3
0
bool QProcessProto::waitForBytesWritten(int msecs)
{
  QProcess *item = qscriptvalue_cast<QProcess*>(thisObject());
  if (item)
    return item->waitForBytesWritten(msecs);
  return false;
}
Example #4
0
void tst_qdbusxml2cpp::process()
{
    QFETCH(QString, xmlSnippet);
    QFETCH(QRegularExpression, interfaceSearch);
    QFETCH(QRegularExpression, adaptorSearch);
    QVERIFY2(interfaceSearch.isValid(), qPrintable(interfaceSearch.errorString()));
    QVERIFY2(adaptorSearch.isValid(), qPrintable(adaptorSearch.errorString()));

    // test both interface and adaptor generation
    QFETCH_GLOBAL(int, outputMode);
    QFETCH_GLOBAL(QString, commandLineArg);

    // Run the tool
    const QString binpath = QLibraryInfo::location(QLibraryInfo::BinariesPath);
    const QString command = binpath + QLatin1String("/qdbusxml2cpp");
    QProcess process;
    process.start(command, QStringList() << commandLineArg << "-" << "-N");
    QVERIFY2(process.waitForStarted(), qPrintable(process.errorString()));

    // feed it our XML data
    static const char xmlHeader[] =
            "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n"
            DBUS_INTROSPECT_1_0_XML_DOCTYPE_DECL_NODE // \n is included
            "<node>\n"
            "  <interface name=\"local.name.is.not.important\">\n"
            "    <!-- begin data -->\n";
    static const char xmlFooter[] = "\n"
            "    <!-- end data -->\n"
            "  </interface>\n"
            "</node>\n";

    process.write(xmlHeader, int(sizeof xmlHeader) - 1);
    process.write(xmlSnippet.toLatin1());
    process.write(xmlFooter, int(sizeof xmlFooter) - 1);
    while (process.bytesToWrite())
        QVERIFY2(process.waitForBytesWritten(), qPrintable(process.errorString()));
    //    fprintf(stderr, "%s%s%s", xmlHeader, xmlSnippet.toLatin1().constData(), xmlFooter);

    process.closeWriteChannel();
    QVERIFY2(process.waitForFinished(), qPrintable(process.errorString()));

    QByteArray errOutput = process.readAllStandardError();
    QVERIFY2(errOutput.isEmpty(), errOutput);
    QCOMPARE(process.exitCode(), 0);

    QByteArray fullOutput = process.readAll();
    QString output = stripHeader(QString::fromLatin1(fullOutput));
    QVERIFY2(!output.isEmpty(), fullOutput);
    if (outputMode == Interface)
        QVERIFY2(output.count(interfaceSearch) == 1, qPrintable(interfaceSearch.pattern() + "\nin\n" + output));
    else
        QVERIFY2(output.count(adaptorSearch) == 1, qPrintable(adaptorSearch.pattern() + "\nin\n" + output));
}
Example #5
0
//! [3]
void Window::goDarc()
{


    QStringList pythonCommandArguments = QStringList() << "/rtc/bin/darccontrol" << "-o" << homePath << "--prefix=both";
    qDebug() << pythonCommandArguments.join(" ");
    QProcess *process = new QProcess;
    process->start("python",pythonCommandArguments);
    process->waitForBytesWritten();
    process->waitForFinished();
    qDebug() << process->readAll();
    //process.startDetached("ls .");
}
// Reading and writing to a process is not supported on Qt/CE
void tst_QProcess::echoTest_performance()
{
    QProcess process;
    process.start("testProcessLoopback/testProcessLoopback");

    QByteArray array;
    array.resize(1024 * 1024);
    for (int j = 0; j < array.size(); ++j)
        array[j] = 'a' + (j % 20);

    QVERIFY(process.waitForStarted());

    QTime stopWatch;
    stopWatch.start();

    qint64 totalBytes = 0;
    QByteArray dump;
    QSignalSpy readyReadSpy(&process, SIGNAL(readyRead()));
    QVERIFY(readyReadSpy.isValid());
    while (stopWatch.elapsed() < 2000) {
        process.write(array);
        while (process.bytesToWrite() > 0) {
            int readCount = readyReadSpy.count();
            QVERIFY(process.waitForBytesWritten(5000));
            if (readyReadSpy.count() == readCount)
                QVERIFY(process.waitForReadyRead(5000));
        }

        while (process.bytesAvailable() < array.size())
            QVERIFY2(process.waitForReadyRead(5000), qPrintable(process.errorString()));
        dump = process.readAll();
        totalBytes += dump.size();
    }

    qDebug() << "Elapsed time:" << stopWatch.elapsed() << "ms;"
             << "transfer rate:" << totalBytes / (1048.576) / stopWatch.elapsed()
             << "MB/s";

    for (int j = 0; j < array.size(); ++j)
        QCOMPARE(char(dump.at(j)), char('a' + (j % 20)));

    process.closeWriteChannel();
    QVERIFY(process.waitForFinished());
}
Example #7
0
int main(int argc, char *argv[]) {

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

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

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

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

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

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

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

	cout << "Starting exporting" << endl;

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

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


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

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

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

	cout << "Exporting succeeded" << endl;
	return 0;
}
Example #8
0
void DialogEngines::onAddEngine() {

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

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

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

    this->setEnabled(false);

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

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

}
Example #9
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 #10
0
void Logger::flushPager()
{
    QProcess *pager = _vng_logger_private()->pager;
    if (pager)
        pager->waitForBytesWritten();
}