Exemplo n.º 1
0
int Kandas::Daemon::Engine::addDevice(const QString &deviceName, const QList<QString> &readKey, const QString &writeKey)
{
    //only register new device if no device with this name exists
    if (m_devices.device(deviceName))
        return Kandas::DeviceExistsAlready;
    //validate input
    if (deviceName.contains('/') || deviceName.contains(' ')) //spaces in the device name are possible, but interfere with the parsing of /proc/ndas/devs
        return Kandas::InvalidDeviceName;
    if (readKey.count() != 4)
        return Kandas::InvalidDeviceKey;
    foreach (const QString &keyBlock, readKey)
        if (!validateKeyBlock(keyBlock))
            return Kandas::InvalidDeviceKey;
    if (!validateKeyBlock(writeKey, true))
        return Kandas::InvalidDeviceKey;
    //build key string
    QString keyString = QStringList(readKey).join(QChar('-'));
    if (!writeKey.isEmpty())
        keyString += '-' + writeKey;
    //call ndasadmin
    QStringList args; args << "register" << keyString << "-n" << deviceName << "-b";
    KProcess process;
    process.setProgram("ndasadmin", args);
    process.setOutputChannelMode(KProcess::OnlyStderrChannel);
    process.start();
    process.waitForFinished();
    const QString errorOutput = QString::fromUtf8(process.readAllStandardError()).simplified();
    if (errorOutput.isEmpty())
        return Kandas::DeviceAdded;
    else if (errorOutput.contains(QLatin1String("register: invalid NDAS ID.")))
        return Kandas::InvalidDeviceKey;
    else
        return Kandas::DeviceAdditionFailed;
    //
}
Exemplo n.º 2
0
void TOC::buildCache()
{
    KXmlGuiWindow *mainWindow = dynamic_cast<KXmlGuiWindow *>( kapp->activeWindow() );

    KProcess *meinproc = new KProcess;
    connect( meinproc, SIGNAL( finished( int, QProcess::ExitStatus) ),
             this, SLOT( meinprocExited( int, QProcess::ExitStatus) ) );

    *meinproc << KStandardDirs::locate("exe", "meinproc4");
    *meinproc << "--stylesheet" << KStandardDirs::locate( "data", "khelpcenter/table-of-contents.xslt" );
    *meinproc << "--output" << m_cacheFile;
    *meinproc << m_sourceFile;

    meinproc->setOutputChannelMode(KProcess::OnlyStderrChannel);
    meinproc->start();
    if (!meinproc->waitForStarted()) {
        kError() << "could not start process" << meinproc->program();
        if (mainWindow && !m_alreadyWarned) {
            ; // add warning message box with don't display again option 
              // http://api.kde.org/4.0-api/kdelibs-apidocs/kdeui/html/classKDialog.html
            m_alreadyWarned = true;
        }
        delete meinproc;
    }
}
Exemplo n.º 3
0
QString OcrGocrDialog::version()
{
    kDebug() << "of" << m_ocrCmd;

    QString vers;

    KProcess proc;
    proc.setOutputChannelMode(KProcess::MergedChannels);
    proc << m_ocrCmd << "-h";

    int status = proc.execute(5000);
    if (status==0)
    {
        QByteArray output = proc.readAllStandardOutput();
        QRegExp rx("-- gocr ([\\d\\.\\s]+)");
        if (rx.indexIn(output)>-1) vers = rx.cap(1);
        else vers = i18n("Unknown");
    }
    else
    {
        kDebug() << "failed with status" << status;
        vers = i18n("Error");
    }

    return (vers);
}
Exemplo n.º 4
0
bool EncoderLame::init(){
	// Determine if lame is installed on the system or not.
	if ( KStandardDirs::findExe( "lame" ).isEmpty() )
		return false;

	// Ask lame for the list of genres it knows; otherwise it barfs when doing
	// e.g. lame --tg 'Vocal Jazz'
	KProcess proc;
	proc.setOutputChannelMode(KProcess::MergedChannels);
	proc << "lame" << "--genre-list";
	proc.execute();

	if(proc.exitStatus() != QProcess::NormalExit)
		return false;

	QByteArray array = proc.readAll();
	QString str = QString::fromLocal8Bit( array );
	d->genreList = str.split( '\n', QString::SkipEmptyParts );
	// Remove the numbers in front of every genre
	for( QStringList::Iterator it = d->genreList.begin(); it != d->genreList.end(); ++it ) {
		QString& genre = *it;
		int i = 0;
		while ( i < genre.length() && ( genre[i].isSpace() || genre[i].isDigit() ) )
			++i;
		genre = genre.mid( i );

	}
	//kDebug(7117) << "Available genres:" << d->genreList;

	return true;
}
Exemplo n.º 5
0
QString unquoteWord(const QString &word)
{
    if (word.isEmpty()) {
        return QString();
    }

    KProcess echo;
    echo.setShellCommand(QString(QLatin1String("echo -n %1")).arg(word));
    echo.setOutputChannelMode(KProcess::OnlyStdoutChannel);
    if (echo.execute() == 0) {
        return QString::fromLocal8Bit(echo.readAllStandardOutput().constData());
    }

    QChar ch;
    QString quotedWord = word, unquotedWord;
    QTextStream stream(&quotedWord, QIODevice::ReadOnly | QIODevice::Text);
    while (!stream.atEnd()) {
        stream >> ch;
        if (ch == QLatin1Char('\'')) {
            Q_FOREVER {
                if (stream.atEnd()) {
                    return QString();
                }
                stream >> ch;
                if (ch == QLatin1Char('\'')) {
                    return unquotedWord;
                } else {
                    unquotedWord.append(ch);
                }
            }
        } else if (ch == QLatin1Char('"')) {
Exemplo n.º 6
0
bool K3b::CdrskinProgram::scanFeatures(ExternalBin& bin) const
{
    KProcess fp;
    fp.setOutputChannelMode(KProcess::MergedChannels);
    fp << bin.path() << "-help";

    if (fp.execute() >= 0) {
        QByteArray output = fp.readAll();

        if (output.contains("gracetime"))
            bin.addFeature("gracetime");
        if (output.contains("-overburn"))
            bin.addFeature("overburn");
        if (output.contains("-text"))
            bin.addFeature("cdtext");
        if (output.contains("-clone"))
            bin.addFeature("clone");
        if (output.contains("-tao"))
            bin.addFeature("tao");
    }

#ifdef K3B_DEBUG
    qDebug() << "DEBUG:" << __PRETTY_FUNCTION__ << bin.version(); // 1.4.6 for example
#endif
    // TODO: cdrskin -help | grep XXX
    // Hello Thomas, please help me: the other version number dependent features 
    // need to be checked what they mean and whether cdrskin supports them.
    if (bin.version().suffix().endsWith("-dvd")) {
        bin.addFeature("dvd-patch");
        bin.setVersion(QString(bin.version().versionString()).remove("-dvd"));
    }

    // TODO: find . -name "*.cpp" | xargs grep plain-atapi
    // In src/k3bsystemproblemdialog.cpp there is Check for we have atapi support 
    // in some way in the kernel
    bin.addFeature("plain-atapi");
    // The same story
    bin.addFeature("hacked-atapi");

    bin.addFeature("burnfree");

    if (bin.version() >= K3b::Version(0, 6, 2)) {
#ifdef K3B_DEBUG
        qDebug() << "DEBUG:" << __PRETTY_FUNCTION__ << "Blu-ray support was complete in cdrskin-0.6.2, 20 Feb 2009";
#endif
        bin.addFeature("blu-ray");
    }

    bin.addFeature("dvd");
#ifdef K3B_DEBUG
    qDebug() << "DEBUG:" << __PRETTY_FUNCTION__ << bin.features();
#endif

    return SimpleExternalProgram::scanFeatures(bin);
}
Exemplo n.º 7
0
const QString EncoderAssistant::version(const EncoderAssistant::Encoder encoder) {

  KProcess process;
  process.setOutputChannelMode(KProcess::SeparateChannels);
  process.setReadChannel(KProcess::StandardError);
  switch (encoder) {
    case EncoderAssistant::LAME : process.setShellCommand(QString(ENCODER_LAME_BIN)+" "+QString(ENCODER_LAME_VERSION_PARA)); break;
    case EncoderAssistant::OGGENC : process.setShellCommand(QString(ENCODER_OGGENC_BIN)+" "+QString(ENCODER_OGGENC_VERSION_PARA)); break;
    case EncoderAssistant::FLAC : process.setShellCommand(QString(ENCODER_FLAC_BIN)+" "+QString(ENCODER_FLAC_VERSION_PARA)); break;
    case EncoderAssistant::FAAC : process.setShellCommand(QString(ENCODER_FAAC_BIN)+" "+QString(ENCODER_FAAC_VERSION_PARA)); break;
    case EncoderAssistant::WAVE : return "";
    case EncoderAssistant::CUSTOM : return "";
    default : return "";
  }
  process.start();
  if (!process.waitForFinished()) return "";
  QByteArray rawoutput = process.readAllStandardError();
  if (rawoutput.size() == 0) rawoutput = process.readAllStandardOutput();
  QString output(rawoutput);
  QStringList list = output.trimmed().split("\n");
  if (list.count()==0) return "";
  QStringList words = list[0].split(" ");
  if (words.count()==0) return "";

  switch (encoder) {

    case EncoderAssistant::LAME :
      if ((words.contains("version")) && (words.indexOf("version")+1<words.count())) return words[words.indexOf("version")+1];
      if (words.count()<2) return "";
      return words[words.count()-2];

    case EncoderAssistant::OGGENC :

    case EncoderAssistant::FLAC :
      return words.last();

    case EncoderAssistant::FAAC :
      if (list.count()<2) return "";
      words = list[1].split(" ");
      if (words.count()<2) return "";
      if ((words.contains("FAAC")) && (words.indexOf("FAAC")+1<words.count())) return words[words.indexOf("FAAC")+1];
      return words[1];

    case EncoderAssistant::WAVE :

    case EncoderAssistant::CUSTOM :

    default : ;

  }

  return "";

}
Exemplo n.º 8
0
void PlanExecutor::unmountBupFuse() {
	KProcess lUnmount;
	lUnmount.setOutputChannelMode(KProcess::OnlyStderrChannel);
	lUnmount << QLatin1String("fusermount") << QLatin1String("-u") <<mTempDir;
	if(lUnmount.execute()) {
		KNotification::event(KNotification::Error, i18nc("@title", "Problem"),
		                     i18nc("notification", "Error when trying to unmount backup archive:\n%1",
		                           QString::fromLocal8Bit(lUnmount.readAllStandardError())));
		mShowFilesAction->setChecked(true);
	}
}
Exemplo n.º 9
0
void QtHelpQtDoc::registerDocumentations()
{
    const QString qmake = qmakeCandidate();
    if (!qmake.isEmpty()) {
        KProcess *p = new KProcess;
        p->setOutputChannelMode(KProcess::MergedChannels);
        p->setProgram(qmake, QStringList("-query") << "QT_INSTALL_DOCS");
        p->start();
        connect(p, static_cast<void(KProcess::*)(int)>(&KProcess::finished), this, &QtHelpQtDoc::lookupDone);
    }
}
Exemplo n.º 10
0
void StatsVnstat::importIfaceStats()
{
    mExternalHours->clear();
    mExternalDays->clear();
    KProcess vnstatProc;
    vnstatProc.setOutputChannelMode( KProcess::OnlyStdoutChannel );
    vnstatProc.setEnv( "LANG", "C" );
    vnstatProc.setEnv( "LC_ALL", "C" );
    vnstatProc << "vnstat" << "--dumpdb" << "-i" << mInterface->ifaceName();
    vnstatProc.execute();

    parseOutput( vnstatProc.readAllStandardOutput() );
    getBtime();
}
Exemplo n.º 11
0
/**
 * @brief check if GnuPG returns an error for this arguments
 * @param executable the GnuPG executable to call
 * @param arguments the arguments to pass to executable
 *
 * The arguments will be used together with "--version", so they should not
 * be any commands.
 */
static bool checkGnupgArguments(const QString &executable, const QStringList &arguments)
{
	KProcess gpg;

	// We ignore the output anyway, just make sure it doesn't clutter the output of
	// the parent process. Simplify the handling by putting all trash in one can.
	gpg.setOutputChannelMode(KProcess::MergedChannels);

	QStringList allArguments = arguments;
	allArguments << QLatin1String("--version");
	gpg.setProgram(executable, allArguments);

	return (gpg.execute() == 0);
}
Exemplo n.º 12
0
void KMimeTypeTest::cleanupTestCase()
{
    // If I want the konqueror unit tests to work, then I better not have a non-working part
    // as the preferred part for text/plain...
    const QString fakePart = KStandardDirs::locateLocal("services", "faketextpart.desktop");
    QFile::remove(fakePart);
    const QString fakePlugin = KStandardDirs::locateLocal("services", "faketextplugin.desktop");
    QFile::remove(fakePlugin);
    //QProcess::execute( KGlobal::dirs()->findExe(KBUILDSYCOCA_EXENAME) );
    KProcess proc;
    proc << KStandardDirs::findExe(KBUILDSYCOCA_EXENAME);
    proc.setOutputChannelMode(KProcess::MergedChannels); // silence kbuildsycoca output
    proc.execute();
}
Exemplo n.º 13
0
bool LldbDebugger::checkVersion()
{
    KProcess process;
    process.setProgram(debuggerBinary_, {"--versionLong"});
    process.setOutputChannelMode(KProcess::MergedChannels);
    process.start();
    process.waitForFinished(5000);
    auto output = QString::fromLatin1(process.readAll());
    qCDebug(DEBUGGERLLDB) << output;

    QRegularExpression rx("^Version: (\\d+).(\\d+).(\\d+).(\\d+)$", QRegularExpression::MultilineOption);
    auto match = rx.match(output);
    int version[] = {0, 0, 0, 0};
    if (match.hasMatch()) {
        for (int i = 0; i != 4; ++i) {
            version[i] = match.captured(i+1).toInt();
        }
    }

    // minimal version is 1.0.0.9
    bool ok = true;
    const int min_ver[] = {1, 0, 0, 9};
    for (int i = 0; i < 4; ++i) {
        if (version[i] < min_ver[i]) {
            ok = false;
            break;
        } else if (version[i] > min_ver[i]) {
            ok = true;
            break;
        }
    }

    if (!ok) {
        if (!qobject_cast<QGuiApplication*>(qApp))  {
            //for unittest
            qFatal("You need a graphical application.");
        }

        KMessageBox::error(
            qApp->activeWindow(),
            i18n("<b>You need lldb-mi 1.0.0.9 or higher.</b><br />"
            "You are using: %1", output),
            i18n("LLDB Error"));
    }

    return ok;
}
Exemplo n.º 14
0
QVector<rpp::pp_macro*> computeGccStandardMacros(bool withStdCpp0x = true)
{
    QVector<rpp::pp_macro*> ret;
    //Get standard macros from gcc
    KProcess proc;
    proc.setOutputChannelMode(KProcess::MergedChannels);

    // The output of the following gcc commands is several line in the format:
    // "#define MACRO [definition]", where definition may or may not be present.
    // Parsing each line sequentially, we can easily build the macro set.
    proc << "gcc";
    if (withStdCpp0x) {
        // see also: https://bugs.kde.org/show_bug.cgi?id=298252
        proc << "-std=c++0x";
    }
    proc << "-xc++" << "-E" << "-dM" <<NULL_DEVICE;

    if (proc.execute(5000) == 0) {
        QString line;
        while (proc.canReadLine()) {
            QByteArray buff = proc.readLine();
            if (!buff.isEmpty()) {
                line = buff;
                if (line.startsWith("#define ")) {
                    line = line.right(line.length() - 8).trimmed();
                    int pos = line.indexOf(' ');
                    
                    ret.append(new rpp::pp_macro);
                    
                    rpp::pp_macro& macro(*ret.back());
                    if (pos != -1) {
                        macro.name = IndexedString( line.left(pos) );
                        macro.setDefinitionText( line.right(line.length() - pos - 1).toUtf8() );
                    } else {
                        macro.name = IndexedString( line );
                    }
                }
            }
        }
    } else if (withStdCpp0x) {
        // fallback to macro computation without -std=c++0x arg for old gcc versions
        return computeGccStandardMacros(false);
    } else {
        kDebug(9007) <<"Unable to read standard c++ macro definitions from gcc:" <<QString(proc.readAll()) ;
    }
    return ret;
}
Exemplo n.º 15
0
static void recursor(char **argv)
{
    if (argv[1]) {
        KProcess p;
        p.setShellCommand("echo " EOUT "; echo " EERR " >&2");
        p.setOutputChannelMode((KProcess::OutputChannelMode)atoi(argv[1]));
        fputs(POUT, stdout);
        fflush(stdout);
        p.execute();
        fputs(ROUT, stdout);
        fputs(p.readAllStandardOutput(), stdout);
        fputs(RERR, stdout);
        fputs(p.readAllStandardError(), stdout);
        exit(0);
    }
    gargv = argv;
}
Exemplo n.º 16
0
//Copied from CMakeManager
QString executeProcess(const QString& execName, const QStringList& args=QStringList())
{
    KProcess p;
    p.setOutputChannelMode(KProcess::MergedChannels);
    p.setProgram(execName, args);
    p.start();

    if(!p.waitForFinished())
    {
        qCDebug(CMAKE) << "failed to execute:" << execName;
    }

    QByteArray b = p.readAllStandardOutput();
    QString t;
    t.prepend(b.trimmed());

    return t;
}
void SystemInformation::tryToSetBugzillaPlatformFromExternalInfo()
{
    //Run lsb_release async
    QString lsb_release = QStandardPaths::findExecutable(QLatin1String("lsb_release"));
    if ( !lsb_release.isEmpty() ) {
        qDebug() << "found lsb_release";
        KProcess *process = new KProcess();
        process->setOutputChannelMode(KProcess::OnlyStdoutChannel);
        process->setEnv(QStringLiteral("LC_ALL"), QStringLiteral("C"));
        *process << lsb_release << QStringLiteral("-sd");
        connect(process, static_cast<void (KProcess::*)(int, QProcess::ExitStatus)>(&KProcess::finished), this, &SystemInformation::lsbReleaseFinished);
        process->start();
    } else {
        // when lsb_release is unavailable, turn to /etc/os-release
        const QString& osReleaseInfo = fetchOSReleaseInformation();
        const QString& platform = guessBugzillaPlatform(osReleaseInfo);
        setBugzillaPlatform(platform);
    }
}
Exemplo n.º 18
0
ActionReply Helper::executeCommand(const QStringList &command)
{
    KProcess process;
    process.setProgram(command);
    process.setOutputChannelMode(KProcess::MergedChannels);

    qDebug() << "Executing" << command.join(" ");
    int exitCode = process.execute();

    ActionReply reply;
    if (exitCode != 0) {
        reply = ActionReply::HelperErrorReply();
        //TO BE FIXED
        reply.setErrorCode(ActionReply::Error::InvalidActionError);
    }
    reply.addData("command", command);
    reply.addData("output", process.readAll());
    return reply;
}
Exemplo n.º 19
0
void SystemInformation::tryToSetBugzillaPlatformFromExternalInfo()
{
    //Run lsb_release async
    QString lsb_release = KStandardDirs::findExe(QLatin1String("lsb_release"));
    if ( !lsb_release.isEmpty() ) {
        kDebug() << "found lsb_release";
        KProcess *process = new KProcess();
        process->setOutputChannelMode(KProcess::OnlyStdoutChannel);
        process->setEnv("LC_ALL", "C");
        *process << lsb_release << "-sd";
        connect(process, SIGNAL(finished(int,QProcess::ExitStatus)), SLOT(lsbReleaseFinished()));
        process->start();
    } else {
        // when lsb_release is unavailable, turn to /etc/os-release
        const QString& osReleaseInfo = fetchOSReleaseInformation();
        const QString& platform = guessBugzillaPlatform(osReleaseInfo);
        setBugzillaPlatform(platform);
    }
}
Exemplo n.º 20
0
QString CMakeBuildDirCreator::executeProcess(const QString& execName, const QStringList& args)
{
    kDebug(9042) << "Executing:" << execName << "::" << args /*<< "into" << *m_vars*/;
    
    KProcess p;
    p.setOutputChannelMode(KProcess::MergedChannels);
    p.setProgram(execName, args);
    p.start();
    
    if(!p.waitForFinished())
    {
        kDebug(9042) << "failed to execute:" << execName;
    }
    
    QByteArray b = p.readAllStandardOutput();
    QString t;
    t.prepend(b.trimmed());
    kDebug(9042) << "executed" << execName << "<" << t;
    
    return t;
}
void QGpgMECryptoConfigComponent::runGpgConf()
{
  const QString gpgconf = QGpgMECryptoConfig::gpgConfPath();
  if ( gpgconf.isEmpty() ) {
      kWarning(5150) << "Can't get path to gpgconf executable...";
      return;
  }

  // Run gpgconf --list-options <component>, and create all groups and entries for that component
  KProcess proc;
  proc << gpgconf;
  proc << "--list-options";
  proc << mName;

  //kDebug(5150) <<"Running gpgconf --list-options" << mName;

  connect( &proc, SIGNAL(readyReadStandardOutput()),
           this, SLOT(slotCollectStdOut()) );
  mCurrentGroup = 0;

  // run the process:
  int rc = 0;
  proc.setOutputChannelMode( KProcess::OnlyStdoutChannel );
  proc.start();
  if ( !proc.waitForFinished() )
    rc = -2;
  else if ( proc.exitStatus() == QProcess::NormalExit )
    rc = proc.exitCode();
  else
    rc = -1;

  if( rc != 0 ) // can happen when using the wrong version of gpg...
    kWarning(5150) <<"Running 'gpgconf --list-options" << mName <<"' failed." << strerror( rc ) <<", but try that command to see the real output";
  else {
    if ( mCurrentGroup && !mCurrentGroup->mEntriesNaturalOrder.empty() ) { // only add non-empty groups
      mGroupsByName.insert( mCurrentGroupName, mCurrentGroup );
      mGroupsNaturalOrder.push_back( std::make_pair( mCurrentGroupName, mCurrentGroup ) );
    }
  }
}
Exemplo n.º 22
0
QMap<QString, QString> MANProtocol::buildIndexMap(const QString &section)
{
    QMap<QString, QString> i;
    QStringList man_dirs = manDirectories();
    // Supplementary places for whatis databases
    man_dirs += m_mandbpath;
    if (!man_dirs.contains("/var/cache/man"))
        man_dirs << "/var/cache/man";
    if (!man_dirs.contains("/var/catman"))
        man_dirs << "/var/catman";

    QStringList names;
    names << "whatis.db" << "whatis";
    QString mark = "\\s+\\(" + section + "[a-z]*\\)\\s+-\\s+";

    for ( QStringList::ConstIterator it_dir = man_dirs.constBegin();
          it_dir != man_dirs.constEnd();
          ++it_dir )
    {
        if ( QFile::exists( *it_dir ) ) {
    	    QStringList::ConstIterator it_name;
            for ( it_name = names.constBegin();
	          it_name != names.constEnd();
	          it_name++ )
            {
	        if (addWhatIs(i, (*it_dir) + '/' + (*it_name), mark))
		    break;
	    }
            if ( it_name == names.constEnd() ) {
                KProcess proc;
                proc << "whatis" << "-M" << (*it_dir) << "-w" << "*";
                proc.setOutputChannelMode( KProcess::OnlyStdoutChannel );
                proc.execute();
                QTextStream t( proc.readAllStandardOutput(), QIODevice::ReadOnly );
                parseWhatIs( i, t, mark );
            }
        }
    }
    return i;
}
QVector<rpp::pp_macro*> computeGccStandardMacros()
{
    QVector<rpp::pp_macro*> ret;
    //Get standard macros from gcc
    KProcess proc;
    proc.setOutputChannelMode(KProcess::MergedChannels);
    proc.setTextModeEnabled(true);

    // The output of the following gcc commands is several line in the format:
    // "#define MACRO [definition]", where definition may or may not be present.
    // Parsing each line sequentially, we can easily build the macro set.
    proc <<"gcc" <<"-xc++" <<"-E" <<"-dM" <<"/dev/null";

    if (proc.execute(5000) == 0) {
        QString line;
        while (proc.canReadLine()) {
            QByteArray buff = proc.readLine();
            if (!buff.isEmpty()) {
                line = buff;
                if (line.startsWith("#define ")) {
                    line = line.right(line.length() - 8).trimmed();
                    int pos = line.indexOf(' ');
                    
                    ret.append(new rpp::pp_macro);
                    
                    rpp::pp_macro& macro(*ret.back());
                    if (pos != -1) {
                        macro.name = IndexedString( line.left(pos) );
                        macro.setDefinitionText( line.right(line.length() - pos - 1).toUtf8() );
                    } else {
                        macro.name = IndexedString( line );
                    }
                }
            }
        }
    } else {
        kDebug(9007) <<"Unable to read standard c++ macro definitions from gcc:" <<QString(proc.readAll()) ;
    }
    return ret;
}
void QGpgMECryptoConfig::runGpgConf( bool showErrors )
{
  // Run gpgconf --list-components to make the list of components
  KProcess process;

  process << gpgConfPath();
  process << "--list-components";


  connect( &process, SIGNAL(readyReadStandardOutput()),
           this, SLOT(slotCollectStdOut()) );

  // run the process:
  int rc = 0;
  process.setOutputChannelMode( KProcess::OnlyStdoutChannel );
  process.start();
  if ( !process.waitForFinished() )
    rc = -2;
  else if ( process.exitStatus() == QProcess::NormalExit )
    rc = process.exitCode();
  else
    rc = -1;

  // handle errors, if any (and if requested)
  if ( showErrors && rc != 0 ) {
    QString reason;
    if ( rc == -1 )
        reason = i18n( "program terminated unexpectedly" );
    else if ( rc == -2 )
        reason = i18n( "program not found or cannot be started" );
    else
      reason = QString::fromLocal8Bit( strerror(rc) ); // XXX errno as an exit code?
    QString wmsg = i18n("<qt>Failed to execute gpgconf:<p>%1</p></qt>", reason);
    kWarning(5150) << wmsg; // to see it from test_cryptoconfig.cpp
    KMessageBox::error(0, wmsg);
  }
  mParsed = true;
}
Exemplo n.º 25
0
void LocalPatchSource::update()
{
    if( !m_command.isEmpty() ) {
        QTemporaryFile temp(QDir::tempPath() + QLatin1String("/patchreview_XXXXXX.diff"));
        if( temp.open() ) {
            temp.setAutoRemove( false );
            QString filename = temp.fileName();
            qCDebug(PLUGIN_PATCHREVIEW) << "temp file: " << filename;
            temp.close();
            KProcess proc;
            proc.setWorkingDirectory( m_baseDir.toLocalFile() );
            proc.setOutputChannelMode( KProcess::OnlyStdoutChannel );
            proc.setStandardOutputFile( filename );
            ///Try to apply, if it works, the patch is not applied
            proc << KShell::splitArgs( m_command );

            qCDebug(PLUGIN_PATCHREVIEW) << "calling " << m_command;

            if ( proc.execute() ) {
                qWarning() << "returned with bad exit code";
                return;
            }
            if ( !m_filename.isEmpty() ) {
                QFile::remove( m_filename.toLocalFile() );
            }
            m_filename = QUrl::fromLocalFile( filename );
            qCDebug(PLUGIN_PATCHREVIEW) << "success, diff: " << m_filename;
        }else{
            qWarning() << "PROBLEM";
        }
    }
    if (m_widget) {
        m_widget->updatePatchFromEdit();
    }
    emit patchChanged();
}
Exemplo n.º 26
0
bool K3b::CdrdaoProgram::scanFeatures( ExternalBin& bin ) const
{
    // probe features
    KProcess fp;
    fp.setOutputChannelMode( KProcess::MergedChannels );
    fp << bin.path() << "write" << "-h";

    if( fp.execute() >= 0 ) {
        QByteArray out = fp.readAll();
        if( out.contains( "--overburn" ) )
            bin.addFeature( "overburn" );
        if( out.contains( "--multi" ) )
            bin.addFeature( "multisession" );

        if( out.contains( "--buffer-under-run-protection" ) )
            bin.addFeature( "disable-burnproof" );

        // SuSE 9.0 ships with a patched cdrdao 1.1.7 which contains an updated libschily
        // Gentoo ships with a patched cdrdao 1.1.7 which contains scglib support
        if( bin.version() > K3b::Version( 1, 1, 7 ) ||
            bin.version() == K3b::Version( 1, 1, 7, "-gentoo" ) ||
            bin.version() == K3b::Version( 1, 1, 7, "-suse" ) ) {
            //    bin.addFeature( "plain-atapi" );
            bin.addFeature( "hacked-atapi" );
        }

        if( bin.version() >= K3b::Version( 1, 1, 8 ) )
            bin.addFeature( "plain-atapi" );

        return SimpleExternalProgram::scanFeatures( bin );
    }
    else {
        qDebug() << "could not start " << bin.path();
        return false;
    }
}
Exemplo n.º 27
0
QString CustomScriptPlugin::formatSourceWithStyle(SourceFormatterStyle style, const QString& text, const QUrl &url, const QMimeType& /*mime*/, const QString& leftContext, const QString& rightContext)
{
	KProcess proc;
	QTextStream ios(&proc);

	std::unique_ptr<QTemporaryFile> tmpFile;

	if (style.content().isEmpty())
	{
		style = predefinedStyle(style.name());
		if (style.content().isEmpty())
		{
			qWarning() << "Empty contents for style" << style.name() << "for indent plugin";
			return text;
		}
	}

	QString useText = text;
	useText = leftContext + useText + rightContext;

	QMap<QString, QString> projectVariables;
	foreach(IProject* project, ICore::self()->projectController()->projects())
		projectVariables[project->name()] = project->folder().toLocalFile();

	QString command = style.content();

	// Replace ${Project} with the project path
	command = replaceVariables( command, projectVariables );
	command.replace("$FILE", url.toLocalFile());

	if(command.contains("$TMPFILE"))
	{
		tmpFile.reset(new QTemporaryFile(QDir::tempPath() + "/code"));
		tmpFile->setAutoRemove(false);
		if(tmpFile->open())
		{
			qCDebug(CUSTOMSCRIPT) << "using temporary file" << tmpFile->fileName();
			command.replace("$TMPFILE", tmpFile->fileName());
			QByteArray useTextArray = useText.toLocal8Bit();
			if( tmpFile->write(useTextArray) != useTextArray.size() )
			{
				qWarning() << "failed to write text to temporary file";
				return text;
			}

		}else{
			qWarning() << "Failed to create a temporary file";
			return text;
		}
		tmpFile->close();
	}

	qCDebug(CUSTOMSCRIPT) << "using shell command for indentation: " << command;
	proc.setShellCommand(command);
	proc.setOutputChannelMode(KProcess::OnlyStdoutChannel);

	proc.start();
	if(!proc.waitForStarted()) {
		qCDebug(CUSTOMSCRIPT) << "Unable to start indent" << endl;
		return text;
	}

	if(!tmpFile.get())
		proc.write(useText.toLocal8Bit());

	proc.closeWriteChannel();
	if(!proc.waitForFinished()) {
		qCDebug(CUSTOMSCRIPT) << "Process doesn't finish" << endl;
		return text;
	}

	QString output;

	if(tmpFile.get())
	{
		QFile f(tmpFile->fileName());
		if( f.open(QIODevice::ReadOnly) )
		{
			output = QString::fromLocal8Bit(f.readAll());
		}else{
			qWarning() << "Failed opening the temporary file for reading";
			return text;
		}
	}else{
		output = ios.readAll();
	}
	if (output.isEmpty())
	{
		qWarning() << "indent returned empty text for style" << style.name() << style.content();
		return text;
	}

	int tabWidth = 4;
	if((!leftContext.isEmpty() || !rightContext.isEmpty()) && (text.contains('	') || output.contains('	')))
	{
		// If we have to do contex-matching with tabs, determine the correct tab-width so that the context
		// can be matched correctly
		Indentation indent = indentation(url);
		if(indent.indentationTabWidth > 0)
			tabWidth = indent.indentationTabWidth;
	}

    return KDevelop::extractFormattedTextFromContext(output, text, leftContext, rightContext, tabWidth);
}
Exemplo n.º 28
0
QStringList gccSetupStandardIncludePaths(bool withStdCpp0x)
{
    QStringList includePaths;
    
    KProcess proc;
    proc.setOutputChannelMode(KProcess::MergedChannels);

    // The following command will spit out a bnuch of information we don't care
    // about before spitting out the include paths.  The parts we care about
    // look like this:
    // #include "..." search starts here:
    // #include <...> search starts here:
    //  /usr/lib/gcc/i486-linux-gnu/4.1.2/../../../../include/c++/4.1.2
    //  /usr/lib/gcc/i486-linux-gnu/4.1.2/../../../../include/c++/4.1.2/i486-linux-gnu
    //  /usr/lib/gcc/i486-linux-gnu/4.1.2/../../../../include/c++/4.1.2/backward
    //  /usr/local/include
    //  /usr/lib/gcc/i486-linux-gnu/4.1.2/include
    //  /usr/include
    // End of search list.
    proc << "gcc";
    if (withStdCpp0x) {
        // see also: https://bugs.kde.org/show_bug.cgi?id=298252
        proc << "-std=c++0x";
    }
    proc << "-xc++" << "-E" << "-v" << NULL_DEVICE;

    // We'll use the following constants to know what we're currently parsing.
    const short parsingInitial = 0;
    const short parsedFirstSearch = 1;
    const short parsingIncludes = 2;
    const short parsingFinished = 3;
    short parsingMode = parsingInitial;

    if (proc.execute(5000) == 0) {
        QString line;
        while (proc.canReadLine() && parsingMode != parsingFinished) {
            QByteArray buff = proc.readLine();
            if (!buff.isEmpty()) {
                line = buff;
                switch (parsingMode) {
                case parsingInitial:
                    if (line.indexOf("#include \"...\"") != -1) {
                        parsingMode = parsedFirstSearch;
                    }
                    break;
                case parsedFirstSearch:
                    if (line.indexOf("#include <...>") != -1) {
                        parsingMode = parsingIncludes;
                        break;
                    }
                case parsingIncludes:
                    //if (!line.indexOf(QDir::separator()) == -1 && line != "." ) {
                    //Detect the include-paths by the first space that is prepended. Reason: The list may contain relative paths like "."
                    if (!line.startsWith(" ") ) {
                        // We've reached the end of the list.
                        parsingMode = parsingFinished;
                    } else {
                        line = line.trimmed();
                        // This is an include path, add it to the list.
                        includePaths << QDir::cleanPath(line);
                    }
                    break;
                }
            }
        }
    } else if (withStdCpp0x) {
        // fallback to include-path computation without -std=c++0x arg for old gcc versions
        return gccSetupStandardIncludePaths(false);
    } else {
        kDebug(9007) <<"Unable to read standard c++ macro definitions from gcc:" <<QString(proc.readAll()) ;
    }
    
    return includePaths;
}
Exemplo n.º 29
0
void ghostscript_interface::gs_generate_graphics_file(const PageNumber& page, const QString& filename, long magnification) {
#ifdef DEBUG_PSGS
  kDebug(kvs::dvi) << "ghostscript_interface::gs_generate_graphics_file( " << page << ", " << filename << " )";
#endif

  if (knownDevices.isEmpty()) {
    kError(kvs::dvi) << "No known devices found" << endl;
    return;
  }

  pageInfo *info = pageList.value(page);

  // Generate a PNG-file
  // Step 1: Write the PostScriptString to a File
  KTemporaryFile PSfile;
  PSfile.setAutoRemove(false);
  PSfile.setSuffix(".ps");
  PSfile.open();
  const QString PSfileName = PSfile.fileName();

  QTextStream os(&PSfile);
  os << "%!PS-Adobe-2.0\n"
     << "%%Creator: kdvi\n"
     << "%%Title: KDVI temporary PostScript\n"
     << "%%Pages: 1\n"
     << "%%PageOrder: Ascend\n"
        // HSize and VSize in 1/72 inch
     << "%%BoundingBox: 0 0 "
     << (qint32)(72*(pixel_page_w/resolution)) << ' '
     << (qint32)(72*(pixel_page_h/resolution)) << '\n'
     << "%%EndComments\n"
     << "%!\n"
     << psheader
     << "TeXDict begin "
        // HSize in (1/(65781.76*72))inch
     << (qint32)(72*65781*(pixel_page_w/resolution)) << ' '
        // VSize in (1/(65781.76*72))inch
     << (qint32)(72*65781*(pixel_page_h/resolution)) << ' '
        // Magnification
     << (qint32)(magnification)
        // dpi and vdpi
     << " 300 300"
        // Name
     << " (test.dvi)"
     << " @start end\n"
     << "TeXDict begin\n"
        // Start page
     << "1 0 bop 0 0 a \n";

  if (!PostScriptHeaderString->toLatin1().isNull())
    os << PostScriptHeaderString->toLatin1();

  if (info->background != Qt::white) {
    QString colorCommand = QString("gsave %1 %2 %3 setrgbcolor clippath fill grestore\n").
      arg(info->background.red()/255.0).
      arg(info->background.green()/255.0).
      arg(info->background.blue()/255.0);
    os << colorCommand.toLatin1();
  }

  if (!info->PostScriptString->isNull())
    os << *(info->PostScriptString);

  os << "end\n"
     << "showpage \n";

  PSfile.close();

  // Step 2: Call GS with the File
  QFile::remove(filename.toAscii());
  KProcess proc;
  proc.setOutputChannelMode(KProcess::SeparateChannels);
  QStringList argus;
  argus << "gs";
  argus << "-dSAFER" << "-dPARANOIDSAFER" << "-dDELAYSAFER" << "-dNOPAUSE" << "-dBATCH";
  argus << QString("-sDEVICE=%1").arg(*gsDevice);
  argus << QString("-sOutputFile=%1").arg(filename);
  argus << QString("-sExtraIncludePath=%1").arg(includePath);
  argus << QString("-g%1x%2").arg(pixel_page_w).arg(pixel_page_h); // page size in pixels
  argus << QString("-r%1").arg(resolution);                       // resolution in dpi
  argus << "-dTextAlphaBits=4 -dGraphicsAlphaBits=2"; // Antialiasing
  argus << "-c" << "<< /PermitFileReading [ ExtraIncludePath ] /PermitFileWriting [] /PermitFileControl [] >> setuserparams .locksafe";
  argus << "-f" << PSfileName;

#ifdef DEBUG_PSGS
  kDebug(kvs::dvi) << argus.join(" ");
#endif
 
  proc << argus;
  int res = proc.execute();
  
  if ( res ) {
    // Starting ghostscript did not work. 
    // TODO: Issue error message, switch PS support off.
    kError(kvs::dvi) << "ghostview could not be started" << endl;
  } 

  PSfile.remove();

 // Check if gs has indeed produced a file.
  if (QFile::exists(filename) == false) {
    kError(kvs::dvi) << "GS did not produce output." << endl;

    // No. Check is the reason is that the device is not compiled into
    // ghostscript. If so, try again with another device.
    QString GSoutput;
    proc.setReadChannel(QProcess::StandardOutput);
    while(proc.canReadLine()) {
      GSoutput = QString::fromLocal8Bit(proc.readLine());
      if (GSoutput.contains("Unknown device")) {
	kDebug(kvs::dvi) << QString("The version of ghostview installed on this computer does not support "
                                     "the '%1' ghostview device driver.").arg(*gsDevice) << endl;
	knownDevices.erase(gsDevice);
	gsDevice = knownDevices.begin();
	if (knownDevices.isEmpty())
	  // TODO: show a requestor of some sort.
#if 0
	  KMessageBox::detailedError(0, 
				     i18n("<qt>The version of Ghostview that is installed on this computer does not contain "
					  "any of the Ghostview device drivers that are known to Okular. PostScript "
					  "support has therefore been turned off in Okular.</qt>"), 
				     i18n("<qt><p>The Ghostview program, which Okular uses internally to display the "
					  "PostScript graphics that is included in this DVI file, is generally able to "
					  "write its output in a variety of formats. The sub-programs that Ghostview uses "
					  "for these tasks are called 'device drivers'; there is one device driver for "
					  "each format that Ghostview is able to write. Different versions of Ghostview "
					  "often have different sets of device drivers available. It seems that the "
					  "version of Ghostview that is installed on this computer does not contain "
					  "<strong>any</strong> of the device drivers that are known to Okular.</p>"
					  "<p>It seems unlikely that a regular installation of Ghostview would not contain "
					  "these drivers. This error may therefore point to a serious misconfiguration of "
					  "the Ghostview installation on your computer.</p>"
					  "<p>If you want to fix the problems with Ghostview, you can use the command "
					  "<strong>gs --help</strong> to display the list of device drivers contained in "
					  "Ghostview. Among others, Okular can use the 'png256', 'jpeg' and 'pnm' "
					  "drivers. Note that Okular needs to be restarted to re-enable PostScript support."
					  "</p></qt>"));
#else
	{}
#endif
	else {
	  kDebug(kvs::dvi) << QString("Okular will now try to use the '%1' device driver.").arg(*gsDevice);
	  gs_generate_graphics_file(page, filename, magnification);
	}
	return;
      }
Exemplo n.º 30
0
void CameraController::slotCheckRename(const QString& folder, const QString& file,
                                       const QString& destination, const QString& temp,
                                       const QString& script)
{
    // this is the direct continuation of executeCommand, case CameraCommand::cam_download
    bool skip      = false;
    bool cancel    = false;
    bool overwrite = d->overwriteAll;
    QString dest   = destination;

    // Check if dest file already exist, unless we overwrite anyway

    QFileInfo info(dest);

    if (!d->overwriteAll)
    {

        while (info.exists())
        {
            if (d->skipAll)
            {
                skip = true;
                break;
            }

            QPointer<KIO::RenameDialog> dlg = new KIO::RenameDialog(d->parent, i18nc("@title:window", "Rename File"),
                    QString(folder + QLatin1String("/") + file), dest,
                    KIO::RenameDialog_Mode(KIO::M_MULTI     |
                                           KIO::M_OVERWRITE |
                                           KIO::M_SKIP));

            int result = dlg->exec();
            dest       = dlg->newDestUrl().toLocalFile();
            info       = QFileInfo(dest);

            delete dlg;

            switch (result)
            {
            case KIO::R_CANCEL:
            {
                cancel = true;
                break;
            }

            case KIO::R_SKIP:
            {
                skip = true;
                break;
            }

            case KIO::R_AUTO_SKIP:
            {
                d->skipAll = true;
                skip       = true;
                break;
            }

            case KIO::R_OVERWRITE:
            {
                overwrite = true;
                break;
            }

            case KIO::R_OVERWRITE_ALL:
            {
                d->overwriteAll = true;
                overwrite       = true;
                break;
            }

            default:
                break;
            }

            if (cancel || skip || overwrite)
            {
                break;
            }
        }
    }

    if (cancel)
    {
        unlink(QFile::encodeName(temp));
        slotCancel();
        emit signalSkipped(folder, file);
        return;
    }
    else if (skip)
    {
        unlink(QFile::encodeName(temp));
        sendLogMsg(i18n("Skipped file <filename>%1</filename>", file), DHistoryView::WarningEntry, folder, file);
        emit signalSkipped(folder, file);
        return;
    }

    kDebug() << "Checking whether (" << temp << ") has a sidecar";

    // move the file to the destination file
    if (DMetadata::hasSidecar(temp))
    {
        kDebug() << "  Yes, renaming it to " << dest;
        if (KDE::rename(DMetadata::sidecarPath(temp), DMetadata::sidecarPath(dest)) != 0)
        {
            sendLogMsg(i18n("Failed to save sidecar file for <filename>%1</filename>", file), DHistoryView::ErrorEntry,  folder, file);
        }
    }

    if (KDE::rename(temp, dest) != 0)
    {
        kDebug() << "Renaming " << temp << " to " << dest << " failed";
        // rename failed. delete the temp file
        unlink(QFile::encodeName(temp));
        emit signalDownloaded(folder, file, CamItemInfo::DownloadFailed);
        sendLogMsg(i18n("Failed to download <filename>%1</filename>", file), DHistoryView::ErrorEntry,  folder, file);
    }
    else
    {
        kDebug() << "Rename done, emiting downloaded signals:" << file << " info.filename: " << info.fileName();
        // TODO why two signals??
        emit signalDownloaded(folder, file, CamItemInfo::DownloadedYes);
        emit signalDownloadComplete(folder, file, info.path(), info.fileName());

        // Run script
        if (!script.isEmpty())
        {
            kDebug() << "Got a script, processing: " << script;
            KProcess process;

            process.setOutputChannelMode(KProcess::SeparateChannels);
            QString s;

            if (script.indexOf('%') > -1)
            {
                QHash<QString, QString> map;
                map.insert("file", dest);
                map.insert("filename", info.fileName());
                map.insert("path", info.path());
                map.insert("orgfilename", file);
                map.insert("orgpath", folder);
                s = KMacroExpander::expandMacros(script, map);
            }
            else
            {
                s = script + " \"" + dest + "\"";
            }

            process.setShellCommand(s);
            kDebug() << "Running: " << s;
            int ret = process.execute();

            if (ret != 0)
            {
                sendLogMsg(i18n("Failed to run script for <filename>%1</filename>", file), DHistoryView::ErrorEntry,  folder, file);
            }

            kDebug() << "stdout" << process.readAllStandardOutput();
            kDebug() << "stderr" << process.readAllStandardError();
        }
    }
}