Example #1
0
void MainWindow::testPass()
{

  QString program = "sudo";
  QStringList arguments;
  arguments << "-S";
  arguments << "-k";
  arguments << "true";

  QProcess *tP = new QProcess(this);
  tP->setProcessChannelMode(QProcess::MergedChannels);
  tP->start(program, arguments);
  tP->write(passwordLineEdit->text().toLatin1() + "\n");
  tP->write(passwordLineEdit->text().toLatin1() + "\n");
  tP->write(passwordLineEdit->text().toLatin1() + "\n");
  while(tP->state() == QProcess::Starting || tP->state() == QProcess::Running ) {
     tP->waitForFinished(500);
     QCoreApplication::processEvents();
  }
  if ( tP->exitCode() != 0 )
  {
     QString tmp;
     tmp.setNum(tries-1);
     labelBadPW->setText(tr("Invalid Password! Tries Left: %1").arg(tmp) );
     tries--;
     if ( tries == 0 )
       exit(1);
     passwordLineEdit->setText("");
  } else {
     startSudo();
  }
}
Example #2
0
int main(int argc, char** argv) {
  (void) argc;
  (void) argv;
  
  QProcess client;
  client.start("./client.elf", QStringList());
  myAssert(client.waitForStarted(), "Line " S__LINE__ ": The client could not be initialized properly.");
  char buffer[80];
  char buffer2[80];
  
  for(int i = 1 ; i <= 8 ; i++) {
    sprintf(buffer, "T %d 0\n", (i * 10) + 1);
    client.write(buffer);
    
    client.waitForReadyRead();
    for(int id = 1 ; id <= 8 ; id++) {
      if(i % id == 0) {
        sprintf(buffer, "D TESTER value %d", id);
        sprintf(buffer2, "Line " S__LINE__ ": Unexpected at i=%d and id=%d", i, id);
        myAssert(checkMsg(client, buffer), buffer2);
      }
    }
    
    myAssert(checkMsg(client, "T"), "Line " S__LINE__ ": The client thread did not send \"T\" as expected.");
  }
  
  client.write("S\n");
  myAssert(checkMsg(client, "S"), "Line " S__LINE__ ": The client thread did not send \"S\" as expected.");
  
  client.closeWriteChannel();
  myAssert(client.waitForFinished(), "Line " S__LINE__ ": The client did not close properly.");
  
  std::cout << "OK" << std::endl;
  return 0;
}
Example #3
0
QVector<TypeInfo> Process::getCompletions(const QString &filename, const QByteArray& ustart, const QByteArray& uend)
{
    QStringList args;
    args << "-f=csv" << "autocomplete" << filename << QString("c") + QString::number(ustart.length());

    QProcess p;
    p.start("gocode", args);

    if(!p.waitForStarted(TIMEOUT))
        return QVector<TypeInfo>();

    p.write(ustart);
    p.write(uend);
    p.closeWriteChannel();

    if(!p.waitForFinished(TIMEOUT))
        return QVector<TypeInfo>();

    QStringList lines = QString(p.readAllStandardOutput()).split("\n");
    QVector<TypeInfo> out;
    out.reserve(lines.size());

    TypeInfo info;

    for(int i = 0, e = lines.size(); i < e; ++i)
        if(info.parseString(lines[i]))
            out.push_back(info);

    return out;
}
Example #4
0
bool Pack::ExecuteCmd(QString exe, QStringList argument, QProcess &pprocess, QString workPath)
{
	QString enterPath = QStringLiteral("cd ") + "\"" + workPath + "\"" + QStringLiteral("\n");
	QString arg;
	arg.append(exe);
	for (QStringList::Iterator ite = argument.begin(); ite != argument.end(); ite++)
	{
		arg.append(" ");
		arg.append(*ite);		
	}
	arg.append("\n");
	pprocess.start("cmd");
	pprocess.waitForStarted();
	QTextCodec *gbk = QTextCodec::codecForName("GBK");
	QByteArray byteEnterPath = gbk->fromUnicode(enterPath.constData(), enterPath.length());
	QByteArray byteCommand = gbk->fromUnicode(arg.constData(), arg.length());
	char *charEnterPath = byteEnterPath.data();
	char *charCommand = byteCommand.data();
	pprocess.write(byteEnterPath);
	pprocess.write(charCommand);
	pprocess.closeWriteChannel();
	if (!pprocess.waitForFinished(1000 * 60 * 20)){
		return false;
	}
	return true;
	//mpprocess->setWorkingDirectory(workPath);
	//mpprocess->start(exe,argument);
}
Example #5
0
bool zip()
{
//! [0]
    QProcess gzip;
    gzip.start("gzip", QStringList() << "-c");
    if (!gzip.waitForStarted())
        return false;

    gzip.write("Qt rocks!");
    gzip.closeWriteChannel();

    if (!gzip.waitForFinished())
        return false;

    QByteArray result = gzip.readAll();
//! [0]

    gzip.start("gzip", QStringList() << "-d" << "-c");
    gzip.write(result);
    gzip.closeWriteChannel();

    if (!gzip.waitForFinished())
        return false;

    qDebug("Result: %s", gzip.readAll().data());
    return true;
}
Example #6
0
bool SystemUtils::setUserPassword(const QString &password, const QString &user)
{
	QStringList args;
	if(password.isEmpty()) args << "--delete";
	const QString username = user.isEmpty() ? currentUser() : user;
	args << username;
	QProcess process;
	process.start(PASSWD_PROCESS, args);
	if(!process.waitForStarted(1000)) {
		process.kill();
		return false;
	}
	
	process.write(password.toUtf8());
	process.putChar(NEWLINE_CHAR);
	
	// Confirmation
	process.write(password.toUtf8());
	process.putChar(NEWLINE_CHAR);
	
	if(!process.waitForFinished(1000)) {
		process.kill();
		return false;
	}
	
	return process.exitCode() == 0;
}
Example #7
0
QString ConnectionTester::Private::scutilHelper(const QByteArray &command, const QString &searchKey) const
{
    QString result;

    QProcess sc;
    QTextStream stream(&sc);
    sc.start("scutil");
    sc.waitForStarted();
    //sc.write("show State:/Network/Global/IPv4\n");
    sc.write(command);
    sc.write("\n");
    sc.waitForReadyRead();

    QString line = stream.readLine();

    while (!line.isEmpty())
    {
        QStringList parts = line.split(':');

        if (parts.size() == 2)
        {
            if (parts.at(0).trimmed() == searchKey)
            {
                result = parts.at(1).trimmed();
            }
        }

        line = stream.readLine();
    }

    sc.write("exit\n");
    sc.waitForFinished();

    return result;
}
Example #8
0
/// set the tooltable and start interpreting input from stdin. called from interpret()
bool g2m::startInterp(QProcess &tc) {
    if (!chooseToolTable())
        return false;
    // run:  rs274 file.ngc
    tc.start( interp , QStringList(file) );
    tc.write("3\n"); // "read tool file" command to rs274
    tc.write(tooltable.toAscii());
    tc.write("\n"); // "enter"
    tc.write("1\n"); // "start interpreting" command to rs274
    return true;
}
Example #9
0
void tst_qdbusxml2cpp::process()
{
    QFETCH(QString, xmlSnippet);
    QFETCH(QRegularExpression, interfaceSearch);
    QFETCH(QRegularExpression, adaptorSearch);
    QVERIFY2(interfaceSearch.isValid(), qPrintable(interfaceSearch.errorString()));
    QVERIFY2(adaptorSearch.isValid(), qPrintable(adaptorSearch.errorString()));

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

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

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

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

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

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

    QByteArray fullOutput = process.readAll();
    QString output = stripHeader(QString::fromLatin1(fullOutput));
    QVERIFY2(!output.isEmpty(), fullOutput);
    if (outputMode == Interface)
        QVERIFY2(output.count(interfaceSearch) == 1, qPrintable(interfaceSearch.pattern() + "\nin\n" + output));
    else
        QVERIFY2(output.count(adaptorSearch) == 1, qPrintable(adaptorSearch.pattern() + "\nin\n" + output));
}
Example #10
0
TTSStatus TTSFestival::voice(QString text, QString wavfile, QString* errStr)
{
    qDebug() << "[Festival] Voicing " << text << "->" << wavfile;

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

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

    return NoError;
}
Example #11
0
// Slot of MainWindow
// For handle convert markdown to html
// Single receive from editor, when it text change
int MainWindow::convert()
{
    Ui_MainWindow *ui = this->ui;
    QProcess *myProcess = new QProcess();

    // Convert README.md to HTML
    QString program = "/home/ham/document/QT/MarkdownEditor/MarkdownEditor/mkd2html";
    QStringList arguments;

    // write editor content to README.md
    QString utf8_data = ui->editor->toPlainText();
    QByteArray byteArray=utf8_data.toLocal8Bit ();
    char *c=byteArray.data();

    // Setting args

    arguments << QStringList();
    // Exec
    myProcess->start(program, arguments);
    if (!myProcess->waitForStarted())
            return false;

    myProcess->write(c);
    myProcess->closeWriteChannel();

    if (!myProcess->waitForFinished())
            return false;
    QByteArray result = myProcess->readAll();

    qDebug() << result;
    ui->markdown_viewer->setHtml(result);


    return 0;
}
Example #12
0
bool Global::sendEMail(const QString subject, const QString to, const QString text, const QStringList attachments) {
    QStringList args;

    foreach (QString attachment, attachments)
        args << "-a" << attachment;

    args << "-s" << subject << to;

    QProcess process;
    process.start("mail", args);
    if (!process.waitForStarted())
        return false;

    QStringList lines = text.split("\n", QString::KeepEmptyParts);
    for (int i = 0; i < lines.size(); ++i) {
        process.write(QString(lines.at(i) + "\n").toUtf8());
    }

    process.closeWriteChannel();

    if (!process.waitForFinished())
        return false;
    if (process.exitCode() != 0)
        return false;

    return true;
}
Example #13
0
Gpg::Decrypted Gpg::decrypt(QVector<QString> const &pInput)
{
    QProcess process;
    process.start(QStringLiteral("gpg"), QStringList() << QStringLiteral("--decrypt"));
    process.waitForStarted(-1);

    if (process.state() != QProcess::Running)
    {
        qWarning() << "Failed to launch GPG!";
        return Decrypted();
    }

    for (QString const &line : pInput)
    {
        process.write((line + '\n').toLatin1());
    }
    process.closeWriteChannel();

    process.waitForFinished(-1);
    if (process.exitCode() != 0)
    {
        qWarning() << "GPG terminated with exit code" << process.exitCode();
        return Decrypted();
    }

    return Decrypted(process.exitCode() == 0, process.readAllStandardOutput(), process.readAllStandardError());
}
bool UiCodeModelSupport::runUic(const QString &ui) const
{
    QProcess process;
    const QString uic = uicCommand();
    process.setEnvironment(environment());

    if (debug)
        qDebug() << "UiCodeModelSupport::runUic " << uic << " on " << ui.size() << " bytes";
    process.start(uic, QStringList(), QIODevice::ReadWrite);
    if (!process.waitForStarted())
        return false;
    process.write(ui.toUtf8());
    process.closeWriteChannel();
    if (process.waitForFinished() && process.exitStatus() == QProcess::NormalExit && process.exitCode() == 0) {
        m_contents = process.readAllStandardOutput();
        m_cacheTime = QDateTime::currentDateTime();
        if (debug)
            qDebug() << "ok" << m_contents.size() << "bytes.";
        return true;
    } else {
        if (debug)
            qDebug() << "failed" << process.readAllStandardError();
        process.kill();
    }
    return false;
}
Example #15
0
qint64 QProcessProto::write(const char *data, qint64 maxSize)
{
  QProcess *item = qscriptvalue_cast<QProcess*>(thisObject());
  if (item)
    return item->write(data, maxSize);
  return 0;
}
Example #16
0
bool DriveFormatThread::partitionDrive()
{
    QByteArray partitionTable;

    if (_reformatBoot)
        partitionTable = "2048,129024,0E\n"; /* 63 MB FAT partition LBA */
//        partitionTable = "0,128,6\n"; /* 64 MB FAT partition */

    partitionTable += "131072,,L\n"; /* Linux partition with all remaining space */
    partitionTable += "0,0\n";
    partitionTable += "0,0\n";
    if (!_reformatBoot)
        partitionTable += "0,0\n";

    //QString cmd = QString("/sbin/sfdisk -H 32 -S 32 /dev/")+_dev;
    QString cmd = QString("/sbin/sfdisk -H 255 -S 63 -u S /dev/")+_dev;
    QProcess proc;
    proc.setProcessChannelMode(proc.MergedChannels);
    proc.start(cmd);
    proc.write(partitionTable);
    proc.closeWriteChannel();
    proc.waitForFinished(-1);
    //qDebug() << "partitioning" << cmd;
    //qDebug() << partitionTable;

    return proc.exitCode() == 0;
}
Example #17
0
QString CommandProcess::run()
{
	QProcess process;
	process.setReadChannel(QProcess::StandardOutput);
	process.start(m_Command, m_Arguments);
	bool success = process.waitForStarted();

	QString output, error;
	if (success)
	{
		if (!m_Input.isEmpty()) {
			process.write(m_Input.toStdString().c_str());
		}

		if (process.waitForFinished()) {
			output = process.readAllStandardOutput().trimmed();
			error = process.readAllStandardError().trimmed();
		}
	}

	int code = process.exitCode();
	if (!error.isEmpty() || !success || code != 0)
	{
		throw std::runtime_error(
			QString("Code: %1\nError: %2")
				.arg(process.exitCode())
				.arg(error.isEmpty() ? "Unknown" : error)
				.toStdString());
	}

	emit finished();

	return output;
}
bool TSendmailMailer::send()
{
    QMutexLocker locker(&sendMutex); // Global lock for load reduction of mail server
    if (sendmailCmd.isEmpty()) {
        return false;
    }

    QStringList args;
    QByteArray rawmail = mailMessage.toByteArray();
    const QList<QByteArray> recipients = mailMessage.recipients();

    for (auto &recipt : recipients) {
        args.clear();
        args << recipt;

        QProcess sendmail;
        sendmail.start(sendmailCmd, args);
        if (!sendmail.waitForStarted(5000)) {
            tSystemError("Sendmail error. CMD: %s", qPrintable(sendmailCmd));
            return false;
        }

        sendmail.write(rawmail);
        sendmail.write("\n.\n");
        sendmail.waitForFinished();
        tSystemDebug("Mail sent. Recipients: %s", recipt.data());
    }

    return true;
}
Example #19
0
DCDCompletion QcdAssist::sendRequestToDCD(QByteArray& filedata, uint pos)
{
	QProcess proc;
	proc.setProcessChannelMode(QProcess::MergedChannels);
	proc.start(QcdAssist::dcdClient(),
		QStringList()
			//<< QString(QLatin1String("-p%1")).arg(QcdAssist::dcdPort)
			<< QString(QLatin1String("-c%1")).arg(pos)
	);
	proc.write(filedata);
	proc.closeWriteChannel();
	if(!proc.waitForFinished(QcdAssist::waitForReadyReadTimeout))
	{
		//Core::MessageManager::write(QLatin1String("qcdassist error: unable to complete: client didn't finish in time"));
		proc.close();
	}
	else if(proc.exitCode() != 0)
	{
		//Core::MessageManager::write(QString(QLatin1String("qcdassist error: unable to complete: %1")).arg(proc.exitCode()));
		QByteArray arr = proc.readAll();
		//Core::MessageManager::write(QString::fromUtf8(arr.data(),arr.length()));
	}
	else
	{
		// everything Ok
		return processCompletion(proc.readAllStandardOutput());
	}

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

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

        dtkTrace() << "run graphviz dot" ;
        cmd.start(command, arglist, QProcess::Unbuffered | QProcess::ReadWrite);
        cmd.write(content);
        cmd.closeWriteChannel();
        cmd.waitForBytesWritten();
        qlonglong timeout = 3000;
        QString stdout_data;
        if (cmd.waitForFinished(timeout)) {
            QByteArray svg = cmd.readAllStandardOutput();
            this->load(svg);
        } else {
            dtkWarn() << "graphviz timeout !";
        }
    } else {
        d->graphviz_avail = false;
        dtkWarn() << "can't find 'dot' binary in PATH, graphviz probably not installed";
    }
}
Example #21
0
   bool unmount(QString devicePath, bool isDisk)
   {
       QString aScript ="diskutil";

       QStringList processArguments;
       QProcess p;
       if (isDisk)
           processArguments << "unmountDisk";
       else
           processArguments << "unmount";

       processArguments << devicePath;

       p.start(aScript, processArguments);

       p.write(aScript.toUtf8());

       p.closeWriteChannel();
       p.waitForReadyRead(-1);
       p.waitForFinished(-1);
       QByteArray stdoutArray = p.readAllStandardOutput();
       QByteArray stderrArray = p.readAllStandardError();
       int exitCode = p.exitCode();

       /* Non-0 exit code indicates failure */
       if (exitCode != 0)
       {
           utils::writeLog("Could not unmount " + devicePath + ". Messages are: stdErr: " + QString(stderrArray) + "\n stdOut: " + QString(stdoutArray));
           return false;
       }
       else
          return true;
   }
