コード例 #1
0
ファイル: encoderassistant.cpp プロジェクト: KDE/audex
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 "";

}
コード例 #2
0
ファイル: common.cpp プロジェクト: KDE/kcm-grub2
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('"')) {
コード例 #3
0
void NotifyByExecute::notify( int id, KNotifyConfig * config )
{
	QString command=config->readEntry( "Execute" );
	
	kDebug() << command;
	
	if (!command.isEmpty()) {
// 	kDebug() << "executing command '" << command << "'";
		QHash<QChar,QString> subst;
		subst.insert( 'e', config->eventid );
		subst.insert( 'a', config->appname );
		subst.insert( 's', config->text );
		subst.insert( 'w', QString::number( (quintptr)config->winId ));
		subst.insert( 'i', QString::number( id ));
		QString execLine = KMacroExpander::expandMacrosShellQuote( command, subst );
		if ( execLine.isEmpty() )
			execLine = command; // fallback
                KProcess proc;
		proc.setShellCommand(execLine.trimmed());
		if(!proc.startDetached())
			kDebug()<<"KNotify: Could not start process!";
	}
	
	finish( id );
}
コード例 #4
0
ファイル: kprocesstest.cpp プロジェクト: fluxer/kdelibs
void KProcessTest::test_setShellCommand()
{
// Condition copied from kprocess.cpp
#if !defined(__linux__) && !defined(__FreeBSD__) && !defined(__NetBSD__) && !defined(__OpenBSD__) && !defined(__DragonFly__) && !defined(__GNU__)
    QSKIP("This test needs a free UNIX system", SkipSingle);
#else
    KProcess p;

    p.setShellCommand("cat");
    QCOMPARE(p.program().count(), 1);
    QCOMPARE(p.program().at(0), KStandardDirs::findExe("cat"));
    QVERIFY(p.program().at(0).endsWith("/bin/cat"));
    p.setShellCommand("true || false");
    QCOMPARE(p.program(), QStringList() << "/bin/sh" << "-c" << "true || false");
#endif
}
コード例 #5
0
void CfgWm::loadWMs( const QString& current )
{
    WmData kwin;
    kwin.internalName = KWIN_BIN;
    kwin.exec = KWIN_BIN;
    kwin.configureCommand = "";
    kwin.restartArgument = "--replace";
    kwin.parentArgument = "";
    wms[ "KWin" ] = kwin;
    oldwm = KWIN_BIN;
    kwinRB->setChecked( true );
    wmCombo->setEnabled( false );

    QStringList list = KGlobal::dirs()->findAllResources( "windowmanagers", QString(), KStandardDirs::NoDuplicates );
    QRegExp reg( ".*/([^/\\.]*)\\.[^/\\.]*" );
    foreach( const QString& wmfile, list )
    {
        KDesktopFile file( wmfile );
        if( file.noDisplay())
            continue;
        if( !file.tryExec())
            continue;
        QString testexec = file.desktopGroup().readEntry( "X-KDE-WindowManagerTestExec" );
        if( !testexec.isEmpty())
        {
            KProcess proc;
            proc.setShellCommand( testexec );
            if( proc.execute() != 0 )
                continue;
        }
        QString name = file.readName();
        if( name.isEmpty())
            continue;
        if( !reg.exactMatch( wmfile ))
            continue;
        QString wm = reg.cap( 1 );
        if( wms.contains( name ))
            continue;
        WmData data;
        data.internalName = wm;
        data.exec = file.desktopGroup().readEntry( "Exec" );
        if( data.exec.isEmpty())
            continue;
        data.configureCommand = file.desktopGroup().readEntry( "X-KDE-WindowManagerConfigure" );
        data.restartArgument = file.desktopGroup().readEntry( "X-KDE-WindowManagerRestartArgument" );
        data.parentArgument = file.desktopGroup().readEntry( "X-KDE-WindowManagerConfigureParentArgument" );
        wms[ name ] = data;
        wmCombo->addItem( name );
        if( wms[ name ].internalName == current ) // make it selected
        {
            wmCombo->setCurrentIndex( wmCombo->count() - 1 );
            oldwm = wm;
            differentRB->setChecked( true );
            wmCombo->setEnabled( true );
        }
    }
コード例 #6
0
ファイル: diffdialog.cpp プロジェクト: KDE/cervisia
void DiffDialog::callExternalDiff(const QString& extdiff, OrgKdeCervisia5CvsserviceCvsserviceInterface* service,
                                  const QString& fileName, const QString &revA,
                                  const QString &revB)
{
    QString extcmdline = extdiff;
    extcmdline += ' ';

    // create suffix for temporary file (used QFileInfo to remove path from file name)
    const QString suffix = '-' + QFileInfo(fileName).fileName();

    QDBusReply<QDBusObjectPath> job;
    if (!revA.isEmpty() && !revB.isEmpty())
    {
        // We're comparing two revisions
        QString revAFilename = tempFileName(suffix+QString("-")+revA);
        QString revBFilename = tempFileName(suffix+QString("-")+revB);

        // download the files for revision A and B
        job = service->downloadRevision(fileName, revA, revAFilename,
                                                revB, revBFilename);
        if( !job.isValid() )
            return;

        extcmdline += KShell::quoteArg(revAFilename);
        extcmdline += ' ';
        extcmdline += KShell::quoteArg(revBFilename);
    }
    else
    {
        // We're comparing to a file, and perhaps one revision
        QString revAFilename = tempFileName(suffix+QString("-")+revA);
        job = service->downloadRevision(fileName, revA, revAFilename);
        if( !job.isValid() )
            return;

        extcmdline += KShell::quoteArg(revAFilename);
        extcmdline += ' ';
        extcmdline += KShell::quoteArg(QFileInfo(fileName).absoluteFilePath());
    }

    ProgressDialog dlg(this, "Diff", service->service(),job, "diff");
    if( dlg.execute() )
    {
        // call external diff application
        KProcess proc;
        proc.setShellCommand(extcmdline);
        proc.startDetached();
    }
}
コード例 #7
0
ファイル: kprocesstest.cpp プロジェクト: fluxer/kdelibs
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;
}
コード例 #8
0
static void slipInFilter(KProcess & proc, KTextEditor::View & view, QString command)
{
  QString inputText;

  if (view.selection()) {
    inputText = view.selectionText();
  }

  proc.clearProgram ();
  proc.setShellCommand(command);

  proc.start();
  QByteArray encoded = inputText.toLocal8Bit();
  proc.write(encoded);
  proc.closeWriteChannel();
  //  TODO: Put up a modal dialog to defend the text from further
  //  keystrokes while the command is out. With a cancel button...
}
コード例 #9
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);
}
コード例 #10
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();
        }
    }
}
コード例 #11
0
void QGpgMECryptoConfigComponent::sync( bool runtime )
{
  KTemporaryFile tmpFile;
  tmpFile.open();

  QList<QGpgMECryptoConfigEntry *> dirtyEntries;

  // Collect all dirty entries
  const QList<QString> keylist = mGroupsByName.uniqueKeys();
  Q_FOREACH (const QString & key, keylist) {
    const QHash<QString,QGpgMECryptoConfigEntry*> entry = mGroupsByName[key]->mEntriesByName;
    const QList<QString> keylistentry = entry.uniqueKeys();
    Q_FOREACH (const QString & keyentry, keylistentry) {
      if(entry[keyentry]->isDirty())
      {
       // OK, we can set it.currentKey() to it.current()->outputString()
        QString line = keyentry;
        if ( entry[keyentry]->isSet() ) { // set option
          line += ":0:";
          line += entry[keyentry]->outputString();
        } else {                       // unset option
          line += ":16:";
        }
#ifdef Q_OS_WIN
        line += '\r';
#endif
        line += '\n';
        const QByteArray line8bit = line.toUtf8(); // encode with utf8, and K3ProcIO uses utf8 when reading.
        tmpFile.write( line8bit );
        dirtyEntries.append( entry[keyentry] );

      }
    }
  }

  tmpFile.flush();
  if ( dirtyEntries.isEmpty() )
    return;

  // Call gpgconf --change-options <component>
  const QString gpgconf = QGpgMECryptoConfig::gpgConfPath();
  QString commandLine = gpgconf.isEmpty()
      ? QString::fromLatin1( "gpgconf" )
      : KShell::quoteArg( gpgconf ) ;
  if ( runtime )
    commandLine += " --runtime";
  commandLine += " --change-options ";
  commandLine += KShell::quoteArg( mName );
  commandLine += " < ";
  commandLine += KShell::quoteArg( tmpFile.fileName() );

  //kDebug(5150) << commandLine;
  //system( QCString( "cat " ) + tmpFile.name().toLatin1() ); // DEBUG

  KProcess proc;
  proc.setShellCommand( commandLine );

  // run the process:
  int rc = proc.execute();

  if ( rc == -2 )
  {
    QString wmsg = i18n( "Could not start gpgconf.\nCheck that gpgconf is in the PATH and that it can be started." );
    kWarning(5150) << wmsg;
    KMessageBox::error(0, wmsg);
  }
  else if( rc != 0 ) // Happens due to bugs in gpgconf (e.g. issues 104/115)
  {
    QString wmsg = i18n( "Error from gpgconf while saving configuration: %1", QString::fromLocal8Bit( strerror( rc ) ) );
    kWarning(5150) <<":" << strerror( rc );
    KMessageBox::error(0, wmsg);
  }
  else
  {
    QList<QGpgMECryptoConfigEntry *>::const_iterator it = dirtyEntries.constBegin();
    for( ; it != dirtyEntries.constEnd(); ++it ) {
      (*it)->setDirty( false );
    }
  }
}