Example #1
0
std::list<int> ProcessControl::getPidProcessByName(std::string name)
{
    std::list<int> result;
    qDebug() << "ProcessControl::getPidProcessByName: Begin:";
#ifndef WIN32
    QProcess myprocess;
    std::string command = std::string("ps -C ")+name+std::string(" -o pid --no-heading");
    qDebug() << "ProcessControl::getPidProcessByName: comando solicitado:" << command.c_str();
    myprocess.start(command.c_str());
    if (!myprocess.waitForFinished()) return result;
    while (!myprocess.atEnd())
    {
        char buf[16];
        qint64 length = myprocess.readLine(buf,sizeof(buf));
        if (length != -1)
        {
            QString mystring(buf);
            result.push_back(mystring.toInt());
        }
        else break;
    }
#else
      DWORD aProcesses[1024], cbNeeded, cProcesses;
      if ( !EnumProcesses( aProcesses, sizeof(aProcesses), &cbNeeded ) )
	      return result;
      // Calculate how many process identifiers were returned.

      cProcesses = cbNeeded / sizeof(DWORD);
      for ( int i = 0 ; i < cProcesses; i++)
      {
	      if (aProcesses[i] != 0)
	      {
		      std::wstring nombre = PrintProcessNameAndID( aProcesses[i] );
		      std::string temp;
		      std::copy(nombre.begin(), nombre.end(), std::back_inserter(temp));
		      qDebug() << "ProcessControl::getPidProcessByName: New pid name" << aProcesses[i] <<  temp.c_str();
		      if (QString(temp.c_str()).toLower()==QString(name.c_str()).toLower())
		      {
			      qDebug() << "ProcessControl::getPidProcessByName: found proccess";
			      result.push_back((int)aProcesses[i]);
		      }
	      }
      }
      
      


#endif
    return result;
}
Example #2
0
bool Features::checkEigenvalues(QTransform tr){

    double eig1, eig2, eig3, minDist;
    //qDebug() << "EIGENVALUES";

    QString program = "./eig/eig.exe";
    QStringList arguments;
    arguments << QString::number(tr.m11());
    arguments << QString::number(tr.m12());
    arguments << QString::number(tr.m13());
    arguments << QString::number(tr.m21());
    arguments << QString::number(tr.m22());
    arguments << QString::number(tr.m23());
    arguments << QString::number(tr.m31());
    arguments << QString::number(tr.m32());
    arguments << QString::number(tr.m33());   

    QProcess *eig = new QProcess();
    eig->start(program, arguments);
    eig->waitForFinished();    

    QString line;
    line = eig->readLine();
    eig1 = line.left(line.indexOf('.') + 5).remove('\n').toDouble();
    line = eig->readLine();    
    eig2 = line.left(line.indexOf('.') + 5).remove('\n').toDouble();
    line = eig->readLine();    
    eig3 = line.left(line.indexOf('.') + 5).remove('\n').toDouble();
    //qDebug() << "Eig1:" << eig1 << "| Eig2:" << eig2 << "| Eig3:" << eig3;

    minDist = abs(eig1 - eig2);
    if(abs(eig1 - eig3) < minDist) minDist = abs(eig1 - eig3);
    if(abs(eig2 - eig3) < minDist) minDist = abs(eig2 - eig3);
    //qDebug() << "MinDist:" << minDist;

    return minDist <= 0.5;
}
Example #3
0
bool PreloadCheck::test(const QString& symbol)
{
  const QString fileName = findSharedObjectFile(symbol);
  if (fileName.isEmpty()) {
    setErrorString(QObject::tr("Cannot find file containing symbol: %1").arg(symbol));
    return false;
  }

  if (!QFile(fileName).exists()) {
    setErrorString(QObject::tr("Invalid shared object: %1").arg(fileName));
    return false;
  }

  QStringList args;
  args << "--relocs" << "--wide" << fileName;
  QProcess proc;
  proc.setProcessChannelMode(QProcess::MergedChannels);
  proc.start("readelf", args, QIODevice::ReadOnly);
  if (!proc.waitForFinished()) {
    // TODO: Find out if we want to error out if 'readelf' is missing
    // The question is: Do all (major) distributions ship binutils by default?
    setErrorString(QObject::tr("Failed to run 'readelf' (binutils) binary: %1").arg(QString(proc.errorString())));
    return false;
  }

  if (proc.exitCode() != 0) {
    setErrorString(QObject::tr("Cannot read shared object: %1").arg(QString(proc.readAll())));
    return false;
  }

  // Example line on x86_64: 00000049f3d8  054300000007 R_X86_64_JUMP_SLO 000000000016c930 qt_startup_hook + 0
  // Example line on   i386: 002e02f0  00034407 R_386_JUMP_SLOT        00181490   qt_startup_hook
  QRegExp rx("^(?:[^ ]+\\s+){4}([^ ]+)(?:.*)$");
  while(proc.canReadLine()) {
    const QString line = proc.readLine().trimmed();
    if (!rx.exactMatch(line))
      continue;

    const QString currentSymbol = rx.cap(1);
    if (currentSymbol == symbol) {
      qDebug() << "Found relocatable symbol in" << fileName << ":" << symbol;
      setErrorString(QString());
      return true;
    }
  }

  setErrorString(QObject::tr("Symbol is not marked as relocatable: %1").arg(symbol));
  return false;
}
Example #4
0
void KCookie::getXCookie()
{
#if HAVE_X11
    d->display = qgetenv("DISPLAY");
    if (d->display.isEmpty()) {
        // maybe we are on Wayland?
        d->display = qgetenv("WAYLAND_DISPLAY");
        if (!d->display.isEmpty()) {
            // don't go into the xauth code path
            return;
        }
    }
#else
    d->display = qgetenv("QWS_DISPLAY");
#endif
    if (d->display.isEmpty()) {
        qCritical() << "[" << __FILE__ << ":" << __LINE__ << "] " << "$DISPLAY is not set.";
        return;
    }
#if HAVE_X11 // No need to mess with X Auth stuff
    QByteArray disp = d->display;
    if (disp.startsWith("localhost:")) { // krazy:exclude=strings
        disp.remove(0, 9);
    }

    QProcess proc;
    proc.start(QStringLiteral("xauth"), QStringList() << QStringLiteral("list") << QString::fromUtf8(disp));
    if (!proc.waitForStarted()) {
        qCritical() << "[" << __FILE__ << ":" << __LINE__ << "] " << "Could not run xauth.";
        return;
    }
    proc.waitForReadyRead(100);

    QByteArray output = proc.readLine().simplified();
    if (output.isEmpty()) {
        qWarning() << "No X authentication info set for display" << d->display;
        return;
    }

    QList<QByteArray> lst = output.split(' ');
    if (lst.count() != 3) {
        qCritical() << "[" << __FILE__ << ":" << __LINE__ << "] " << "parse error.";
        return;
    }
    d->displayAuth = (lst[1] + ' ' + lst[2]);
    proc.waitForFinished(100); // give QProcess a chance to clean up gracefully
#endif
}
Example #5
0
void dialogCheckHardware::getVideo()
{
   QString tmp, res, driver;
   QProcess d;
   d.start(QString("xdpyinfo"), QStringList());
   while(d.state() == QProcess::Starting || d.state() == QProcess::Running) {
      d.waitForFinished(200);
      QCoreApplication::processEvents();
   }

   while (d.canReadLine()) {
     tmp = d.readLine().simplified();
     if ( tmp.indexOf("dimensions:") != -1 ) {
       res = tmp.section(" ", 1, 1);
       break;
     }
   }

   // Figure out the driver
   QFile file("/var/log/Xorg.0.log");
   if (file.open(QIODevice::ReadOnly | QIODevice::Text)) {
     QTextStream in(&file);
     while (!in.atEnd()) {
        QString line = in.readLine();
        if ( line.indexOf("Loading /usr/local/lib/xorg/modules/drivers/") != -1 ) {
           QFileInfo fi(line);
           driver = fi.fileName();
           driver = driver.section("_", 0, 0);
           break;
        }
     }
    file.close();
   }


  if ( driver != "vesa" ) {
     labelVideoDriverIcon->setPixmap(QPixmap(":/modules/images/ok.png"));
  } else {
     labelVideoDriverIcon->setPixmap(QPixmap(":/modules/images/failed.png"));
  } 
  labelVideoDriverIcon->setScaledContents(true);
  labelVideoDriver->setText(tr("Video driver:") + " (" + driver + ")" );
  labelVideoResolution->setText(tr("Video resolution:") + " (" + res + ")" );
  labelVideoResolutionIcon->setPixmap(QPixmap(":/modules/images/ok.png"));
  labelVideoResolutionIcon->setScaledContents(true);

}
Example #6
0
void HgMergeDialog::updateInitialDialog()
{
    HgWrapper *hgWrapper = HgWrapper::instance();

    // update label - current branch
    QString line("<b>parents:</b> ");
    line += hgWrapper->getParentsOfHead();
    m_currentChangeset->setText(line);

    // update heads list
    QProcess process;
    process.setWorkingDirectory(hgWrapper->getBaseDir());

    QStringList args;
    args << QLatin1String("heads");
    args << QLatin1String("--template");
    args << QLatin1String("{rev}\n{node|short}\n{branch}\n"
                          "{author}\n{desc|firstline}\n");

    process.start(QLatin1String("hg"), args);
    m_commitInfoWidget->clear();

    const int FINAL = 5;
    char buffer[FINAL][1024];
    int count = 0;
    while (process.waitForReadyRead()) {
        while (process.readLine(buffer[count], sizeof(buffer[count])) > 0) {
            if (count == FINAL - 1) {
                QString rev = QTextCodec::codecForLocale()->toUnicode(buffer[0]).trimmed();
                QString changeset = QTextCodec::codecForLocale()->toUnicode(buffer[1]).trimmed();
                QString branch = QTextCodec::codecForLocale()->toUnicode(buffer[2]).trimmed();
                QString author = QTextCodec::codecForLocale()->toUnicode(buffer[3]).trimmed();
                QString log = QTextCodec::codecForLocale()->toUnicode(buffer[4]).trimmed();

                QListWidgetItem *item = new QListWidgetItem;
                item->setData(Qt::DisplayRole, changeset);
                item->setData(Qt::UserRole + 1, rev);
                item->setData(Qt::UserRole + 2, branch);
                item->setData(Qt::UserRole + 3, author);
                item->setData(Qt::UserRole + 4, log);
                m_commitInfoWidget->addItem(item);

            }
            count = (count + 1)%FINAL;
        }
    }
}
Example #7
0
void VapoursynthSource::flushProcess(QProcess &processInput)
{
	while(processInput.bytesAvailable() > 0)
	{
		log(tr("vpyp [info]: %1").arg(QString::fromUtf8(processInput.readLine()).simplified()));
	}
	
	if(processInput.exitCode() != EXIT_SUCCESS)
	{
		const int exitCode = processInput.exitCode();
		log(tr("\nWARNING: Input process exited with error (code: %1), your encode might be *incomplete* !!!").arg(QString::number(exitCode)));
		if((exitCode < 0) || (exitCode >= 32))
		{
			log(tr("\nIMPORTANT: The Vapoursynth process terminated abnormally. This means Vapoursynth or one of your Vapoursynth-Plugin's just crashed."));
		}
	}
}
void AvisynthSource::flushProcess(QProcess &processInput)
{
	while(processInput.bytesAvailable() > 0)
	{
		log(tr("av2y [info]: %1").arg(QString::fromUtf8(processInput.readLine()).simplified()));
	}
	
	if(processInput.exitCode() != EXIT_SUCCESS)
	{
		const int exitCode = processInput.exitCode();
		log(tr("\nWARNING: Input process exited with error (code: %1), your encode might be *incomplete* !!!").arg(QString::number(exitCode)));
		if((exitCode < 0) || (exitCode >= 32))
		{
			log(tr("\nIMPORTANT: The Avs2YUV process terminated abnormally. This means Avisynth or one of your Avisynth-Plugin's just crashed."));
			log(tr("IMPORTANT: Please fix your Avisynth script and try again! If you use Avisynth-MT, try using a *stable* Avisynth instead!"));
		}
	}
}
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 #10
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 #11
0
bool KBugReport::sendBugReport()
{
#ifndef EMSCRIPTEN
  QString recipient ( d->m_aboutData ?
    d->m_aboutData->bugAddress() :
    QString::fromLatin1("*****@*****.**") );

  QString command;
  command = KStandardDirs::locate("exe", "ksendbugmail");
  if (command.isEmpty())
      command = KStandardDirs::findExe( QString::fromLatin1("ksendbugmail") );

  QProcess proc;
  QStringList args;
  args << "--subject" << d->m_subject->text() << "--recipient" << recipient;
  proc.start( command, args );
  //kDebug() << command << args;
  if (!proc.waitForStarted())
  {
    kError() << "Unable to open a pipe to " << command << endl;
    return false;
  }
  proc.write( text().toUtf8() );
  proc.closeWriteChannel();

  proc.waitForFinished();
  kDebug() << "kbugreport: sendbugmail exit, status " << proc.exitStatus() << " code " << proc.exitCode();

  QByteArray line;
  if (proc.exitStatus() == QProcess::NormalExit && proc.exitCode() != 0) {
      // XXX not stderr?
      while (!proc.atEnd())
          line = proc.readLine();
      d->lastError = QString::fromUtf8( line );
      return false;
  }
  return true;
#else
  kWarning() << "Bug report stuff not supported on Emscripten";
  return false;
#endif
}
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
QStringList AndroidConfigurations::sdkTargets(int minApiLevel) const
{
    QStringList targets;
    QProcess proc;
    proc.start(androidToolPath().toString(), QStringList() << QLatin1String("list") << QLatin1String("target")); // list avaialbe AVDs
    if (!proc.waitForFinished(-1)) {
        proc.terminate();
        return targets;
    }
    while (proc.canReadLine()) {
        const QString line = QString::fromLocal8Bit(proc.readLine().trimmed());
        int index = line.indexOf(QLatin1String("\"android-"));
        if (index == -1)
            continue;
        QString apiLevel = line.mid(index + 1, line.length() - index - 2);
        if (apiLevel.mid(apiLevel.lastIndexOf(QLatin1Char('-')) + 1).toInt() >= minApiLevel)
            targets.push_back(apiLevel);
    }
    return targets;
}
Example #14
0
// Open the parent directory of the given path with a file manager and select
// (if possible) the item at the given path
void Utils::Misc::openFolderSelect(const QString &absolutePath)
{
    const QString path = Utils::Fs::fromNativePath(absolutePath);
    // If the item to select doesn't exist, try to open its parent
    if (!QFileInfo(path).exists()) {
        openPath(path.left(path.lastIndexOf("/")));
        return;
    }
#ifdef Q_OS_WIN
    HRESULT hresult = ::CoInitializeEx(nullptr, COINIT_MULTITHREADED);
    PIDLIST_ABSOLUTE pidl = ::ILCreateFromPathW(reinterpret_cast<PCTSTR>(Utils::Fs::toNativePath(path).utf16()));
    if (pidl) {
        ::SHOpenFolderAndSelectItems(pidl, 0, nullptr, 0);
        ::ILFree(pidl);
    }
    if ((hresult == S_OK) || (hresult == S_FALSE))
        ::CoUninitialize();
#elif defined(Q_OS_UNIX) && !defined(Q_OS_MAC)
    QProcess proc;
    proc.start("xdg-mime", QStringList() << "query" << "default" << "inode/directory");
    proc.waitForFinished();
    QString output = proc.readLine().simplified();
    if ((output == "dolphin.desktop") || (output == "org.kde.dolphin.desktop"))
        proc.startDetached("dolphin", QStringList() << "--select" << Utils::Fs::toNativePath(path));
    else if ((output == "nautilus.desktop") || (output == "org.gnome.Nautilus.desktop")
             || (output == "nautilus-folder-handler.desktop"))
        proc.startDetached("nautilus", QStringList() << "--no-desktop" << Utils::Fs::toNativePath(path));
    else if (output == "nemo.desktop")
        proc.startDetached("nemo", QStringList() << "--no-desktop" << Utils::Fs::toNativePath(path));
    else if ((output == "konqueror.desktop") || (output == "kfmclient_dir.desktop"))
        proc.startDetached("konqueror", QStringList() << "--select" << Utils::Fs::toNativePath(path));
    else
        // "caja" manager can't pinpoint the file, see: https://github.com/qbittorrent/qBittorrent/issues/5003
        openPath(path.left(path.lastIndexOf("/")));
#else
    openPath(path.left(path.lastIndexOf("/")));
#endif
}
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();
}
Example #16
0
DeviceList DeviceInfo::alsaDevices()
{
    qDebug("DeviceInfo::alsaDevices");

    DeviceList l;
    QRegExp rx_device("^card\\s([0-9]+).*\\[(.*)\\],\\sdevice\\s([0-9]+):");

    QProcess p;
    p.setProcessChannelMode( QProcess::MergedChannels );
    p.setEnvironment( QStringList() << "LC_ALL=C" );
    p.start("aplay", QStringList() << "-l");

    if (p.waitForFinished())
    {
        QByteArray line;
        while (p.canReadLine())
        {
            line = p.readLine();
            qDebug("DeviceInfo::alsaDevices: '%s'", line.constData());
            if ( rx_device.indexIn(line) > -1 )
            {
                QString id = rx_device.cap(1);
                id.append(".");
                id.append(rx_device.cap(3));
                QString desc = rx_device.cap(2);
                qDebug("DeviceInfo::alsaDevices: found device: '%s' '%s'", id.toUtf8().constData(), desc.toUtf8().constData());
                l.append( DeviceData(id, desc) );
            }
        }
    }
    else
    {
        qDebug("DeviceInfo::alsaDevices: could not start aplay, error %d", p.error());
    }

    return l;
}
Example #17
0
void sndDialog::refreshDevices()
{
    defaultUnit = -1 ;
    comboSound->clear();

    // List the sound devices
    QString tmp, snd;
    QProcess d;
    d.start(QString("cat"), QStringList() << "/dev/sndstat");
    while(d.state() == QProcess::Starting || d.state() == QProcess::Running) {
        d.waitForFinished(200);
        QCoreApplication::processEvents();
    }

    int i = 0;
    while (d.canReadLine()) {
        tmp = d.readLine().simplified();
        if ( tmp.indexOf("pcm") == 0 ) {
            comboSound->addItem(tmp);
            if ( tmp.indexOf("default") != -1 ) {
                defaultUnit=i;
                comboSound->setCurrentIndex(i);
            }
            i++;
        }
    }

    if ( defaultUnit == -1 ) {
        labelDesc->setText(tr("No sound devices detected!"));
        pushTest->setEnabled(false);
        pushApply->setEnabled(false);
        comboSound->setEnabled(false);
    }

    pushApply->setEnabled(false);
}
Example #18
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 #19
0
Defines GccLikeCompiler::defines(const QString& arguments) const
{
    if (!m_definesIncludes.value(arguments).definedMacros.isEmpty() ) {
        return m_definesIncludes.value(arguments).definedMacros;
    }

    // #define a 1
    // #define a
    QRegExp defineExpression( "#define\\s+(\\S+)(?:\\s+(.*)\\s*)?");

    QProcess proc;
    proc.setProcessChannelMode( QProcess::MergedChannels );

    // TODO: what about -mXXX or -target= flags, some of these change search paths/defines
    auto compilerArguments = languageOptions(arguments);
    compilerArguments.append("-dM");
    compilerArguments.append("-E");
    compilerArguments.append(QProcess::nullDevice());

    proc.start(path(), compilerArguments);

    if ( !proc.waitForStarted( 1000 ) || !proc.waitForFinished( 1000 ) ) {
        definesAndIncludesDebug() <<  "Unable to read standard macro definitions from "<< path();
        return {};
    }

    while ( proc.canReadLine() ) {
        auto line = proc.readLine();

        if ( defineExpression.indexIn( line ) != -1 ) {
            m_definesIncludes[arguments].definedMacros[defineExpression.cap( 1 )] = defineExpression.cap( 2 ).trimmed();
        }
    }

    return m_definesIncludes[arguments].definedMacros;
}
Example #20
0
void KeyboardLayoutConfig::loadSettings() {
  // load current settings from the output of setxkbmap command
  QProcess setxkbmap;
  setxkbmap.start(QLatin1String("setxkbmap -query -verbose 5"));
  setxkbmap.waitForFinished();
  if(setxkbmap.exitStatus() == QProcess::NormalExit) {
    QList<QByteArray> layouts, variants;
    while(!setxkbmap.atEnd()) {
      QByteArray line = setxkbmap.readLine();
      if(line.startsWith("model:")) {
        keyboardModel_ = QString::fromLatin1(line.mid(6).trimmed());
      }
      else if(line.startsWith("layout:")) {
        layouts = line.mid(7).trimmed().split(',');
      }
      else if(line.startsWith("variant:")) {
        variants = line.mid(8).trimmed().split(',');
      }
      else if(line.startsWith("options:")) {
        const QList<QByteArray> options = line.mid(9).trimmed().split(',');
        Q_FOREACH(const QByteArray &option, options) {
          if(option.startsWith("grp:"))
            switchKey_ = QString::fromLatin1(option);
          else
            currentOptions_ << QString::fromLatin1(option);
        }
      }
    }

    const int size = layouts.size(), variantsSize = variants.size();
    for(int i = 0; i < size; ++i) {
      currentLayouts_.append(QPair<QString, QString>(layouts.at(i), variantsSize > 0 ? variants.at(i) : QString()));
    }

    setxkbmap.close();
  }
int main(int argc, char *argv[])
{

    QApplication a(argc, argv);
#if defined(Q_OS_LINUX)
    // Check if this program is executed as root
    QProcess lsblk;
    lsblk.start(QString("whoami"), QIODevice::ReadOnly);
    lsblk.waitForStarted();
    lsblk.waitForFinished();
    QString output = lsblk.readLine();
    if (!output.contains("root")) {
        qDebug () << "Not executed as root! Closing...";
        QMessageBox::StandardButton nonRoot = QMessageBox::warning(NULL,"Sorry", "Insufficient privileges, Please execute as root!",QMessageBox::Ok);
        if (nonRoot == QMessageBox::Ok) {
            return 0;
        }
    }
#endif

    Dialog devices_window;
    devices_window.show();
    return devices_window.exec();
}
Example #22
0
DeviceList DeviceInfo::retrieveDevices(DeviceType type)
{
    qDebug("DeviceInfo::retrieveDevices: %d", type);

    DeviceList l;
    QRegExp rx_device("^(\\d+): (.*)");

    if (QFile::exists("dxlist.exe")) {
        QProcess p;
        p.setProcessChannelMode(QProcess::MergedChannels);
        QStringList arg;

        if (type == Sound) arg << "-s";
        else arg << "-d";

        p.start("dxlist", arg);

        if (p.waitForFinished()) {
            QByteArray line;

            while (p.canReadLine()) {
                line = p.readLine().trimmed();
                qDebug("DeviceInfo::retrieveDevices: '%s'", line.constData());

                if (rx_device.indexIn(line) > -1) {
                    int id = rx_device.cap(1).toInt();
                    QString desc = rx_device.cap(2);
                    qDebug("DeviceInfo::retrieveDevices: found device: '%d' '%s'", id, desc.toUtf8().constData());
                    l.append(DeviceData(id, desc));
                }
            }
        }
    }

    return l;
}
Example #23
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 #24
0
void mainWin::checkFBSDUpdates() {
  QString line, toPatchVer, tmp;
  QStringList up, listDesc, listPkgs;

  if ( QFile::exists("/tmp/.fbsdup-reboot") ) {
     qDebug() << "Skipping update check - Waiting for reboot";
     return;
  }

  if ( QFile::exists("/tmp/.fbsdup-lock") ) {
     qDebug() << "Skipping update check - freebsd-update is running elsewhere";
     return;
  }

  // Now check if there are freebsd-updates to install
  QProcess f;
  if ( wDir.isEmpty() )
     f.start(QString("pc-fbsdupdatecheck"), QStringList() << "update" );
  else {
     QProcess::execute("cp /usr/local/bin/pc-fbsdupdatecheck " + wDir + "/tmp/.fbupdatechk");
     QProcess::execute("chmod 755 " + wDir + "/tmp/.fbupdatechk");
     f.start(QString("chroot"), QStringList() << wDir << "/tmp/.fbupdatechk" << "update" );
  }
  while(f.state() == QProcess::Starting || f.state() == QProcess::Running)
     QCoreApplication::processEvents();

  bool fUp = false;
  
  while (f.canReadLine()) {
    line = f.readLine().simplified();
    qDebug() << line;
    if ( line.indexOf("The following files will be ") == 0) {
       toPatchVer= line.remove(0, line.lastIndexOf(" "));
       toPatchVer=toPatchVer.section("-", 2,2);
       toPatchVer=toPatchVer.section(":", 0,0);
       toPatchVer=toPatchVer.section("p", 1,1);
       fUp = true;
       listPkgs << " " << tr("The following files will be updated:");
       continue;
    }

    if ( fUp )
       listPkgs << line;
  }

  if ( ! wDir.isEmpty() )
     QProcess::execute("rm " + wDir + "/tmp/.fbupdatechk");

  // Are there freebsd updates to install?
  if ( fUp ) {
    QString mySysVer;
    QString myPatchVer;

    // Lets try and fetch the desc file
    QProcess::execute("fetch -o /tmp/.fbsdupdesc http://fbsd-update.pcbsd.org/updates.desc");

    // Get the current system ver
    QProcess p;
    p.start(QString("uname"), QStringList() << "-r");
    while(p.state() == QProcess::Starting || p.state() == QProcess::Running)
       QCoreApplication::processEvents();
    tmp = p.readLine().simplified();
    mySysVer = tmp;
    myPatchVer = tmp;
    mySysVer = mySysVer.section("-", 0, 1);
    mySysVer = mySysVer.section("-", 0, 1);
    myPatchVer = myPatchVer.section("-", 2, 2);
    myPatchVer = myPatchVer.section(":", 0, 0);
    myPatchVer = myPatchVer.section("p", 1, 1);

    QFile file("/tmp/.fbsdupdesc");
    if (file.open(QIODevice::ReadOnly | QIODevice::Text)) {
	listDesc << tr("Update Details:");
      while (!file.atEnd()) {
         line = file.readLine();
         tmp = line;
	 if ( tmp.section(":::", 0, 0) != mySysVer ) 
	    continue;
	 if ( tmp.section(":::", 1, 1) <= myPatchVer )
	    continue;
	 if ( tmp.section(":::", 1, 1) > toPatchVer )
	    continue;
	 listDesc << tmp.section(":::", 2, 2);
      }
    }

    up.clear();
    up << "FreeBSD Security Updates" << "FBSDUPDATE";
    up.append(listDesc + listPkgs);
    listUpdates.append(up);
  }

}
Example #25
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 #26
0
void mainWin::checkPCUpdates() {

  QString line, tmp, name, type, version, date, tag, url, size, sa, rr;
  QStringList up;

  QProcess p;
  p.start(QString("pc-updatemanager"), QStringList() << "check");
  while(p.state() == QProcess::Starting || p.state() == QProcess::Running)
     QCoreApplication::processEvents();

  while (p.canReadLine()) {
    line = p.readLine().simplified();
    if ( line.indexOf("NAME: ") == 0) {
       name = line.replace("NAME: ", "");
       continue;
    }
    if ( line.indexOf("TYPE: ") == 0) {
       type = line.replace("TYPE: ", "");
       continue;
    }

    if ( type == "SYSUPDATE" ) {
      if ( line.indexOf("VERSION: ") == 0) {
         version = line.replace("VERSION: ", "");
         continue;
      }
      if ( line.indexOf("DATE: ") == 0) {
         date = line.replace("DATE: ", "");
         continue;
      }
      if ( line.indexOf("TAG: ") == 0) {
         tag = line.replace("TAG: ", "");
         continue;
      }
      if ( line.indexOf("DETAILS: ") == 0) {
         url = line.replace("DETAILS: ", "");
         continue;
      }

      if ( line.indexOf("To install:") == 0) {
         up.clear();
	 up << name << type << version << date << tag << url;
	 listUpdates.append(up);
         type=""; name="", version="", date="", tag="", url="";
         continue;
      }

    }
    if ( type == "PATCH" ) {
      if ( line.indexOf("DATE: ") == 0) {
         date = line.replace("DATE: ", "");
         continue;
      }
      if ( line.indexOf("TAG: ") == 0) {
         tag = line.replace("TAG: ", "");
         continue;
      }
      if ( line.indexOf("SIZE: ") == 0) {
         size = line.replace("SIZE: ", "");
         continue;
      }
      if ( line.indexOf("STANDALONE: ") == 0) {
         sa = line.replace("STANDALONE: ", "");
         continue;
      }
      if ( line.indexOf("REQUIRESREBOOT: ") == 0) {
         rr = line.replace("REQUIRESREBOOT: ", "");
         continue;
      }
      if ( line.indexOf("DETAILS: ") == 0) {
         url = line.replace("DETAILS: ", "");
         continue;
      }
      if ( line.indexOf("To install:") == 0) {
	 // TODO add this update to list
         up.clear();
	 up << name << type << date << tag << size << sa << rr << url;
	 listUpdates.append(up);
         type=""; name="", date="", tag="", size="", sa="", rr="", url="";
         continue;
      }
    }

  }


}
Example #27
0
// Function which checks for our GUI package schema data, and sets found if its located
QList<QStringList> Backend::getPackageData(bool &found, QString pkgset)
{
  if ( pkgset.isEmpty() )
     pkgset="pcbsd";
  QList<QStringList> metaPkgs;
  found=false;
  bool onDisk;
  onDisk=true; 
  QString tmp, mName, mDesc, mIcon, mParent, mDesktop, mPkgFileList;
  QStringList package;

  QProcess pcmp;
  qDebug() << "Searching for meta-pkgs...";
  pcmp.start(QString("/root/get-pkgset.sh"), QStringList());
  if (pcmp.waitForFinished()) {
    while (pcmp.canReadLine()) {
        tmp = pcmp.readLine().simplified();
	if ( tmp.indexOf("Meta Package: ") == 0) {
		mName = tmp.replace("Meta Package: ", "");
		continue;
	}
	if ( tmp.indexOf("Description: ") == 0) {
		mDesc = tmp.replace("Description: ", "");
		continue;
	}
	if ( tmp.indexOf("Icon: ") == 0) {
		mIcon = tmp.replace("Icon: ", "");
	        mPkgFileList = mIcon;
                mPkgFileList.replace("pkg-icon.png", "pkg-list");
		continue;
	}
	if ( tmp.indexOf("Parent: ") == 0) {
		mParent = tmp.replace("Parent: ", "");
		continue;
	}
	if ( tmp.indexOf("Desktop: ") == 0) {
		mDesktop = tmp.replace("Desktop: ", "");
		continue;
	}
        if ( tmp.indexOf("Category Entry") == 0) {
		// Now add this category to the string list
		package.clear();
		//qDebug() << "Found Category" << mName << mDesc << mIcon << mParent<< mDesktop << "CATEGORY";
		package << mName << mDesc << mIcon << mParent << mDesktop << "CATEGORY";
		metaPkgs.append(package);
		mName=""; mDesc=""; mIcon=""; mParent=""; mDesktop=""; mPkgFileList="";
        }

	if ( tmp.indexOf("Required Packages:") == 0) {
		// Now add this meta-pkg to the string list
		package.clear();

		//qDebug() << "Found Package" << mName << mDesc << mIcon << mParent << mDesktop << "NO" << mPkgFileList;
		package << mName << mDesc << mIcon << mParent << mDesktop << "NO" << mPkgFileList;
		metaPkgs.append(package);
		found = true;
		mName=""; mDesc=""; mIcon=""; mParent=""; mDesktop=""; mPkgFileList="";
	}
    }
  }

  return metaPkgs;
}
Example #28
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 #29
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 #30
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;
}