Example #22
0
File: main.cpp Project: avdbg/Saber
int main(int argc, char *argv[])
{
    if (getuid() != 0)
    {
        QString aScript("do shell script \"\\\"");
        aScript += argv[0];
        aScript += "\\\"\" with administrator privileges";

        QString osascript = "/usr/bin/osascript";
        QStringList processArguments;
        processArguments << "-l" << "AppleScript";

        QProcess p;
        p.start(osascript, processArguments);
        p.write(aScript.toUtf8());
        p.closeWriteChannel();
        p.waitForReadyRead(-1);
        return 0;
    }

    QApplication a(argc, argv);
    //IMPORTANT:非等宽字体会导致某些自绘文本控件的错位
    QApplication::setFont(QFontDatabase::systemFont(QFontDatabase::FixedFont));
    EventDispatcher::registerMetaType();
    QApplication::setStyle(new FlexStyle());

    MainWindow w;
    w.showMaximized();

    return a.exec();
}
Example #23
0
qint64 QProcessProto::write(const QByteArray &byteArray)
{
  QProcess *item = qscriptvalue_cast<QProcess*>(thisObject());
  if (item)
    return item->write(byteArray);
  return 0;
}
int main()
{
#ifndef QT_NO_PROCESS
    QProcess process;
    process.setProcessChannelMode(QProcess::ForwardedChannels);
    if (process.processChannelMode() != QProcess::ForwardedChannels)
        return -1;

    process.start("testProcessEcho/testProcessEcho");

    if (!process.waitForStarted(5000))
        return -1;

    if (process.write("forwarded\n") != 10)
        return -1;

    process.waitForReadyRead(250);
    if (process.bytesAvailable() != 0)
        return -1;

    process.closeWriteChannel();
    process.waitForFinished(5000);
#endif
    return 0;
}
Example #25
0
bool PatchTool::runPatch(const QByteArray &input, const QString &workingDirectory,
                         int strip, bool reverse)
{
    const QString patch = patchCommand();
    if (patch.isEmpty()) {
        MessageManager::write(QApplication::translate("Core::PatchTool", "There is no patch-command configured in the general \"Environment\" settings."));
        return false;
    }

    QProcess patchProcess;
    if (!workingDirectory.isEmpty())
        patchProcess.setWorkingDirectory(workingDirectory);
    QStringList args;
    // Add argument 'apply' when git is used as patch command since git 2.5/Windows
    // no longer ships patch.exe.
    if (patch.endsWith(QLatin1String("git"), Qt::CaseInsensitive)
        || patch.endsWith(QLatin1String("git.exe"), Qt::CaseInsensitive)) {
        args << QLatin1String("apply");
    }
    if (strip >= 0)
        args << (QLatin1String("-p") + QString::number(strip));
    if (reverse)
        args << QLatin1String("-R");
    MessageManager::write(QApplication::translate("Core::PatchTool", "Executing in %1: %2 %3").
                          arg(QDir::toNativeSeparators(workingDirectory),
                              QDir::toNativeSeparators(patch), args.join(QLatin1Char(' '))));
    patchProcess.start(patch, args);
    if (!patchProcess.waitForStarted()) {
        MessageManager::write(QApplication::translate("Core::PatchTool", "Unable to launch \"%1\": %2").arg(patch, patchProcess.errorString()));
        return false;
    }
    patchProcess.write(input);
    patchProcess.closeWriteChannel();
    QByteArray stdOut;
    QByteArray stdErr;
    if (!Utils::SynchronousProcess::readDataFromProcess(patchProcess, 30, &stdOut, &stdErr, true)) {
        Utils::SynchronousProcess::stopProcess(patchProcess);
        MessageManager::write(QApplication::translate("Core::PatchTool", "A timeout occurred running \"%1\"").arg(patch));
        return false;

    }
    if (!stdOut.isEmpty())
        MessageManager::write(QString::fromLocal8Bit(stdOut));
    if (!stdErr.isEmpty())
        MessageManager::write(QString::fromLocal8Bit(stdErr));

    if (patchProcess.exitStatus() != QProcess::NormalExit) {
        MessageManager::write(QApplication::translate("Core::PatchTool", "\"%1\" crashed.").arg(patch));
        return false;
    }
    if (patchProcess.exitCode() != 0) {
        MessageManager::write(QApplication::translate("Core::PatchTool", "\"%1\" failed (exit code %2).").arg(patch).arg(patchProcess.exitCode()));
        return false;
    }
    return true;
}
Example #26
0
void Action::writeInput()
{
    if (m_processes.empty())
        return;

    QProcess *p = m_processes.front();

    if (m_input.isEmpty())
        p->closeWriteChannel();
    else
        p->write(m_input);
}
Example #27
0
/*! Open a new backup (encrypted or unencrypted) and sets the location
 *
 * \return success, failed or what else
 */
