本文整理汇总了C++中QProcess::readAllStandardOutput方法的典型用法代码示例。如果您正苦于以下问题:C++ QProcess::readAllStandardOutput方法的具体用法?C++ QProcess::readAllStandardOutput怎么用?C++ QProcess::readAllStandardOutput使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类QProcess
的用法示例。
在下文中一共展示了QProcess::readAllStandardOutput方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。
示例1: processCommand
//.........这里部分代码省略.........
} else {
return;
}
loop.exec();
} else if (command.name() == "current_title") {
command.sendResponse(webView->title().toLocal8Bit());
} else if (command.name() == "screenshot") {
processScreenshotCommand(command);
} else if (command.name() == "subscribe") {
QString eventName = command.arguments().value(0);
QStringList events = QStringList()
<< "title_changed"
<< "url_changed"
<< "load_started"
<< "load_finished"
<< "user_activity"
<< "info_message_raised"
<< "warning_message_raised"
<< "error_message_raised"
<< "feature_permission_requested";
if (events.contains(eventName)) {
Event event(command);
event.setName(eventName);
ElectricWebView::instance()->eventManager()->subscribe(event);
}
} else if (command.name() == "exec_js") {
processJavaScriptCommand(command);
} else if (command.name() == "inject_js") {
QMap<QString, QWebEngineScript::ScriptWorldId> worlds;
worlds["main"] = QWebEngineScript::MainWorld;
worlds["application"] = QWebEngineScript::ApplicationWorld;
worlds["user"] = QWebEngineScript::UserWorld;
QMap<QString, QWebEngineScript::InjectionPoint> injectionPoints;
injectionPoints["document_creation"] = QWebEngineScript::DocumentCreation;
injectionPoints["document_ready"] = QWebEngineScript::DocumentReady;
injectionPoints["deferred"] = QWebEngineScript::Deferred;
QWebEngineScript::ScriptWorldId world = worlds[command.arguments().value(0)];
QWebEngineScript::InjectionPoint injectionPoint = injectionPoints[command.arguments().value(1)];
QWebEngineScript script;
script.setWorldId(world);
script.setInjectionPoint(injectionPoint);
QString source = command.arguments().value(2);
QString value = command.arguments().mid(3, -1).join(' ');
if (source == "string") {
script.setSourceCode(value);
} else if (source == "file") {
QFile file(value);
file.open(QFile::ReadOnly);
script.setSourceCode(file.readAll());
}
ElectricWebView::instance()->webView()->page()->scripts().insert(script);
} else if (command.name() == "idle_time") {
command.sendResponse(QString("%1").arg(ElectricWebView::instance()->inputEventFilter()->idle()).toLocal8Bit());
} else if (command.name() == "block_user_activity") {
bool block = QVariant(command.arguments().value(0)).toBool();
ElectricWebView::instance()->inputEventFilter()->setBlock(block);
} else if (command.name() == "exec_cmd") {
bool sync = command.arguments().value(0) == "sync";
if (sync) {
QProcess *process = new QProcess;
process->start(command.arguments().mid(1, -1).join(' '));
process->waitForFinished(-1);
command.sendResponse(QUrl::toPercentEncoding(process->readAllStandardOutput()));
} else {
QProcess::startDetached(command.arguments().mid(1, -1).join(' '));
}
} else if (command.name() == "accept_feature_request" || command.name() == "reject_feature_request") {
QMap<QString, QWebEnginePage::Feature> features;
features["geolocation"] = QWebEnginePage::Geolocation;
features["audio_capture"] = QWebEnginePage::MediaAudioCapture;
features["video_capture"] = QWebEnginePage::MediaVideoCapture;
features["audio_video_capture"] = QWebEnginePage::MediaAudioVideoCapture;
features["mouse_lock"] = QWebEnginePage::MouseLock;
QUrl securityOrigin(command.arguments().value(1));
QWebEnginePage::Feature feature = features[command.arguments().value(0)];
QWebEnginePage::PermissionPolicy policy;
if (command.name() == "accept_feature_request")
policy = QWebEnginePage::PermissionGrantedByUser;
else
policy = QWebEnginePage::PermissionDeniedByUser;
ElectricWebView::instance()->webView()->page()->setFeaturePermission(securityOrigin, feature, policy);
} else if (command.name() == "quit") {
int exitCode = command.arguments().value(0).toInt();
qApp->exit(exitCode);
}
}
示例2: saveEdit
void Area::saveEdit(int del){
//temporary file for the text edition
QFile newph("temp.ph");
newph.open(QIODevice::WriteOnly | QIODevice::Truncate);
QTextStream flux(&newph);
flux.setCodec("UTF-8");
QString *file = new QString("temp.ph");
QString fileXML("tempXML.xml");
std::string phFile = file->toStdString();
try{
//Save new text into new file
if(this->textArea->toPlainText().isEmpty()){
throw textAreaEmpty_exception();
}
flux << this->textArea->toPlainText() << endl;
newph.close();
if(del == 0){
emit makeTempXML();
}
// render graph
PHPtr myPHPtr = PHIO::parseFile(phFile);
this->myArea->setPHPtr(myPHPtr);
myPHPtr->render();
PHScenePtr scene = myPHPtr->getGraphicsScene();
this->myArea->setScene(&*scene);
// delete the current sortsTree and groupsTree
this->treeArea->sortsTree->clear();
//this->treeArea->groupsTree->clear();
// set the pointer of the treeArea
this->treeArea->myPHPtr = myPHPtr;
//set the pointer of the treeArea
this->treeArea->myArea = this->myArea;
// build the tree in the treeArea
this->treeArea->build();
this->indicatorEdit->setVisible(false);
this->saveTextEdit->setDefault(false);
this->textArea->incrementeNberTextChange();
this->typeOfCancel = 0;
this->saveTextEdit->setEnabled(false);
this->textArea->setNberEdit(0);
this->cancelTextEdit->setShortcut(QKeySequence());
this->setOldText();
newph.remove();
this->mainWindow->importXMLMetadata(fileXML);
}
catch(textAreaEmpty_exception & e){
QMessageBox::critical(this, "Error !", "You cannot update from an empty text area !");
}
catch(ph_parse_error & argh){
//Catch a parsing error !
//Put the exception into a QMessageBox critical
QString phc = "phc";
QStringList args;
args << "-l" << "dump" << "-i" << QString::fromUtf8(phFile.c_str()) << "--no-debug";
QProcess *phcProcess = new QProcess();
phcProcess->start(phc, args);
if (!phcProcess->waitForStarted())
throw pint_program_not_found() << file_info("phc");
phcProcess->readChannel();
// read result
QByteArray stderr;
QByteArray stdout;
while (!phcProcess->waitForFinished()) {
stderr += phcProcess->readAllStandardError();
stdout += phcProcess->readAllStandardOutput();
}
stderr += phcProcess->readAllStandardError();
stdout += phcProcess->readAllStandardOutput();
delete phcProcess;
//Use split function to only keep the line number
QStringList list = QString(stderr).split('"');
QStringList list2 = list[1].split(":");
QStringList list3 = list2[0].split(" ");
//One or more of your expressions are wrong !
newph.remove();
//.........这里部分代码省略.........
示例3: onAddEngine
void DialogEngines::onAddEngine() {
QString fileName = QFileDialog::getOpenFileName(this,
tr("Add UCI Engine"), this->lastAddedEnginePath, tr("UCI Engines (*)"));
fileName = QString('"').append(fileName).append('"');
QDir d = QFileInfo(fileName).absoluteDir();
this->lastAddedEnginePath = d.absolutePath();
this->setEnabled(false);
QProcess process;
process.start(fileName,QIODevice::ReadWrite);
// Wait for process to start
if(!process.waitForStarted(500)) {
// if process doesn't start, just ignore
} else {
process.write("uci\n");
process.waitForBytesWritten();
// give the engine 700 ms to respond to
// the uci command
this->delay(700);
// read generated output
QString output = QString("");
// give another 50 ms until the engine outputs info
process.waitForReadyRead(50) ;
output.append(process.readAllStandardOutput());
// look for engine id
QString engine_name = QString("");
QRegularExpression regExpEngineName = QRegularExpression("id\\sname\\s(\\w|\\s|\\S)+");
QRegularExpressionMatch m_id = regExpEngineName.match(output);
if(m_id.hasMatch()) {
int len = m_id.capturedLength(0);
engine_name = m_id.captured(0).mid(8,len-1).split("\n").at(0);
}
// attempt to quit the engine
process.write("quit\n");
process.waitForBytesWritten();
process.waitForFinished(250);
// if still running, kill it
if(process.state() == QProcess::Running) {
// if engine doesn't response, it could mean that
// this is no engine _or_ (as in the case of e.g arasanx-64
// takes an extremely long time to respond to "quit".
// kill it ...
process.kill();
process.waitForFinished();
}
// ... however even if we had to kill the engine, as
// long as the engine provided us with a proper name, we
// assume that we found a real uci engine
if(!engine_name.isEmpty()) {
Engine new_engine = Engine();
new_engine.setName(engine_name);
new_engine.setPath(fileName);
this->engines.append(new_engine);
QListWidgetItem *item = new QListWidgetItem(new_engine.getName());
this->lstEngines->addItem(item);
item->setSelected(true);
this->update();
}
}
this->setEnabled(true);
}
示例4: processDownload
void KbFirmware::processDownload(QNetworkReply* reply){
if(reply->error() != QNetworkReply::NoError)
return;
// Update last check
lastCheck = lastFinished = QDateTime::currentMSecsSinceEpoch();
QByteArray data = reply->readAll();
// Don't do anything if this is the same as the last version downloaded
QByteArray hash = QCryptographicHash::hash(data, QCryptographicHash::Sha256);
if(hash == fwTableHash)
return;
fwTableHash = hash;
if(hasGPG == UNKNOWN){
// Check for a GPG installation
QProcess gpg;
gpg.start("gpg", QStringList("--version"));
gpg.waitForFinished();
if(gpg.error() == QProcess::FailedToStart)
// No GPG install
hasGPG = NO;
else {
QString output = QString::fromUtf8(gpg.readAll());
// Must support RSA keys and SHA256
if(output.contains("RSA", Qt::CaseInsensitive) && output.contains("SHA256", Qt::CaseInsensitive))
hasGPG = YES;
else
hasGPG = NO;
}
if(!hasGPG)
qDebug() << "No GPG detected, signature verification disabled";
}
if(hasGPG){
// If GPG is available, check the signature on the file before proceeding.
QDir tmp = QDir::temp();
// Save file to a temporary path. Include PID to avoid conflicts
qint64 pid = QCoreApplication::applicationPid();
QString fwPath = tmp.absoluteFilePath(QString("ckb-%1-firmware").arg(pid));
QFile firmware(fwPath);
if(!firmware.open(QIODevice::WriteOnly)
|| firmware.write(data) != data.length()){
qDebug() << "Failed to write firmware file to temporary location, aborting firmware check";
return;
}
firmware.close();
// Write GPG key
QString keyPath = tmp.absoluteFilePath(QString("ckb-%1-key.gpg").arg(pid));
if(!QFile::copy(":/bin/msckey.gpg", keyPath)){
firmware.remove();
qDebug() << "Failed to write GPG key to temporary location, aborting firmware check";
return;
}
// Check signature
QProcess gpg;
gpg.start("gpg", QStringList("--no-default-keyring") << "--keyring" << keyPath << "--verify" << fwPath);
gpg.waitForFinished();
// Clean up temp files
tmp.remove(fwPath);
tmp.remove(keyPath);
if(gpg.error() != QProcess::UnknownError || gpg.exitCode() != 0){
qDebug() << "GPG couldn't verify firmware signature:";
qDebug() << gpg.readAllStandardOutput();
qDebug() << gpg.readAllStandardError();
return;
}
// Signature good, proceed to update database
}
fwTable.clear();
QStringList lines = QString::fromUtf8(data).split("\n");
bool scan = false;
foreach(QString line, lines){
// Collapse whitespace
line.replace(QRegExp("\\s+"), " ").remove(QRegExp("^\\s")).remove(QRegExp("\\s$"));
// Skip empty or commented-out lines
if(line.length() == 0 || line.at(0) == '#')
continue;
// Don't read anything until the entries begin and don't read anything after they end
if(!scan){
if(line == "!BEGIN FW ENTRIES")
scan = true;
else
continue;
}
if(line == "!END FW ENTRIES")
break;
QStringList components = line.split(" ");
if(components.length() != 7)
continue;
// "VENDOR-PRODUCT"
QString device = components[0].toUpper() + "-" + components[1].toUpper();
FW fw;
fw.fwVersion = components[2].toFloat(); // Firmware blob version
fw.url = QUrl::fromPercentEncoding(components[3].toLatin1()); // URL to zip file
fw.ckbVersion = PARSE_CKB_VERSION(components[4]); // Minimum ckb version
fw.fileName = QUrl::fromPercentEncoding(components[5].toLatin1()); // Name of file inside zip
fw.hash = QByteArray::fromHex(components[6].toLatin1()); // SHA256 of file inside zip
// Update entry
fwTable[device] = fw;
}
示例5: setAllMonitorsExtend
DUTIL_USE_NAMESPACE
bool setAllMonitorsExtend()
{
QProcess *checkMons = new QProcess;
checkMons->start("xrandr");
checkMons->waitForFinished(1000);
QString primaryMonitor;
QStringList otherMonitors;
const QString result = checkMons->readAllStandardOutput();
const QStringList &infoList = result.split('\n');
bool foundMonitor = false;
for (const QString &info : infoList)
{
const QStringList details = info.split(' ');
if (details.count() < 3 || details.at(1) != "connected")
continue;
qDebug() << "info: " << info;
qDebug() << "found monitor: " << details.first();
foundMonitor = true;
if (details.at(2) == "primary")
primaryMonitor = details.first();
else
otherMonitors.append(details.first());
}
if (!foundMonitor) {
qCritical() << "can not find any monitor" << "retray in 15 second...";
return foundMonitor;
}
// set other monitors
QString lastMonitor = primaryMonitor;
if (lastMonitor.isEmpty())
lastMonitor = otherMonitors.first();
// call enable xrandr first
QProcess enableMonitor;
enableMonitor.start("xrandr --auto");
bool ret = enableMonitor.waitForFinished(-1);
qDebug()<< "enable monitor" <<ret<<enableMonitor.readAll();
for (const QString &m : otherMonitors)
{
if (m == lastMonitor)
continue;
QProcess *setting = new QProcess;
QString cmd = QString("xrandr --output %1 --right-of %2 --auto").arg(m).arg(lastMonitor);
qDebug() << "exec: " << cmd;
setting->start(cmd);
bool result = setting->waitForFinished(1000);
qDebug() << "finished: " << result;
setting->deleteLater();
}
checkMons->deleteLater();
return foundMonitor;
}
示例6: stdoutStream
QList<DiskDevice *> enumerateDevice()
{
QList<DiskDevice *> devices;
utils::writeLog("Enumerating imageable devices for OSX");
QProcess process;
QStringList lines;
process.setEnvironment(QStringList() << "LANG=C");
process.start("/usr/sbin/diskutil", QStringList() << "list", QIODevice::ReadWrite | QIODevice::Text);
if (! process.waitForFinished())
utils::writeLog("Could not execute diskutil to enumerate devices");
else
{
QTextStream stdoutStream(process.readAllStandardOutput());
while (true)
{
QString line = stdoutStream.readLine().simplified(); /* Remove trailing and leading ws */
if (line.isNull())
break;
/* The line holding the device is the only line always starting with 0: */
else if (line.startsWith("0:"))
{
lines << line;
}
}
for (int i = 0; i < lines.count(); i++)
{
QString line = lines.at(i);
QStringList deviceAttr = line.split(" ");
/*
* THE FOLLOWING LIST CHANGES IF THE DISK WAS NOT INITIALISED
* In that case, <partition schema name> is missing and the
* index for the following elements has to be adressed by n-1
* content is now:
* [0] 0:
* [1] <partition scheme name>
* [2] <total_size>
* [3] <size_unit>
* [4] device name (disk0, disk1, etc)
*/
QString deviceSpace;
QString devicePath("/dev/");
if (deviceAttr.at(1).startsWith("*"))
{
/* partition schema name was missing - uninitialised disk */
deviceSpace = deviceAttr.at(1) + " " + deviceAttr.at(2);
devicePath += (new QString(deviceAttr.at(3)))->replace(0, 1, "rd");
} else
{
deviceSpace = deviceAttr.at(2) + " " + deviceAttr.at(3);
QString deviceName(deviceAttr.at(4));
/* make the disk become a rdisk */
devicePath += deviceName.replace(0, 1, "rd");
}
deviceSpace.remove("*");
DiskDevice *nd = new DiskDevice(i, devicePath, deviceSpace);
nd = addAdditionalInfo(nd);
if (nd->getIsWritable())
devices.append(nd);
}
}
return devices;
}
示例7: executeSCPFrom
bool SSHConnectionCLI::executeSCPFrom(const QString& source,
const QString& dest,
const QStringList& args,
QString* stdout_str, QString* stderr_str,
int* ec)
{
QProcess proc;
// Start with input args
QStringList fullArgs(args);
// Add port number
fullArgs << "-P" << QString::number(m_port);
// Add source
fullArgs << QString("%1%2%3:%4")
.arg(m_user)
.arg(m_user.isEmpty() ? "" : "@")
.arg(m_host)
.arg(source);
// Add destination
fullArgs << dest;
proc.start("scp", fullArgs);
int timeout_ms = 60000; // one minute
if (!proc.waitForStarted(timeout_ms)) {
qWarning() << QString("Failed to start scp command with args \"%1\" "
"after %2 seconds.")
.arg(fullArgs.join(","))
.arg(timeout_ms / 1000);
return false;
}
proc.closeWriteChannel();
if (!proc.waitForFinished(timeout_ms)) {
qWarning() << QString("scp command with args \"%1\" failed to finish "
"within %2 seconds.")
.arg(fullArgs.join(","))
.arg(timeout_ms / 1000);
return false;
}
if (proc.exitCode() != 0) {
qWarning() << QString("scp command with args \"%1\" failed with an exit "
"code of %2.")
.arg(fullArgs.join(","))
.arg(proc.exitCode())
<< "\nstdout:\n"
<< QString(proc.readAllStandardOutput()) << "\nstderr:\n"
<< QString(proc.readAllStandardError());
return false;
}
if (stdout_str != nullptr)
*stdout_str = QString(proc.readAllStandardOutput());
if (stderr_str != nullptr)
*stderr_str = QString(proc.readAllStandardError());
if (ec != nullptr)
*ec = proc.exitCode();
proc.close();
return true;
}
示例8: indexAttachment
// Index any PDFs that are attached. Basically it turns the PDF into text and adds it the same
// way as a note's body
void IndexRunner::indexAttachment(qint32 lid, Resource &r) {
if (!officeFound)
return;
QLOG_DEBUG() << "indexing attachment to note " << lid;
if (!keepRunning || pauseIndexing) {
indexTimer->start();
return;
}
ResourceTable rtable(&db->conn);
qint32 reslid = rtable.getLid(r.guid);
if (lid <= 0) {
indexTimer->start();
return;
}
QLOG_DEBUG() << "Resource " << reslid;
QString extension = "";
ResourceAttributes attributes;
if (r.attributes.isSet())
attributes = r.attributes;
if (attributes.fileName.isSet()) {
extension = attributes.fileName;
int i = extension.indexOf(".");
extension = extension.mid(i);
}
if (extension != ".doc" && extension != ".xls" && extension != ".ppt" &&
extension != ".docx" && extension != ".xlsx" && extension != ".pptx" &&
extension != ".pps" && extension != ".pdf" && extension != ".odt" &&
extension != ".odf" && extension != ".ott" && extension != ".odm" &&
extension != ".html" && extension != ".txt" && extension != ".oth" &&
extension != ".ods" && extension != ".ots" && extension != ".odg" &&
extension != ".otg" && extension != ".odp" && extension != ".otp" &&
extension != ".odb" && extension != ".oxt" && extension != ".htm" &&
extension != ".docm")
return;
QString file = global.fileManager.getDbaDirPath() + QString::number(reslid) +extension;
QFile dataFile(file);
if (!dataFile.exists()) {
QDir dir(global.fileManager.getDbaDirPath());
QStringList filterList;
filterList.append(QString::number(lid)+".*");
QStringList list= dir.entryList(filterList, QDir::Files);
if (list.size() > 0) {
file = global.fileManager.getDbaDirPath()+list[0];
}
}
QString outDir = global.fileManager.getTmpDirPath();
QProcess sofficeProcess;
QString cmd = "soffice --headless --convert-to txt:\"Text\" --outdir "
+outDir + " "
+file;
sofficeProcess.start(cmd,
QIODevice::ReadWrite|QIODevice::Unbuffered);
QLOG_DEBUG() << "Starting soffice ";
sofficeProcess.waitForStarted();
QLOG_DEBUG() << "Waiting for completion";
sofficeProcess.waitForFinished();
int rc = sofficeProcess.exitCode();
QLOG_DEBUG() << "soffice Errors:" << sofficeProcess.readAllStandardError();
QLOG_DEBUG() << "soffice Output:" << sofficeProcess.readAllStandardOutput();
QLOG_DEBUG() << "return code:" << rc;
if (rc == 255) {
QLOG_ERROR() << "soffice not found. Disabling attachment indexing.";
this->officeFound = false;
return;
}
QFile txtFile(outDir+QString::number(reslid) +".txt");
if (txtFile.open(QIODevice::ReadOnly)) {
QString text;
text = txtFile.readAll();
NSqlQuery sql(db->conn);
sql.prepare("Insert into SearchIndex (lid, weight, source, content) values (:lid, :weight, 'recognition', :content)");
sql.bindValue(":lid", lid);
sql.bindValue(":weight", 100);
sql.bindValue(":content", text);
QLOG_DEBUG() << "Adding note resource to index DB";
sql.exec();
txtFile.close();
}
QDir dir;
dir.remove(outDir+QString::number(reslid) +".txt");
}
示例9: DevSelectionChanged
void NetworkMan::DevSelectionChanged()
{
int sel = listNetDev->currentRow();
if ( sel != -1 ) {
pushConfigure->setEnabled(TRUE);
// Check to see if the network tray icon is enabled or not
QString filename = PREFIX + "/share/pcbsd/xstartup/tray-" + Devs[sel] + ".sh";
// First run a check to if we need to enable or disable the checkbox
if ( QFile::exists( filename ) )
{
checkSysTray->setChecked(TRUE);
} else {
checkSysTray->setChecked(FALSE);
}
DevsIP[sel] = getIpForIdent(Devs[sel]);
DevsStatus[sel] = getStatusForIdent(Devs[sel]);
DevsNetmask[sel] = getNetmaskForIdent(Devs[sel]);
textStatusLabel1->setText(tr("Address:"));
textStatus1->setText(tr("IP: ") + DevsIP[sel] + " / " + tr("Netmask: ") + DevsNetmask[sel]);
if ( getTypeForIdent(Devs[sel]) == "Wireless" )
{
checkSysTray->setVisible(FALSE);
textStatusLabel2->setText(tr("SSID:"));
QString SSID = "";
QString tmp;
QProcess *getIfProc = new QProcess();
getIfProc->start(IFCONFIG, QStringList() << Devs[sel]);
if (getIfProc->waitForFinished(2000)) {
tmp = getIfProc->readAllStandardOutput().simplified();
}
getIfProc->kill();
delete getIfProc;
if (tmp != "" && tmp.indexOf("ssid ") != -1){
SSID = tmp.remove(0, tmp.indexOf("ssid ") + 5);
SSID.truncate(tmp.indexOf("channel") - 1 );
}
textStatus2->setText(SSID);
} else {
if ( ! InstallerMode )
checkSysTray->setVisible(TRUE);
textStatusLabel2->setText(tr("MAC Address:"));
textStatus2->setText(DevsMAC[sel]);
}
textStatusLabel3->setText(tr("Status:"));
textStatus3->setText(DevsStatus[sel]);
}
}
示例10: subProcessStandardOutput
void EngineSync::subProcessStandardOutput()
{
QProcess *process = qobject_cast<QProcess *>(this->sender());
QByteArray data = process->readAllStandardOutput();
qDebug() << QString(data);
}
示例11: resetComboBoxVoAoItem
void ConfigDialog::resetComboBoxVoAoItem(const ConfigData::Data& data)
{
// 使用出来るドライバ項目を取得、初期化する
QRegExp rx("^\t(.+)\t");
QProcess p;
QString mplayerPath;
if( data.useMplayerPath )
mplayerPath = data.mplayerPath;
else
mplayerPath = "mplayer";
_comboBoxVo->clear();
_comboBoxVo->addItem(tr("指定無し"), "");
_comboBoxVoClipping->clear();
_comboBoxVoClipping->addItem(tr("指定無し"), "");
p.start(mplayerPath, QStringList() << "-vo" << "help");
if( p.waitForFinished() ) {
QStringList out = QString(p.readAllStandardOutput()).split("\n");
for(int i=0; i < out.size(); ++i) {
if( rx.indexIn(out[i]) != -1 ) {
_comboBoxVo->addItem(rx.cap(1), rx.cap(1));
_comboBoxVoClipping->addItem(rx.cap(1), rx.cap(1));
}
}
}
_comboBoxAo->clear();
_comboBoxAo->addItem(tr("指定無し"), "");
p.start(mplayerPath, QStringList() << "-ao" << "help");
if( p.waitForFinished() ) {
QStringList out = QString(p.readAllStandardOutput()).split("\n");
for(int i=0; i < out.size(); ++i) {
if( rx.indexIn(out[i]) != -1 )
_comboBoxAo->addItem(rx.cap(1), rx.cap(1));
}
}
// 項目を選択する
int index;
index = _comboBoxVo->findData(data.voName);
if( index < 0 ) {
_comboBoxVo->addItem(data.voName + tr("(使用不可)"), data.voName);
index = _comboBoxVo->count() - 1;
}
_comboBoxVo->setCurrentIndex(index);
index = _comboBoxVoClipping->findData(data.voNameForClipping);
if( index < 0 ) {
_comboBoxVoClipping->addItem(data.voNameForClipping + tr("(使用不可)"), data.voNameForClipping);
index = _comboBoxVoClipping->count() - 1;
}
_comboBoxVoClipping->setCurrentIndex(index);
index = _comboBoxAo->findData(data.aoName);
if( index < 0 ) {
_comboBoxAo->addItem(data.aoName + tr("(使用不可)"), data.aoName);
index = _comboBoxAo->count() - 1;
}
_comboBoxAo->setCurrentIndex(index);
}
示例12: find_running_copy
bool DFInstanceLinux::find_running_copy(bool connect_anyway) {
// find PID of DF
TRACE << "attempting to find running copy of DF by executable name";
QProcess *proc = new QProcess(this);
QStringList args;
args << "dwarfort.exe"; // 0.31.04 and earlier
args << "Dwarf_Fortress"; // 0.31.05+
proc->start("pidof", args);
proc->waitForFinished(1000);
if (proc->exitCode() == 0) { //found it
QByteArray out = proc->readAllStandardOutput();
QStringList str_pids = QString(out).split(" ");
str_pids.sort();
if(str_pids.count() > 1){
m_pid = QInputDialog::getItem(0, tr("Warning"),tr("Multiple Dwarf Fortress processes found, please choose the process to use."),str_pids,str_pids.count()-1,false).toInt();
}else{
m_pid = str_pids.at(0).toInt();
}
m_memory_file.setFileName(QString("/proc/%1/mem").arg(m_pid));
TRACE << "USING PID:" << m_pid;
} else {
QMessageBox::warning(0, tr("Warning"),
tr("Unable to locate a running copy of Dwarf "
"Fortress, are you sure it's running?"));
LOGW << "can't find running copy";
m_is_ok = false;
return m_is_ok;
}
m_inject_addr = unsigned(-1);
m_alloc_start = 0;
m_alloc_end = 0;
map_virtual_memory();
//qDebug() << "LOWEST ADDR:" << hex << lowest_addr;
//DUMP LIST OF MEMORY RANGES
/*
QPair<uint, uint> tmp_pair;
foreach(tmp_pair, m_regions) {
LOGD << "RANGE start:" << hex << tmp_pair.first << "end:" << tmp_pair.second;
}*/
VIRTADDR m_base_addr = read_addr(m_lowest_address + 0x18);
LOGD << "base_addr:" << m_base_addr << "HEX" << hex << m_base_addr;
m_is_ok = m_base_addr > 0;
uint checksum = calculate_checksum();
LOGD << "DF's checksum is" << hexify(checksum);
if (m_is_ok) {
m_layout = get_memory_layout(hexify(checksum).toLower(), !connect_anyway);
}
//Get dwarf fortress directory
m_df_dir = QDir(QFileInfo(QString("/proc/%1/cwd").arg(m_pid)).symLinkTarget());
LOGI << "Dwarf fortress path:" << m_df_dir.absolutePath();
return m_is_ok || connect_anyway;
}
示例13: main
int main(int argc, char** argv)
{
QApplication myApp(argc, argv);
myApp.setOrganizationName("CommonTK");
myApp.setApplicationName("CommandLineModuleExplorer");
ctkCommandLineParser cmdLineParser;
cmdLineParser.setArgumentPrefix("--", "-");
cmdLineParser.setStrictModeEnabled(true);
cmdLineParser.addArgument("module", "", QVariant::String, "Path to a CLI module (executable)");
//cmdLineParser.addArgument("module-xml", "", QVariant::String, "Path to a CLI XML description.");
cmdLineParser.addArgument("validate-module", "", QVariant::String, "Path to a CLI module");
cmdLineParser.addArgument("validate-xml", "", QVariant::String, "Path to a CLI XML description.");
cmdLineParser.addArgument("verbose", "v", QVariant::Bool, "Be verbose.");
cmdLineParser.addArgument("help", "h", QVariant::Bool, "Print this help text.");
bool parseOkay = false;
QHash<QString, QVariant> args = cmdLineParser.parseArguments(argc, argv, &parseOkay);
QTextStream out(stdout, QIODevice::WriteOnly);
if(!parseOkay)
{
out << "Error parsing command line arguments: " << cmdLineParser.errorString() << '\n';
return EXIT_FAILURE;
}
if (args.contains("help"))
{
out << "Usage:\n" << cmdLineParser.helpText();
out.flush();
return EXIT_SUCCESS;
}
if (args.contains("validate-module"))
{
if (args.contains("validate-xml"))
{
out << "Ignoring \"validate-xml\" option.\n\n";
}
QString input = args["validate-module"].toString();
if (!QFile::exists(input))
{
qCritical() << "Module does not exist:" << input;
return EXIT_FAILURE;
}
QProcess process;
process.setReadChannel(QProcess::StandardOutput);
process.start(input, QStringList("--xml"));
if (!process.waitForFinished() || process.exitStatus() == QProcess::CrashExit ||
process.error() != QProcess::UnknownError)
{
qWarning() << "The executable at" << input << "could not be started:" << process.errorString();
return EXIT_FAILURE;
}
process.waitForReadyRead();
QByteArray xml = process.readAllStandardOutput();
if (args.contains("verbose"))
{
qDebug() << xml;
}
// validate the outputted xml description
QBuffer xmlInput(&xml);
xmlInput.open(QIODevice::ReadOnly);
ctkCmdLineModuleXmlValidator validator(&xmlInput);
if (!validator.validateInput())
{
qCritical() << validator.errorString();
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
else if (args.contains("validate-xml"))
{
QFile input(args["validate-xml"].toString());
if (!input.exists())
{
qCritical() << "XML description does not exist:" << input.fileName();
return EXIT_FAILURE;
}
input.open(QIODevice::ReadOnly);
ctkCmdLineModuleXmlValidator validator(&input);
if (!validator.validateInput())
{
qCritical() << validator.errorString();
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
//.........这里部分代码省略.........
示例14: main
int main(int argc, char **argv)
{
if (argc < 3) {
qFatal("Usage: ./genversion <git_root> <target_file>");
return 255;
}
QCoreApplication app(argc, argv);
QString gitroot = app.arguments()[1];
QString target = app.arguments()[2];
QString basever, protover, clientneeds, coreneeds, descrver, dirty;
QString committish, commitdate;
// check Git for information if present
if (QFile::exists(gitroot + "/.git")) {
// try to execute git-describe to get a version string
QProcess git;
git.setWorkingDirectory(gitroot);
#ifdef Q_OS_WIN
git.start("cmd.exe", QStringList() << "/C" << "git" << "describe" << "--long");
#else
git.start("git", QStringList() << "describe" << "--long");
#endif
if (git.waitForFinished(10000)) {
QString descr = git.readAllStandardOutput().trimmed();
if (!descr.isEmpty() && !descr.contains("fatal")) {
// seems we have a valid git describe string
descrver = descr;
// check if the workdir is dirty
#ifdef Q_OS_WIN
git.start("cmd.exe", QStringList() << "/C" << "git" << "diff-index" << "--name-only" << "HEAD");
#else
git.start("git", QStringList() << "diff-index" << "--name-only" << "HEAD");
#endif
if (git.waitForFinished(10000)) {
if (!git.readAllStandardOutput().isEmpty()) dirty = "*";
}
// get a full committish
#ifdef Q_OS_WIN
git.start("cmd.exe", QStringList() << "/C" << "git" << "rev-parse" << "HEAD");
#else
git.start("git", QStringList() << "rev-parse" << "HEAD");
#endif
if (git.waitForFinished(10000)) {
committish = git.readAllStandardOutput().trimmed();
}
// Now we do some replacement magic...
//QRegExp rxCheckTag("(.*)-0-g[0-9a-f]+\n$");
//QRegExp rxGittify("(.*)-(\\d+)-g([0-9a-f]+)\n$");
//gitversion.replace(rxCheckTag, QString("\\1%1").arg(dirty));
//gitversion.replace(rxGittify, QString("\\1:git-\\3+\\2%1").arg(dirty));
}
}
}
// parse version.inc
QFile verfile(gitroot + "/version.inc");
if (verfile.open(QIODevice::ReadOnly | QIODevice::Text)) {
QString ver = verfile.readAll();
QRegExp rxBasever("baseVersion\\s*=\\s*\"(.*)\";");
if (rxBasever.indexIn(ver) >= 0)
basever = rxBasever.cap(1);
QRegExp rxProtover("protocolVersion\\s*=\\s*(\\d+)");
if (rxProtover.indexIn(ver) >= 0)
protover = rxProtover.cap(1);
QRegExp rxClientneeds("clientNeedsProtocol\\s*=\\s*(\\d+)");
if (rxClientneeds.indexIn(ver) >= 0)
clientneeds = rxClientneeds.cap(1);
QRegExp rxCoreneeds("coreNeedsProtocol\\s*=\\s*(\\d+)");
if (rxCoreneeds.indexIn(ver) >= 0)
coreneeds = rxCoreneeds.cap(1);
if (committish.isEmpty()) {
QRegExp rxCommit("distCommittish\\s*=\\s*([0-9a-f]+)");
if (rxCommit.indexIn(ver) >= 0) committish = rxCommit.cap(1);
}
QRegExp rxTimestamp("distCommitDate\\s*=\\s*([0-9]+)");
if (rxTimestamp.indexIn(ver) >= 0) commitdate = rxTimestamp.cap(1);
verfile.close();
}
// generate the contents for version.gen
QByteArray contents = QString("QString buildinfo = \"%1,%2,%3,%4,%5,%6,%7,%8\";\n")
.arg(basever, descrver, dirty, committish, commitdate, protover, clientneeds, coreneeds)
.toAscii();
QFile gen(target);
if (!gen.open(QIODevice::ReadWrite | QIODevice::Text)) {
qFatal("%s", qPrintable(QString("Could not write %1!").arg(target)));
return EXIT_FAILURE;
}
QByteArray oldContents = gen.readAll();
if (oldContents != contents) { // only touch the file if something changed
gen.seek(0);
//.........这里部分代码省略.........
示例15: QString
bool CommandLineExporter::executeCommand
(
const QString& command,
const QString& inputFilePath,
const QString& textInput,
const QString& outputFilePath,
QString& stdoutOutput,
QString& stderrOutput
)
{
QProcess process;
process.setReadChannel(QProcess::StandardOutput);
QString expandedCommand = command + QString(" ");
if (!outputFilePath.isNull() && !outputFilePath.isEmpty())
{
// Redirect stdout to the output file path if the path variable wasn't
// set in the command string.
//
if (!expandedCommand.contains(OUTPUT_FILE_PATH_VAR))
{
process.setStandardOutputFile(outputFilePath);
}
else
{
// Surround file path with quotes in case there are spaces in the
// path.
//
QString outputFilePathWithQuotes = QString('\"') +
outputFilePath + '\"';
expandedCommand.replace(OUTPUT_FILE_PATH_VAR, outputFilePathWithQuotes);
}
}
if
(
this->getSmartTypographyEnabled() &&
!this->smartTypographyOnArgument.isNull()
)
{
expandedCommand.replace
(
SMART_TYPOGRAPHY_ARG,
smartTypographyOnArgument
);
}
else if
(
!this->getSmartTypographyEnabled() &&
!this->smartTypographyOffArgument.isNull()
)
{
expandedCommand.replace
(
SMART_TYPOGRAPHY_ARG,
smartTypographyOffArgument
);
}
if (!inputFilePath.isNull() && !inputFilePath.isEmpty())
{
process.setWorkingDirectory(QFileInfo(inputFilePath).dir().path());
}
process.start(expandedCommand);
if (!process.waitForStarted())
{
return false;
}
else
{
if (!textInput.isNull() && !textInput.isEmpty())
{
process.write(textInput.toUtf8());
process.closeWriteChannel();
}
if (!process.waitForFinished())
{
return false;
}
else
{
stdoutOutput = QString::fromUtf8(process.readAllStandardOutput().data());
stderrOutput = QString::fromUtf8(process.readAllStandardError().data());
}
}
return true;
}