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; }
void CheckDirModel::getFileInfoResult() { #ifdef Q_OS_MAC QProcess* p = qobject_cast< QProcess* >( sender() ); Q_ASSERT( p ); QByteArray res = p->readAll().trimmed(); qDebug() << "Got output from GetFileInfo:" << res; // 1 means /Volumes is hidden, so we show it while the dialog is visible if ( res == "1" ) { // Remove the hidden flag for the /Volumnes folder so all mount points are visible in the default (Q)FileSystemModel QProcess* showProcess = new QProcess( this ); qDebug() << "Running SetFile:" << QString( "%1 -a v %2" ).arg( m_setFilePath ).arg( s_macVolumePath ); showProcess->start( QString( "%1 -a v %2" ).arg( m_setFilePath ).arg( s_macVolumePath ) ); connect( showProcess, SIGNAL( readyReadStandardError() ), this, SLOT( processErrorOutput() ) ); m_shownVolumes = true; QTimer::singleShot( 500, this, SLOT( volumeShowFinished() ) ); } p->terminate(); p->deleteLater(); #endif }
bool MountManager::mount() { if(!isPasswordCorrect()){ return false; } if(mountedDirExists()){ emit errorString(QString(QLatin1String("Already have something mounted in %1 ...continue")).arg(m_mountdir)); return true; } if(!QFileInfo(m_imgdir).exists()){ emit errorString(m_imgdir+QLatin1String("file does not exists\n")); return false; } QProcess proc; proc.setEnvironment(QProcess::systemEnvironment()); proc.start(QString(QLatin1String("sh -c \"echo %1 | sudo -S mount -o loop %2 %3\"")).arg(m_userPassWord).arg(m_imgdir).arg(m_mountdir)); if(!proc.waitForFinished()){ emit errorString(QString(QLatin1String("Can't mount image %1")).arg(QString(proc.errorString()))); return false; } if(!mountedDirExists()){ proc.waitForReadyRead(); emit errorString(QLatin1String(proc.readAllStandardError())); return false; } proc.terminate(); messageString(QString(QLatin1String("Image mounted in %1")).arg(m_mountdir)); return true; }
inline QStringList ProcessRun(QString cmd, QStringList args){ //Assemble outputs QStringList out; out << "1" << ""; //error code, string output QProcess proc; QProcessEnvironment env = QProcessEnvironment::systemEnvironment(); env.insert("LANG", "C"); env.insert("LC_MESSAGES", "C"); proc.setProcessEnvironment(env); proc.setProcessChannelMode(QProcess::MergedChannels); if(args.isEmpty()){ proc.start(cmd, QIODevice::ReadOnly); }else{ proc.start(cmd,args ,QIODevice::ReadOnly); } QString info; while(!proc.waitForFinished(1000)){ if(proc.state() == QProcess::NotRunning){ break; } //somehow missed the finished signal QString tmp = proc.readAllStandardOutput(); if(tmp.isEmpty()){ proc.terminate(); } else{ info.append(tmp); } } out[0] = QString::number(proc.exitCode()); out[1] = info+QString(proc.readAllStandardOutput()); return out; }
PRL_RESULT CDspHaClusterHelper::runProgram(const QString & sPath, const QStringList & lstArgs, QProcess & proc) { WRITE_TRACE(DBG_INFO, "run %s %s", qPrintable(sPath), qPrintable(lstArgs.join(" "))); proc.start(sPath, lstArgs); if (!proc.waitForStarted(HAMAN_START_TMO)) { WRITE_TRACE(DBG_FATAL, "Failed to run %s : %s", QSTR2UTF8(sPath), QSTR2UTF8(proc.errorString())); return PRL_ERR_CLUSTER_RESOURCE_ERROR; } if (!proc.waitForFinished(HAMAN_EXEC_TMO)) { WRITE_TRACE(DBG_FATAL, "Failed to wait for finished %s : %s", QSTR2UTF8(sPath), QSTR2UTF8(proc.errorString())); proc.terminate(); return PRL_ERR_CLUSTER_RESOURCE_ERROR; } if (proc.exitCode()) { WRITE_TRACE(DBG_FATAL, "%s failed : retcode : %d, stdout: [%s] stderr: [%s]", QSTR2UTF8(sPath), proc.exitCode(), proc.readAllStandardOutput().constData(), proc.readAllStandardError().constData() ); return PRL_ERR_CLUSTER_RESOURCE_ERROR; } return PRL_ERR_SUCCESS; }
void RecoveryWidget::flashZip() { if (QMessageBox::question(this, tr("Flash Zip"), tr("Are you sure??"), QMessageBox::Yes | QMessageBox::No) == QMessageBox::No) return; this->romFileName = QFileDialog::getOpenFileName(this, tr("Open ROM File"), "/", tr("Zip files (*.zip)")); QFileInfo fInfo = QFileInfo(this->romFileName); FileList *fileList = new FileList; fileList->name.append(this->romFileName); fileList->size.append(QString::number(fInfo.size())); fileList->date.append(fInfo.lastModified().toString()); fileList->type.append("file"); this->romFileName = fInfo.fileName(); QProcess tmp; tmp.start("\"" + sdk + "\"adb shell su -c 'mount /sdcard'"); tmp.waitForFinished(-1); tmp.terminate(); // if (this->dialog != NULL) // delete this->dialog; // this->dialog = new dialogKopiuj(this, fileList, this->sdk, dialogKopiuj::ComputerToPhone, fInfo.absolutePath(), "/sdcard/"); // this->dialog=new dialogKopiuj(this,fileList,this->sdk,"computerToPhone",this->phone,NULL,this->computer); // if (this->alwaysCloseCopy) // this->dialog->closeAfterFinished(); // if (this->dialogKopiujShowModal) // this->dialog->setModal(true); // this->dialog->show(); // connect(this->dialog,SIGNAL(finished(int)),this,SLOT(flashZipCopied())); this->ui->stackedRecovery->setCurrentWidget(this->ui->pageFlashZIP); }
QString OSInfo::getOSVersion() { #if defined(Q_WS_WIN) OSVERSIONINFOEXW ovi; memset(&ovi, 0, sizeof(ovi)); ovi.dwOSVersionInfoSize=sizeof(ovi); GetVersionEx(reinterpret_cast<OSVERSIONINFOW *>(&ovi)); QString os; os.sprintf("%d.%d.%d.%d", ovi.dwMajorVersion, ovi.dwMinorVersion, ovi.dwBuildNumber, (ovi.wProductType == VER_NT_WORKSTATION) ? 1 : 0); return os; #elif defined(Q_OS_MAC) SInt32 major, minor, bugfix; OSErr err = Gestalt(gestaltSystemVersionMajor, &major); if (err == noErr) err = Gestalt(gestaltSystemVersionMinor, &minor); if (err == noErr) err = Gestalt(gestaltSystemVersionBugFix, &bugfix); if (err != noErr) return QString::number(QSysInfo::MacintoshVersion, 16); const NXArchInfo *local = NXGetLocalArchInfo(); const NXArchInfo *ai = local ? NXGetArchInfoFromCpuType(local->cputype, CPU_SUBTYPE_MULTIPLE) : NULL; const char *arch = ai ? ai->name : "unknown"; QString os; os.sprintf("%i.%i.%i (%s)", major, minor, bugfix, arch); return os; #else #ifdef Q_OS_LINUX QProcess qp; QStringList args; args << QLatin1String("-s"); args << QLatin1String("-d"); qp.start(QLatin1String("lsb_release"), args); if (qp.waitForFinished(5000)) { QString os = QString::fromUtf8(qp.readAll()).simplified(); if (os.startsWith(QLatin1Char('"')) && os.endsWith(QLatin1Char('"'))) os = os.mid(1, os.length() - 2).trimmed(); if (! os.isEmpty()) return os; } qWarning("OSInfo: Failed to execute lsb_release"); qp.terminate(); if (! qp.waitForFinished(1000)) qp.kill(); #endif struct utsname un; if (uname(&un) == 0) { QString os; os.sprintf("%s %s", un.sysname, un.release); return os; } return QString(); #endif }
void MainWindow::connectWifi() { QProcess *connect = new QProcess; QSettings settings; connect->setProcessChannelMode(QProcess::MergedChannels); connect->start("\"" + settings.value("sdkPath").toString() + "\"adb connect " + this->ipAddress + ":" + this->portNumber); connect->waitForFinished(2000); connect->terminate(); delete connect; }
bool SynchronousProcess::stopProcess(QProcess &p) { if (p.state() != QProcess::Running) return true; p.terminate(); if (p.waitForFinished(300)) return true; p.kill(); return p.waitForFinished(300); }
void ItemEncryptedLoader::terminateGpgProcess() { if (m_gpgProcess == nullptr) return; QProcess *p = m_gpgProcess; m_gpgProcess = nullptr; p->terminate(); p->waitForFinished(); p->deleteLater(); m_gpgProcessStatus = GpgNotRunning; updateUi(); }
void ProcessSocket::close() { QProcess *proc = qobject_cast<QProcess *>(d); Q_ASSERT(proc); // Be nice to it, let it die peacefully before using an axe // QTBUG-5990, don't call waitForFinished() on a process which hadn't started if (proc->state() == QProcess::Running) { proc->terminate(); proc->waitForFinished(200); proc->kill(); } }
void tst_q3buttongroup::clickLock() { // Task 177677 QProcess process; process.start(QLatin1String("clickLock/clickLock")); if (!process.waitForStarted(10000)) { QFAIL("Could not launch process."); } if (!process.waitForFinished(15000)) { process.terminate(); QFAIL("Could not handle click events properly"); } }
void detailwnd::enregistrer( ) { QString destFile = QFileDialog::getSaveFileName(this, tr("Sauver la video"), "/home/dige7306/"+leAdresse->text(), tr("Video (*.asf *.asx *.wsx *.wmv *.flv *.avi)")); if ( destFile.isEmpty() ) return; QStringList arg; /* for eurosport arg << "-cache"; arg << "4096"; arg << "-dumpstream"; arg << "-dumpfile"; arg << destFile; arg << leAdresse->text(); QProcess::execute( "mplayer", arg ); arg.clear(); arg << "/usr/share/sounds/k3b_success1.wav"; QProcess::execute( "mplayer", arg ); */ /* for atdhe.net */ arg << leAdresse->text(); QProcess::execute( "firefox", arg ); sleep( 5 ); /* wait for plugin to start */ QStringList f; f << "Flash*"; QStringList files = QDir::temp().entryList( f ); qDebug() << files[0]; arg.clear(); arg << "-n" << "100000" << "--follow=name" << QDir::tempPath() + "/" + files[0]; QProcess *tail = new QProcess( this ); tail->setStandardOutputFile( destFile, QIODevice::Truncate ); tail->setStandardErrorFile( "/tmp/tail.err", QIODevice::Truncate ); tail->start( "tail", arg ); if ( tail->waitForStarted() ) { int msec = teDuree->time().hour() * 60 * 60 + teDuree->time().minute() * 60; msec *= 1000; if ( msec == 0 ) msec = -1; if ( !tail->waitForFinished(msec) ) { tail->terminate(); } qDebug() << " tail : " << tail->exitStatus() << " " << tail->exitCode() << endl; } else { qDebug() << " tail non demarre" << endl; } }
void US_Win::closeProcs( void ) { QString names; QList<procData*>::iterator p; for ( p = procs.begin(); p != procs.end(); p++ ) { procData* d = *p; names += d->name + "\n"; } QString isAre = ( procs.size() > 1 ) ? "es are" : " is"; QString itThem = ( procs.size() > 1 ) ? "them" : "it"; QMessageBox box; box.setWindowTitle( tr( "Attention" ) ); box.setText( QString( tr( "The following process%1 still running:\n%2" "Do you want to close %3?" ) .arg( isAre ).arg( names ).arg( itThem ) ) ); QString killText = tr( "&Kill" ); QString closeText = tr( "&Close Gracefully" ); QString leaveText = tr( "&Leave Running" ); QPushButton* kill = box.addButton( killText , QMessageBox::YesRole ); box.addButton( closeText, QMessageBox::YesRole ); QPushButton* leave = box.addButton( leaveText, QMessageBox::NoRole ); box.exec(); if ( box.clickedButton() == leave ) return; for ( p = procs.begin(); p != procs.end(); p++ ) { procData* d = *p; QProcess* process = d->proc; if ( box.clickedButton() == kill ) process->kill(); else process->terminate(); } // We need to sleep slightly (one millisecond) so that the system can clean // up and properly release shared memory. g.scheduleDelete(); US_Sleep::msleep( 1 ); }
QString Repository::Git::GitUtils::makeTmpFileFromCommand( QString command, QString filepath ) { bool ok = true; // Ulozim si current working directory QString cwd = QDir::currentPath(); // Nastavim absolutnu cestu k temp file ako template a zakazem automaticke mazanie QTemporaryFile tempFile; tempFile.setFileTemplate( QDir::toNativeSeparators( QDir::tempPath() + "/" + "qXXXXXX" ) ); tempFile.setAutoRemove( false ); // Ak sa nepodarilo vytvorit temp subor, tak nastavim flag "ok" na false a vypisem chybu if ( !tempFile.open() ) { qDebug() << "Nepodarilo sa vytvorit tmp subor"; ok = false; } // Ak sa podarilo vytvorit temp subor, tak zmenim current working directory if ( ok ) { ok = changeDir( filepath ); } // Ak sa podarilo zmenit current working directory, tak skontroluje existenciu git repozitara if ( ok ) { ok = existGit( filepath ); } // Ak existuje na danej ceste git repozitar, tak vykonam command a vystup ulozim do temp suboru if ( ok ) { QProcess process; process.setStandardOutputFile( QDir::toNativeSeparators( tempFile.fileName() ) ); process.start( command ); process.waitForFinished(); process.close(); process.terminate(); } // Vratim povodny current working directory, ak sa nepodari zmenit, vypisem do konzoly if ( !changeDir( cwd ) ) { qDebug() << "Nepodarilo sa vratit na povodny current working directory"; } // Vratim absolutnu cestu k temp suboru return tempFile.fileName(); }
void LocalProcess::kill(QProcess &t_process, bool t_force) { if (t_process.state() == QProcess::Running) { #ifdef Q_WS_WIN PROCESS_INFORMATION *pinfo = (PROCESS_INFORMATION*)t_process.pid(); if (pinfo) { QString abort_cmd; LOG(Info, "Killing process tree using taskkill " << pinfo->dwProcessId << " force " << t_force); if (t_force) { abort_cmd = QString("taskkill /PID %1 /T /F").arg(pinfo->dwProcessId); } else { abort_cmd = QString("taskkill /PID %1 /T").arg(pinfo->dwProcessId); } QProcess::execute(abort_cmd); } #else pid_t pid(t_process.pid()); if (pid > 0) { openstudio::path killtree = openstudio::getSharedResourcesPath()/openstudio::toPath("runmanager")/openstudio::toPath("killtree.sh"); LOG(Info, "Killing process tree using killtree" << openstudio::toString(killtree) << " for pid " << pid << " force " << t_force); QStringList qsl; qsl.push_back(QString::number(pid)); if (t_force) { qsl.push_back(QString::number(SIGKILL)); } else { qsl.push_back(QString::number(SIGTERM)); } QProcess::execute(openstudio::toQString(killtree), qsl); } #endif } if (t_force) { t_process.kill(); } else { t_process.terminate(); } }
QVector<AndroidDeviceInfo> AndroidConfigurations::connectedDevices(int apiLevel) const { QVector<AndroidDeviceInfo> devices; QProcess adbProc; adbProc.start(adbToolPath().toString(), QStringList() << QLatin1String("devices")); if (!adbProc.waitForFinished(-1)) { adbProc.terminate(); return devices; } QList<QByteArray> adbDevs = adbProc.readAll().trimmed().split('\n'); adbDevs.removeFirst(); AndroidDeviceInfo dev; foreach (const QByteArray &device, adbDevs) { dev.serialNumber = QString::fromLatin1(device.left(device.indexOf('\t')).trimmed()); dev.sdk = getSDKVersion(dev.serialNumber); if (apiLevel != -1 && dev.sdk != apiLevel) continue; devices.push_back(dev); }
QStringList AndroidConfigurations::sdkTargets(int minApiLevel) const { QStringList targets; QProcess proc; proc.start(androidToolPath().toString(), QStringList() << QLatin1String("list") << QLatin1String("target")); // list avaialbe AVDs if (!proc.waitForFinished(-1)) { proc.terminate(); return targets; } while (proc.canReadLine()) { const QString line = QString::fromLocal8Bit(proc.readLine().trimmed()); int index = line.indexOf(QLatin1String("\"android-")); if (index == -1) continue; QString apiLevel = line.mid(index + 1, line.length() - index - 2); if (apiLevel.mid(apiLevel.lastIndexOf(QLatin1Char('-')) + 1).toInt() >= minApiLevel) targets.push_back(apiLevel); } return targets; }
static bool runProcess(const QString &binary, const QStringList &arguments, QString *errorMessage, const QString &workingDir = QString(), const QProcessEnvironment &env = QProcessEnvironment(), int timeOut = 5000, QByteArray *stdOut = Q_NULLPTR, QByteArray *stdErr = Q_NULLPTR) { QProcess process; if (!env.isEmpty()) process.setProcessEnvironment(env); if (!workingDir.isEmpty()) process.setWorkingDirectory(workingDir); qDebug().noquote().nospace() << "Running: " << QDir::toNativeSeparators(binary) << ' ' << arguments.join(QLatin1Char(' ')); process.start(binary, arguments, QIODevice::ReadOnly); if (!process.waitForStarted()) { *errorMessage = msgProcessError(process, "Failed to start"); return false; } if (!process.waitForFinished(timeOut)) { *errorMessage = msgProcessError(process, "Timed out"); process.terminate(); if (!process.waitForFinished(300)) process.kill(); return false; } if (stdOut) *stdOut = process.readAllStandardOutput(); if (stdErr) *stdErr= process.readAllStandardError(); if (process.exitStatus() != QProcess::NormalExit) { *errorMessage = msgProcessError(process, "Crashed"); return false; } if (process.exitCode() != QProcess::NormalExit) { *errorMessage = msgProcessError(process, "Exit code " + QString::number(process.exitCode())); return false; } return true; }
VideoAddress *vp_youget::getVideoAddress(map<string,string> params){ if(!params["url"].length()){ throw "URL cannot be empty"; return nullptr; } qDebug() << "Starting you-get"; QProcess p; QStringList args; args << "-u" << QString::fromStdString(params["url"]); p.start("you-get", args); p.waitForFinished(5000); QString stdout = p.readAllStandardError() + p.readAllStandardOutput(); qDebug() << "you-get result:" << stdout; if(!stdout.length()){ p.terminate(); throw "You-Get timeout or empty output"; }else if(!stdout.contains("Real URLs:\n")){ throw stdout.toUtf8().constData(); } QString urls_str = stdout.split("Real URLs:\n")[1]; QStringList urls = urls_str.split("\n"); VideoAddress *video = new VideoAddress(); for (QStringList::iterator it = urls.begin();it != urls.end(); ++it) { QString urlstr = *it; if(!urlstr.length()) continue; QUrl url = QUrl::fromUserInput(urlstr); if(url.isValid()){ video->addURL(urlstr.toUtf8().constData()); }else{ qDebug() << "Ignore invalid url: " << urlstr; } } return video; }
bool MountManager::unmount() { if(!mountedDirExists()){ emit errorString(QString(QLatin1String("Already have unmounted in %1 ...continue")).arg(m_mountdir)); return true; } QProcess proc; proc.setEnvironment(QProcess::systemEnvironment()); proc.start(QString(QLatin1String("sh -c \"echo %1 | sudo -S umount %2\"")).arg(m_userPassWord).arg(m_mountdir)); if(!proc.waitForFinished()){ emit errorString(QString(QLatin1String("Can't unmount image %1")).arg(QString(proc.errorString()))); return false; } if(mountedDirExists()){ proc.waitForReadyRead(); emit errorString(QLatin1String(proc.readAllStandardError())); return false; } proc.terminate(); messageString(QString(QLatin1String("Image unmounted."))); return true; }
bool hasAntiword() { static bool searched = false, found = false; if (searched) // searched already in this run return found; QProcess *test = new QProcess(); QString exename("antiword"); #if defined(_WIN32) exename = ScPaths::instance().libDir() + "tools/antiword/antiword.exe"; #endif test->start(exename, QStringList()); if (test->waitForStarted()) { found = true; test->terminate(); std::this_thread::sleep_for(std::chrono::milliseconds(5)); test->kill(); } delete test; searched = true; return found; }
void ServerThread::run() { mProcess = new QProcess; startProcess(); while (mRunning) { mProcess->waitForFinished(1000); if (mRunning && mProcess->state() == QProcess::NotRunning) { /* The process stopped without being requested via the monitor. * Check for crash and send report when appropriate, then restart * the process. */ qDebug() << mExecutable << "terminated unexpectedly"; maybeSendBacktrace(); qDebug() << "Restarting" << mExecutable << "in 3 seconds..."; sleep(3); startProcess(); } if (!mRunning && mProcess->state() == QProcess::Running) { // Need to shut down the process qDebug() << "Terminating" << mExecutable; mProcess->terminate(); if (!mProcess->waitForFinished(3000)) { qDebug() << mExecutable << "didn't terminate within 3 seconds," " killing"; mProcess->kill(); } break; } } delete mProcess; mProcess = 0; }
void QProcessProto::terminate() { QProcess *item = qscriptvalue_cast<QProcess*>(thisObject()); if (item) item->terminate(); }
/** Runs the specified command (should be ffmpeg), and lets * writeFrame pipe data into it 1 frame at a time. * * @param[in] strCmd A string containing the command to execute and * all of its arguments * @param[out] progress A function that takes one float argument * (the percentage of the ffmpeg operation complete) and * may display the output to the user in any way it * sees fit. * @param[in] writeFrame A function that takes two arguments, a * process (the ffmpeg process) and an integer * (frames processed or -1, see full description). * This function should write a single frame to the * process. The function returns true value if it * actually wrote a frame. * * This function operates generally as follows: * 1. Spawn process with the command from strCmd * 2. Check ffmpeg's output for a progress update. * 3. Add frames with writeFrame until it returns false. * 4. Repeat from step 2 until all frames have been written. * * The idea is that there are two forms of processing occuring * simultaneously, generating frames to send to ffmpeg, and ffmpeg * encoding those frames. Whether these this actually occur * concurrently or one after another appears to depend on the environment. * * The writeFrame function deserves a bit of extra details. It does * not only return false when there is an error in generating or * writing a frame, it also does it when it wants to "return control" * to the rest of the executeFFMpegPipe function for the purposes of * reading updates from ffmpeg's output. This should be done every * once in a while if possible, but with some formats (specifically gif), * all frames must be loaded before any processing can continue, so * there is no point returning false for it until all frames have * been written. writeFrame is also responsible for closing the writeChannel * of the process when it has finished writing all frames. This indicates * to executeFFMpegPipe that it no longer needs to call writeFrame. * * @return Returns Status::OK if everything went well, and Status::FAIL * and error is detected (usually a non-zero exit code for ffmpeg). */ Status MovieExporter::executeFFMpegPipe(QString strCmd, std::function<void(float)> progress, std::function<bool(QProcess&, int)> writeFrame) { qDebug() << strCmd; QProcess ffmpeg; ffmpeg.setReadChannel(QProcess::StandardOutput); // FFmpeg writes to stderr only for some reason, so we just read both channels together ffmpeg.setProcessChannelMode(QProcess::MergedChannels); ffmpeg.start(strCmd); if (ffmpeg.waitForStarted()) { int framesGenerated = 0; int lastFrameProcessed = 0; const int frameStart = mDesc.startFrame; const int frameEnd = mDesc.endFrame; while(ffmpeg.state() == QProcess::Running) { if (mCanceled) { ffmpeg.terminate(); return Status::CANCELED; } // Check FFmpeg progress int framesProcessed = -1; if(ffmpeg.waitForReadyRead(10)) { QString output(ffmpeg.readAll()); QStringList sList = output.split(QRegExp("[\r\n]"), QString::SkipEmptyParts); for (const QString& s : sList) { qDebug() << "[ffmpeg]" << s; } if(output.startsWith("frame=")) { lastFrameProcessed = framesProcessed = output.mid(6, output.indexOf(' ')).toInt(); } } if(!ffmpeg.isWritable()) { continue; } while(writeFrame(ffmpeg, framesProcessed)) { framesGenerated++; const float percentGenerated = framesGenerated / static_cast<float>(frameEnd - frameStart); const float percentConverted = lastFrameProcessed / static_cast<float>(frameEnd - frameStart); progress((percentGenerated + percentConverted) / 2); } const float percentGenerated = framesGenerated / static_cast<float>(frameEnd - frameStart); const float percentConverted = lastFrameProcessed / static_cast<float>(frameEnd - frameStart); progress((percentGenerated + percentConverted) / 2); } QString output(ffmpeg.readAll()); QStringList sList = output.split(QRegExp("[\r\n]"), QString::SkipEmptyParts); for (const QString& s : sList) { qDebug() << "[ffmpeg]" << s; } if(ffmpeg.exitStatus() != QProcess::NormalExit) { qDebug() << "ERROR: FFmpeg crashed"; return Status::FAIL; } } else { qDebug() << "ERROR: Could not start FFmpeg."; return Status::FAIL; } return Status::OK; }
void AndroidRunner::asyncStart() { QMutexLocker locker(&m_mutex); forceStop(); if (m_useCppDebugger) { // Remove pong file. QProcess adb; adb.start(m_adb, selector() << _("shell") << _("rm") << m_pongFile); adb.waitForFinished(); } QStringList args = selector(); args << _("shell") << _("am") << _("start") << _("-n") << m_intentName; if (m_useCppDebugger) { QProcess adb; adb.start(m_adb, selector() << _("forward") << QString::fromLatin1("tcp:%1").arg(m_localGdbServerPort) << _("localfilesystem:") + m_gdbserverSocket); if (!adb.waitForStarted()) { emit remoteProcessFinished(tr("Failed to forward C++ debugging ports. Reason: %1.").arg(adb.errorString())); return; } if (!adb.waitForFinished(5000)) { emit remoteProcessFinished(tr("Failed to forward C++ debugging ports.")); return; } args << _("-e") << _("debug_ping") << _("true"); args << _("-e") << _("ping_file") << m_pingFile; args << _("-e") << _("pong_file") << m_pongFile; args << _("-e") << _("gdbserver_command") << m_gdbserverCommand; args << _("-e") << _("gdbserver_socket") << m_gdbserverSocket; } if (m_useQmlDebugger || m_useQmlProfiler) { // currently forward to same port on device and host const QString port = QString::fromLatin1("tcp:%1").arg(m_qmlPort); QProcess adb; adb.start(m_adb, selector() << _("forward") << port << port); if (!adb.waitForStarted()) { emit remoteProcessFinished(tr("Failed to forward QML debugging ports. Reason: %1.").arg(adb.errorString())); return; } if (!adb.waitForFinished()) { emit remoteProcessFinished(tr("Failed to forward QML debugging ports.")); return; } args << _("-e") << _("qml_debug") << _("true"); args << _("-e") << _("qmljsdebugger") << QString::fromLatin1("port:%1,block").arg(m_qmlPort); } if (m_useLocalQtLibs) { args << _("-e") << _("use_local_qt_libs") << _("true"); args << _("-e") << _("libs_prefix") << _("/data/local/tmp/qt/"); args << _("-e") << _("load_local_libs") << m_localLibs; args << _("-e") << _("load_local_jars") << m_localJars; if (!m_localJarsInitClasses.isEmpty()) args << _("-e") << _("static_init_classes") << m_localJarsInitClasses; } QProcess adb; adb.start(m_adb, args); if (!adb.waitForStarted()) { emit remoteProcessFinished(tr("Failed to start the activity. Reason: %1.").arg(adb.errorString())); return; } if (!adb.waitForFinished(5000)) { adb.terminate(); emit remoteProcessFinished(tr("Unable to start '%1'.").arg(m_packageName)); return; } if (m_useCppDebugger) { // Handling ping. for (int i = 0; ; ++i) { QTemporaryFile tmp(_("pingpong")); tmp.open(); tmp.close(); QProcess process; process.start(m_adb, selector() << _("pull") << m_pingFile << tmp.fileName()); process.waitForFinished(); QFile res(tmp.fileName()); const bool doBreak = res.size(); res.remove(); if (doBreak) break; if (i == 20) { emit remoteProcessFinished(tr("Unable to start '%1'.").arg(m_packageName)); return; } qDebug() << "WAITING FOR " << tmp.fileName(); QThread::msleep(500); } } m_tries = 0; m_wasStarted = false; QMetaObject::invokeMethod(&m_checkPIDTimer, "start"); }
void DebugConsoleTest::testX11Client() { DebugConsoleModel model; QModelIndex x11TopLevelIndex = model.index(0, 0, QModelIndex()); QVERIFY(x11TopLevelIndex.isValid()); // we don't have any windows yet QCOMPARE(model.rowCount(x11TopLevelIndex), 0); QVERIFY(!model.hasChildren(x11TopLevelIndex)); // child index must be invalid QVERIFY(!model.index(0, 0, x11TopLevelIndex).isValid()); QVERIFY(!model.index(0, 1, x11TopLevelIndex).isValid()); QVERIFY(!model.index(0, 2, x11TopLevelIndex).isValid()); QVERIFY(!model.index(1, 0, x11TopLevelIndex).isValid()); // start glxgears, to get a window, which should be added to the model QSignalSpy rowsInsertedSpy(&model, &QAbstractItemModel::rowsInserted); QVERIFY(rowsInsertedSpy.isValid()); QProcess glxgears; glxgears.start(QStringLiteral("glxgears")); QVERIFY(glxgears.waitForStarted()); QVERIFY(rowsInsertedSpy.wait()); QCOMPARE(rowsInsertedSpy.count(), 1); QVERIFY(model.hasChildren(x11TopLevelIndex)); QCOMPARE(model.rowCount(x11TopLevelIndex), 1); QCOMPARE(rowsInsertedSpy.first().at(0).value<QModelIndex>(), x11TopLevelIndex); QCOMPARE(rowsInsertedSpy.first().at(1).value<int>(), 0); QCOMPARE(rowsInsertedSpy.first().at(2).value<int>(), 0); QModelIndex clientIndex = model.index(0, 0, x11TopLevelIndex); QVERIFY(clientIndex.isValid()); QCOMPARE(model.parent(clientIndex), x11TopLevelIndex); QVERIFY(model.hasChildren(clientIndex)); QVERIFY(model.rowCount(clientIndex) != 0); QCOMPARE(model.columnCount(clientIndex), 2); // other indexes are still invalid QVERIFY(!model.index(0, 1, x11TopLevelIndex).isValid()); QVERIFY(!model.index(0, 2, x11TopLevelIndex).isValid()); QVERIFY(!model.index(1, 0, x11TopLevelIndex).isValid()); // the clientIndex has children and those are properties for (int i = 0; i < model.rowCount(clientIndex); i++) { const QModelIndex propNameIndex = model.index(i, 0, clientIndex); QVERIFY(propNameIndex.isValid()); QCOMPARE(model.parent(propNameIndex), clientIndex); QVERIFY(!model.hasChildren(propNameIndex)); QVERIFY(!model.index(0, 0, propNameIndex).isValid()); QVERIFY(model.data(propNameIndex, Qt::DisplayRole).isValid()); QCOMPARE(model.data(propNameIndex, Qt::DisplayRole).userType(), int(QMetaType::QString)); // and the value const QModelIndex propValueIndex = model.index(i, 1, clientIndex); QVERIFY(propValueIndex.isValid()); QCOMPARE(model.parent(propValueIndex), clientIndex); QVERIFY(!model.index(0, 0, propValueIndex).isValid()); QVERIFY(!model.hasChildren(propValueIndex)); // TODO: how to test whether the values actually work? // and on third column we should not get an index any more QVERIFY(!model.index(i, 2, clientIndex).isValid()); } // row after count should be invalid QVERIFY(!model.index(model.rowCount(clientIndex), 0, clientIndex).isValid()); // creating a second model should be initialized directly with the X11 child DebugConsoleModel model2; QVERIFY(model2.hasChildren(model2.index(0, 0, QModelIndex()))); // now close the window again, it should be removed from the model QSignalSpy rowsRemovedSpy(&model, &QAbstractItemModel::rowsRemoved); QVERIFY(rowsRemovedSpy.isValid()); glxgears.terminate(); QVERIFY(glxgears.waitForFinished()); QVERIFY(rowsRemovedSpy.wait()); QCOMPARE(rowsRemovedSpy.count(), 1); QCOMPARE(rowsRemovedSpy.first().first().value<QModelIndex>(), x11TopLevelIndex); QCOMPARE(rowsRemovedSpy.first().at(1).value<int>(), 0); QCOMPARE(rowsRemovedSpy.first().at(2).value<int>(), 0); // the child should be gone again QVERIFY(!model.hasChildren(x11TopLevelIndex)); QVERIFY(!model2.hasChildren(model2.index(0, 0, QModelIndex()))); }
QString OSInfo::getOSVersion() { static QString qsCached; if (! qsCached.isNull()) return qsCached.isEmpty() ? QString() : qsCached; QString os; #if defined(Q_OS_WIN) OSVERSIONINFOEXW ovi; memset(&ovi, 0, sizeof(ovi)); ovi.dwOSVersionInfoSize=sizeof(ovi); if (!GetVersionEx(reinterpret_cast<OSVERSIONINFOW *>(&ovi))) { return QString(); } os.sprintf("%d.%d.%d.%d", ovi.dwMajorVersion, ovi.dwMinorVersion, ovi.dwBuildNumber, (ovi.wProductType == VER_NT_WORKSTATION) ? 1 : 0); #elif defined(Q_OS_MAC) SInt32 major, minor, bugfix; OSErr err = Gestalt(gestaltSystemVersionMajor, &major); if (err == noErr) err = Gestalt(gestaltSystemVersionMinor, &minor); if (err == noErr) err = Gestalt(gestaltSystemVersionBugFix, &bugfix); if (err != noErr) return QString::number(QSysInfo::MacintoshVersion, 16); char *buildno = NULL; char buildno_buf[32]; size_t sz_buildno_buf = sizeof(buildno); int ret = sysctlbyname("kern.osversion", buildno_buf, &sz_buildno_buf, NULL, 0); if (ret == 0) { buildno = &buildno_buf[0]; } os.sprintf("%lu.%lu.%lu %s", static_cast<unsigned long>(major), static_cast<unsigned long>(minor), static_cast<unsigned long>(bugfix), buildno ? buildno : "unknown"); #else #ifdef Q_OS_LINUX QProcess qp; QStringList args; args << QLatin1String("-s"); args << QLatin1String("-d"); qp.start(QLatin1String("lsb_release"), args); if (qp.waitForFinished(5000)) { os = QString::fromUtf8(qp.readAll()).simplified(); if (os.startsWith(QLatin1Char('"')) && os.endsWith(QLatin1Char('"'))) os = os.mid(1, os.length() - 2).trimmed(); } if (os.isEmpty()) qWarning("OSInfo: Failed to execute lsb_release"); qp.terminate(); if (! qp.waitForFinished(1000)) qp.kill(); #endif if (os.isEmpty()) { struct utsname un; if (uname(&un) == 0) { os.sprintf("%s %s", un.sysname, un.release); } } #endif if (! os.isNull()) qsCached = os; else qsCached = QLatin1String(""); return qsCached; }
void JudgingThread::runProgram() { result = CorrectAnswer; int extraTime = qCeil(qMax(2000, timeLimit * 2) * extraTimeRatio); #ifdef Q_OS_WIN32 SetErrorMode(SEM_NOGPFAULTERRORBOX); STARTUPINFO si; PROCESS_INFORMATION pi; SECURITY_ATTRIBUTES sa; ZeroMemory(&si, sizeof(si)); si.cb = sizeof(si); si.dwFlags = STARTF_USESTDHANDLES; ZeroMemory(&pi, sizeof(pi)); ZeroMemory(&sa, sizeof(sa)); sa.bInheritHandle = TRUE; if (task->getStandardInputCheck()) si.hStdInput = CreateFile((const WCHAR*)(inputFile.utf16()), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, &sa, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); if (task->getStandardOutputCheck()) si.hStdOutput = CreateFile((const WCHAR*)((workingDirectory + "_tmpout").utf16()), GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, &sa, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); si.hStdError = CreateFile((const WCHAR*)((workingDirectory + "_tmperr").utf16()), GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, &sa, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); QString values = environment.toStringList().join('\0') + '\0'; if (! CreateProcess(NULL, (WCHAR*)(QString("\"%1\" %2").arg(executableFile, arguments).utf16()), NULL, &sa, TRUE, HIGH_PRIORITY_CLASS | CREATE_NO_WINDOW, (LPVOID)(values.toLocal8Bit().data()), (const WCHAR*)(workingDirectory.utf16()), &si, &pi)) { if (task->getStandardInputCheck()) CloseHandle(si.hStdInput); if (task->getStandardOutputCheck()) CloseHandle(si.hStdOutput); CloseHandle(si.hStdError); score = 0; result = CannotStartProgram; return; } PROCESS_MEMORY_COUNTERS_EX info; ZeroMemory(&info, sizeof(info)); info.cb = sizeof(info); if (memoryLimit != -1) { GetProcessMemoryInfo(pi.hProcess, (PROCESS_MEMORY_COUNTERS*)&info, sizeof(info)); if (qMax(info.PrivateUsage, info.PeakWorkingSetSize) > memoryLimit * 1024 * 1024) { TerminateProcess(pi.hProcess, 0); if (task->getStandardInputCheck()) CloseHandle(si.hStdInput); if (task->getStandardOutputCheck()) CloseHandle(si.hStdOutput); CloseHandle(si.hStdError); CloseHandle(pi.hProcess); CloseHandle(pi.hThread); score = 0; result = MemoryLimitExceeded; memoryUsed = timeUsed = -1; return; } } if (memoryLimit != -1) SetProcessWorkingSetSize(pi.hProcess, memoryLimit * 1024 * 1024 / 4, memoryLimit * 1024 * 1024); bool flag = false; QElapsedTimer timer; timer.start(); while (timer.elapsed() <= timeLimit + extraTime) { if (WaitForSingleObject(pi.hProcess, 0) == WAIT_OBJECT_0) { flag = true; break; } if (memoryLimit != -1) { GetProcessMemoryInfo(pi.hProcess, (PROCESS_MEMORY_COUNTERS*)&info, sizeof(info)); if (qMax(info.PrivateUsage, info.PeakWorkingSetSize) > memoryLimit * 1024 * 1024) { TerminateProcess(pi.hProcess, 0); if (task->getStandardInputCheck()) CloseHandle(si.hStdInput); if (task->getStandardOutputCheck()) CloseHandle(si.hStdOutput); CloseHandle(si.hStdError); CloseHandle(pi.hProcess); CloseHandle(pi.hThread); score = 0; result = MemoryLimitExceeded; memoryUsed = timeUsed = -1; return; } } QCoreApplication::processEvents(); if (stopJudging) { TerminateProcess(pi.hProcess, 0); if (task->getStandardInputCheck()) CloseHandle(si.hStdInput); if (task->getStandardOutputCheck()) CloseHandle(si.hStdOutput); CloseHandle(si.hStdError); CloseHandle(pi.hProcess); CloseHandle(pi.hThread); return; } Sleep(10); } if (! flag) { TerminateProcess(pi.hProcess, 0); if (task->getStandardInputCheck()) CloseHandle(si.hStdInput); if (task->getStandardOutputCheck()) CloseHandle(si.hStdOutput); CloseHandle(si.hStdError); CloseHandle(pi.hProcess); CloseHandle(pi.hThread); score = 0; result = TimeLimitExceeded; timeUsed = -1; return; } unsigned long exitCode; GetExitCodeProcess(pi.hProcess, &exitCode); if (exitCode != 0) { if (task->getStandardInputCheck()) CloseHandle(si.hStdInput); if (task->getStandardOutputCheck()) CloseHandle(si.hStdOutput); CloseHandle(si.hStdError); CloseHandle(pi.hProcess); CloseHandle(pi.hThread); score = 0; result = RunTimeError; QFile file(workingDirectory + "_tmperr"); if (file.open(QFile::ReadOnly)) { QTextStream stream(&file); message = stream.readAll(); file.close(); } memoryUsed = timeUsed = -1; return; } FILETIME creationTime, exitTime, kernelTime, userTime; GetProcessTimes(pi.hProcess, &creationTime, &exitTime, &kernelTime, &userTime); SYSTEMTIME realTime; FileTimeToSystemTime(&userTime, &realTime); timeUsed = realTime.wMilliseconds + realTime.wSecond * 1000 + realTime.wMinute * 60 * 1000 + realTime.wHour * 60 * 60 * 1000; GetProcessMemoryInfo(pi.hProcess, (PROCESS_MEMORY_COUNTERS*)&info, sizeof(info)); memoryUsed = info.PeakWorkingSetSize; if (task->getStandardInputCheck()) CloseHandle(si.hStdInput); if (task->getStandardOutputCheck()) CloseHandle(si.hStdOutput); CloseHandle(si.hStdError); CloseHandle(pi.hProcess); CloseHandle(pi.hThread); #endif #ifdef Q_OS_LINUX QFile::copy(":/watcher/watcher_unix", workingDirectory + "watcher"); QProcess::execute(QString("chmod +wx \"") + workingDirectory + "watcher" + "\""); QProcess *runner = new QProcess(this); QStringList argumentsList; argumentsList << QString("\"%1\" %2").arg(executableFile, arguments); if (task->getStandardInputCheck()) argumentsList << QFileInfo(inputFile).absoluteFilePath(); else argumentsList << ""; if (task->getStandardOutputCheck()) argumentsList << "_tmpout"; else argumentsList << ""; argumentsList << "_tmperr"; argumentsList << QString("%1").arg(timeLimit + extraTime); argumentsList << QString("%1").arg(memoryLimit); runner->setProcessEnvironment(environment); runner->setWorkingDirectory(workingDirectory); runner->start(workingDirectory + "watcher", argumentsList); if (! runner->waitForStarted(-1)) { delete runner; score = 0; result = CannotStartProgram; return; } bool flag = false; QElapsedTimer timer; timer.start(); while (timer.elapsed() <= timeLimit + extraTime) { if (runner->state() != QProcess::Running) { flag = true; break; } QCoreApplication::processEvents(); if (stopJudging) { runner->terminate(); runner->waitForFinished(-1); delete runner; return; } msleep(10); } if (! flag) { runner->terminate(); runner->waitForFinished(-1); delete runner; score = 0; result = TimeLimitExceeded; timeUsed = memoryUsed = -1; return; } int code = runner->exitCode(); if (code == 1) { delete runner; score = 0; result = CannotStartProgram; timeUsed = memoryUsed = -1; return; } if (code == 2) { delete runner; score = 0; result = RunTimeError; QFile file(workingDirectory + "_tmperr"); if (file.open(QFile::ReadOnly)) { QTextStream stream(&file); message = stream.readAll(); file.close(); } timeUsed = memoryUsed = -1; return; } QString out = QString::fromLocal8Bit(runner->readAllStandardOutput().data()); QTextStream stream(&out, QIODevice::ReadOnly); stream >> timeUsed >> memoryUsed; if (memoryUsed <= 0) memoryLimit = -1; if (code == 3) { delete runner; score = 0; result = TimeLimitExceeded; timeUsed = -1; return; } if (code == 4) { delete runner; score = 0; result = MemoryLimitExceeded; memoryUsed = -1; return; } delete runner; #endif }
void CoreApplication::terminateCompilation () { debug("terminate compilation"); QProcess* process = _compiler.getProcess(); process->terminate(); }