Backup::Status Backup::open()
{
    QProcess process;
    QDir dir;

    switch (m_encryption) {
        case Backup::NotEncrypted:
            dir.setPath(m_origin);
            if (!dir.exists()) {
                m_errorString = tr("Directory does not exist or is not accessible.");
                return Backup::Failed;
            }
            m_location = m_origin;
            break;

        case Backup::EncFSEncrypted:
            m_location = findUsableMountPoint();
            dir.mkpath(m_location);

            // start encfs as daemon, reading password from stdin
            process.start("encfs", QStringList() << "--stdinpass" <<  "--standard" << m_origin << m_location);
            if (process.waitForStarted() == false) {
                m_errorString = process.errorString();
                m_rc = process.exitCode();
                dir.rmdir(m_location);
                return Backup::CouldNotStarted;
            }

            process.write(m_password.toUtf8());
            process.closeWriteChannel();
            process.waitForFinished();

            m_errorString = QString::fromLocal8Bit(process.readAllStandardOutput().append(process.readAllStandardError()));
            m_rc = process.exitCode();
            if (process.exitStatus() != QProcess::NormalExit) {
                m_rc = 1;
            }

            if (m_rc != 0) {
                dir.rmdir(m_location);
                return Backup::Failed;
            }
            break;

        default:
            return Backup::Failed;
            break;
    }

    m_isOpen = true;
    return Backup::Success;
}
Example #28
0
int main(int argc, char ** argv)
{
    QHash<QString,WhitLocation> hash;
    
    QCoreApplication app(argc,argv);
    QFile input("listall");
    QFile index("whitindex.cal");
    QFile output("whitdefinitions.cal");

    input.open(QFile::ReadOnly);
    index.open(QFile::WriteOnly);
    output.open(QFile::WriteOnly);

    QTextStream is(&input);
    QTextStream ins(&index);

    QString line;

    while(!is.atEnd())
    {
        line = is.readLine();
        
        QProcess process;
        QStringList args;
        args.push_back(line);
        process.start("./words", args);
        process.waitForStarted();
        process.write("\n\n\n\n\n");
        process.waitForFinished();
        QByteArray ret = process.readAllStandardOutput();
        QString retstring(ret);

        app.processEvents();
        
        ins << line << endl;
        ins << QString::number(output.pos()) << endl;
        QByteArray outd = retstring.toUtf8();
        ins << outd.length() << endl;
        WhitLocation wl;
        wl.pos = output.pos();
        wl.len = outd.length();
        line=line.remove("\n");
        hash[line]=wl;
        output.write(outd);
        output.flush();
    }

    QFile output2("whitindexhash.cal");
    output2.open(QFile::WriteOnly);
    QDataStream qds(&output2);
    qds << hash;
}
void AccountsWorker::setPassword(User *user, const QString &oldpwd, const QString &passwd)
{
    QProcess process;
    process.setProgram("passwd");
    process.setArguments(QStringList() << user->name());
    process.start();
    process.write(QString("%1\n%2\n%3").arg(oldpwd).arg(passwd).arg(passwd).toLatin1());
    process.closeWriteChannel();
    process.waitForFinished();

    qDebug() << Q_FUNC_INFO << process.readAllStandardError() << process.readAllStandardOutput();

    Q_EMIT user->passwordModifyFinished(process.exitCode());
}
Example #30
0
bool BabelFileFormat::write(const chemkit::MoleculeFile *file, std::ostream &output)
{
    // get output format to use
    std::string format = option("format").toString();
    if(format.empty()){
        setErrorString("No format set for Babel conversion.");
        return false;
    }

    // write the file to a buffer in the CML format
    std::ostringstream inputBuffer;
    bool ok = const_cast<chemkit::MoleculeFile *>(file)->write(inputBuffer, "cml");
    if(!ok){
        setErrorString("Failed to write CML data for Babel conversion.");
        return false;
    }

    // setup babel arguments
    QStringList arguments;
    arguments.append("-icml");
    arguments.append("-");
    arguments.append(QString("-o") + format.c_str());
    arguments.append("-");

    // create and start the babel process
    QProcess babel;
    babel.start("babel", arguments);
    if(!babel.waitForStarted()){
        setErrorString("Failed to start Babel process.");
        return false;
    }

    // write the CML file data via stdin
    std::string inputData = inputBuffer.str();
    babel.write(inputData.c_str(), inputData.size());
    babel.closeWriteChannel();

    // wait until the babel process is finished
    if(!babel.waitForFinished()){
        setErrorString("Babel process never finished.");
        return false;
    }

    // set output from babel's output
    output << babel.readAll().constData();

    return true;
}