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 }
void Installer::ifupFinished(int) { QProcess *p = qobject_cast<QProcess*> (sender()); emit networkInterfaceUp(); p->deleteLater(); }
void Discover::processFinished(int exitCode, QProcess::ExitStatus exitStatus) { QProcess *process = static_cast<QProcess*>(sender()); // If the process was killed because guhd is shutting down...we dont't care any more about the result if (m_aboutToQuit) return; // Discovery if (process == m_discoveryProcess) { qCDebug(dcWallbe()) << "Discovery process finished"; process->deleteLater(); m_discoveryProcess = 0; QList<DeviceDescriptor> deviceDescriptors; if (exitCode != 0 || exitStatus != QProcess::NormalExit) { qCWarning(dcWallbe()) << "Network scan error:" << process->readAllStandardError(); emit devicesDiscovered(deviceDescriptors); return; } QByteArray outputData = process->readAllStandardOutput(); foreach (const Host &host, parseProcessOutput(outputData)) { DeviceDescriptor descriptor(wallbeEcoDeviceClassId, host.hostName(), host.address()); descriptor.setParams( ParamList() << Param(wallbeEcoIpParamTypeId, host.address())); deviceDescriptors.append(descriptor); }
void DevicePluginWifiDetector::processFinished(int exitCode, QProcess::ExitStatus exitStatus) { QProcess *p = static_cast<QProcess*>(sender()); p->deleteLater(); if (exitCode != 0 || exitStatus != QProcess::NormalExit) { qCWarning(dcWifiDetector) << "error performing network scan:" << p->readAllStandardError(); return; } QList<Device*> watchedDevices = deviceManager()->findConfiguredDevices(supportedDevices().first().id()); if (watchedDevices.isEmpty()) { return; } QStringList foundDevices; while(p->canReadLine()) { QString result = QString::fromLatin1(p->readLine()); if (result.startsWith("MAC Address:")) { QStringList lineParts = result.split(' '); if (lineParts.count() > 3) { QString addr = lineParts.at(2); foundDevices << addr.toLower(); } } } foreach (Device *device, watchedDevices) { bool wasInRange = device->stateValue(inRangeStateTypeId).toBool(); bool wasFound = foundDevices.contains(device->paramValue("mac").toString().toLower()); if (wasInRange != wasFound) { device->setStateValue(inRangeStateTypeId, wasFound); } }
void UbuntuUnityHack::GetError() { QProcess* get = qobject_cast<QProcess*>(sender()); if (!get) { return; } get->deleteLater(); }
void StaticHelpers::OpenFolderNautilus(QString& file) { QProcess* nautilus = new QProcess(); QStringList arguments; arguments << "--browser" << file; nautilus->startDetached("nautilus", arguments); nautilus->deleteLater(); }
void SysTray::ubuntu_unity_hack_getError() { QProcess* get = qobject_cast<QProcess*>(sender()); if (!get) return; get->deleteLater(); }
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(); }
bool ResultsExporter::exportResults() { ResultsExporterSettings ss = settings(); if(!QDir().mkpath(ss.exportDir())) { qfError() << "Cannot create export dir:" << ss.exportDir(); return false; } qfInfo() << "ResultsExporter export dir:" << ss.exportDir(); if(ss.outputFormat() == static_cast<int>(ResultsExporterSettings::OutputFormat::CSOS)) { int current_stage = eventPlugin()->currentStageId(); QString fn = ss.exportDir() + "/results-csos.txt"; runsPlugin()->exportResultsCsosStage(current_stage, fn); return true; } if(ss.outputFormat() == static_cast<int>(ResultsExporterSettings::OutputFormat::IofXml3)) { int current_stage = eventPlugin()->currentStageId(); QString fn = ss.exportDir() + "/results-csos.txt"; runsPlugin()->exportResultsIofXml30Stage(current_stage, fn); return true; } else if(ss.outputFormat() == static_cast<int>(ResultsExporterSettings::OutputFormat::HtmlMulti)) { quickevent::core::exporters::StageResultsHtmlExporter exp; exp.setOutDir(ss.exportDir()); exp.generateHtml(); QString cmd = ss.whenFinishedRunCmd(); if(!cmd.isEmpty()) { qfInfo() << "Starting process:" << cmd; QProcess *proc = new QProcess(); connect(proc, &QProcess::readyReadStandardOutput, [proc]() { QByteArray ba = proc->readAllStandardOutput(); qfInfo().noquote() << "PROC stdout:" << ba; }); connect(proc, &QProcess::readyReadStandardError, [proc]() { QByteArray ba = proc->readAllStandardError(); qfWarning().noquote() << "PROC stderr:" << ba; }); connect(proc, QOverload<int, QProcess::ExitStatus>::of(&QProcess::finished), [proc](int exit_code, QProcess::ExitStatus exit_status) { if(exit_status == QProcess::ExitStatus::CrashExit) qfError() << "PROC crashed"; else qfInfo() << "PROC finished with exit code:" << exit_code; proc->deleteLater(); }); proc->start(cmd); } return true; } qfError() << "Unsupported output format:" << ss.outputFormat(); return false; }
QProcess *getInterpreterProcess( QString path ) { QProcess *antProcess; antProcess = new QProcess( ); antProcess->start( path ); if (!antProcess->waitForStarted()) { antProcess->deleteLater(); antProcess = NULL; } return antProcess; }
void run() { QStringList list; QString text; QProcess ping; QStringList result; QRegExp rx("(\\d+)% loss"); while(true) { if(window->stop) { window->stop = false; window->StartButton->setEnabled(true); window->StopButton->setEnabled(false); window->IPInput->setEnabled(true); break; } #ifdef _WIN32 ping.start("ping.exe " + window->IPInput->text() + " -n 10"); #else ping.start("ping " + window->IPInput->text() + " -c 10"); #endif ping.waitForFinished(); text = ping.readAll(); if (!text.isEmpty()) { list = text.split("\n"); if(list.length() < 5) { window->stop = true; } else { result = list.filter("unreachable"); if(result.length() > 0) { window->stop = true; } else { result = list.filter("loss"); if(result.length() > 0) { if(rx.indexIn(result[0], 0) != -1) { if(rx.cap(1) == "100") { window->stop = true; } } } } } } ping.deleteLater(); } }
//------------------------------------------------------------------------------------------------ void Window::runAddGateway(QString gw) { QProcess *route = new QProcess(this); QString program = "route"; QStringList arguments; #ifdef Q_OS_WIN arguments << "add" << "0.0.0.0" << "mask" << "0.0.0.0" << gw; #endif route->start(program, arguments); route->waitForFinished(); // start ping every 2 seconds pingTimer->start(2000); QString tooltip; if (route->exitCode() == 0) { if (showBalloons->isChecked()) trayIcon->showMessage(tr("Current gateway:"), gw, QSystemTrayIcon::Information, 5000); routeError.clear(); currentGw = gw; tooltip = tr("Gateway:") + " " + currentGw; gwInfo->setText(tr("Current gateway: ") + "<b>" + currentGw + "</b>"); } else { if (showBalloons->isChecked()) trayIcon->showMessage(tr("Cannot switch gateway"), tr("Press here for additional information"), QSystemTrayIcon::Critical, 5000); #ifdef Q_OS_WIN QByteArray ba = route->readAllStandardError(); QTextCodec *codec = QTextCodec::codecForName("IBM866"); routeError = codec->toUnicode(ba); #else routeError = route->readAllStandardError(); #endif tooltip = tr("Gateway: none"); gwInfo->setText(tr("Current gateway: ") + "<b>" + tr("none") + "</b>"); } trayIcon->setToolTip(tooltip); route->deleteLater(); }
void CheckDirModel::getFileInfoResult() { #ifdef Q_WS_MAC QProcess* p = qobject_cast< QProcess* >( sender() ); Q_ASSERT( p ); QByteArray res = p->readAll().trimmed(); // 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::startDetached( QString( "SetFile -a v %1" ).arg( s_macVolumePath ) ); m_shownVolumes = true; } p->deleteLater(); #endif }
void PluginDumper::qmlPluginTypeDumpError(QProcess::ProcessError) { QProcess *process = qobject_cast<QProcess *>(sender()); if (!process) return; process->deleteLater(); const QString libraryPath = m_runningQmldumps.take(process); Core::MessageManager *messageManager = Core::MessageManager::instance(); const QString errorMessages = process->readAllStandardError(); messageManager->printToOutputPane(qmldumpErrorMessage(libraryPath, errorMessages)); if (!libraryPath.isEmpty()) { const Snapshot snapshot = m_modelManager->snapshot(); LibraryInfo libraryInfo = snapshot.libraryInfo(libraryPath); libraryInfo.setPluginTypeInfoStatus(LibraryInfo::DumpError, qmldumpFailedMessage(errorMessages)); m_modelManager->updateLibraryInfo(libraryPath, libraryInfo); } }
void ServerManager::serverFinish(int exitCode, QProcess::ExitStatus exitStatus) { QProcess *server = qobject_cast<QProcess *>(sender()); if (server) { //server->close(); // long blocking.. server->deleteLater(); int id = serversStatus.take(server); if (isRunning()) { if (exitCode != 127) { // 127 : for auto reloading tSystemError("Detected a server crashed. exitCode:%d exitStatus:%d", exitCode, (int)exitStatus); } startServer(id); } else { tSystemDebug("Detected normal exit of server. exitCode:%d", exitCode); if (serversStatus.count() == 0) { Tf::app()->exit(-1); } } } }
void PluginDumper::qmlPluginTypeDumpDone(int exitCode) { QProcess *process = qobject_cast<QProcess *>(sender()); if (!process) return; process->deleteLater(); const QString libraryPath = m_runningQmldumps.take(process); const Snapshot snapshot = m_modelManager->snapshot(); LibraryInfo libraryInfo = snapshot.libraryInfo(libraryPath); if (exitCode != 0) { Core::MessageManager *messageManager = Core::MessageManager::instance(); const QString errorMessages = process->readAllStandardError(); messageManager->printToOutputPane(qmldumpErrorMessage(libraryPath, errorMessages)); libraryInfo.setPluginTypeInfoStatus(LibraryInfo::DumpError, qmldumpFailedMessage(errorMessages)); } const QByteArray output = process->readAllStandardOutput(); QString error; QString warning; QList<FakeMetaObject::ConstPtr> objectsList = parseHelper(output, &error, &warning); if (exitCode == 0) { if (!error.isEmpty()) { libraryInfo.setPluginTypeInfoStatus(LibraryInfo::DumpError, tr("Type dump of C++ plugin failed. Parse error:\n'%1'").arg(error)); } else { libraryInfo.setMetaObjects(objectsList); // ### disabled code path for running qmldump to get Qt's builtins // if (libraryPath.isEmpty()) // Interpreter::CppQmlTypesLoader::builtinObjects.append(objectsList); libraryInfo.setPluginTypeInfoStatus(LibraryInfo::DumpDone); } if (!warning.isEmpty()) printParseWarnings(libraryPath, warning); } if (!libraryPath.isEmpty()) m_modelManager->updateLibraryInfo(libraryPath, libraryInfo); }
//------------------------------------------------------------------------------------------------ void Window::writeGateway() { #ifdef Q_OS_WIN if (!currentGw.isEmpty()) { QProcess *route = new QProcess(this); QString program = "route"; QStringList arguments; arguments << "delete" << "0.0.0.0"; route->start(program, arguments); route->waitForFinished(); arguments.clear(); arguments << "-p" << "add" << "0.0.0.0" << "mask" << "0.0.0.0" << currentGw; route->start(program, arguments); route->waitForFinished(); route->deleteLater(); } #endif }
//------------------------------------------------------------------------------------------------ void Window::runClearGateway() { // stop ping before switching gateway pingTimer->stop(); QProcess *route = new QProcess(this); QString program = "route"; QStringList arguments; #ifdef Q_OS_WIN arguments << "delete" << "0.0.0.0"; #endif route->start(program, arguments); route->waitForFinished(); route->deleteLater(); currentGw.clear(); trayIcon->setToolTip(tr("Gateway: none")); gwInfo->setText(tr("Current gateway: ") + "<b>" + tr("none") + "</b>"); setInetStatus(imNoGateway); if (showBalloons->isChecked()) trayIcon->showMessage(tr("Current gateway:"), tr("none"), QSystemTrayIcon::Information, 5000); }
void SysTray::ubuntu_unity_hack_getFinished(int exit_code) { QProcess* get = qobject_cast<QProcess*>(sender()); if (!get) return; get->deleteLater(); if (exit_code != 0) { // Probably not running in Unity. return; } QByteArray whitelist = get->readAllStandardOutput(); Debug::debug() << "Unity whitelist is" << whitelist; int index = whitelist.lastIndexOf(']'); if (index == -1 || whitelist.contains("'yarock'")) return; whitelist = whitelist.left(index) + QString(", 'yarock'").toUtf8() + whitelist.mid(index); Debug::debug() << "Setting unity whitelist to" << whitelist; QProcess* set = new QProcess(this); connect(set, SIGNAL(finished(int)), set, SLOT(deleteLater())); set->start(kGSettingsFileName, QStringList() << "set" << kUnityPanel << kUnitySystrayWhitelist << whitelist); Debug::debug() << "Yarock has added itself to the Unity system tray" << "whitelist, but this won't take effect until the next time" << "you log out and log back in."; }
void MainWindowVideos::selected(IVideo * pVideo) { // TODO merge with logic from channel QWidget * lPopup = new QWidget(this, Qt::Popup); QPushButton * lButton; lPopup->setAttribute(Qt::WA_DeleteOnClose); lPopup->setLayout(new QBoxLayout(QBoxLayout::TopToBottom, lPopup)); lButton = new QPushButton(lPopup); lButton->setText("Watch!"); QObject::connect(lButton, &QPushButton::clicked, [pVideo,lPopup] { lPopup->setEnabled(false); QUrl lUrl = pVideo->videoUrl(IVideo::URL_VIDEO_DIRECT); lPopup->close(); if (!lUrl.isValid()) return; QString lProgram; QStringList lArguments; lProgram = "/usr/bin/mpv"; if (QFile::exists(lProgram)) { lArguments << "--untimed"; lArguments << "--quiet"; } else { lProgram = "C:\\Program Files\\VideoLAN\\VLC\\vlc.exe"; if (!QFile::exists(lProgram)) lProgram = "C:\\Program Files\\VLC\\vlc.exe"; if (!QFile::exists(lProgram)) lProgram = "C:\\Program Files (x86)\\VideoLAN\\VLC\\vlc.exe"; if (!QFile::exists(lProgram)) lProgram = "C:\\Program Files (x86)\\VLC\\vlc.exe"; } lArguments << lUrl.toString(QUrl::FullyEncoded); QProcess * lProcess = new QProcess(); QObject::connect(lProcess, (void (QProcess::*) (int))&QProcess::finished, [lProcess] (int pExitCode) { lProcess->deleteLater(); }); lProcess->setProcessChannelMode(QProcess::ForwardedChannels); lProcess->setProgram(lProgram); lProcess->setArguments(lArguments); lProcess->start(); }); lPopup->layout()->addWidget(lButton); lButton = new QPushButton(lPopup); lButton->setText("Open in browser"); QObject::connect(lButton, &QPushButton::clicked, [pVideo,lPopup] { lPopup->setEnabled(false); QUrl lUrl = pVideo->videoUrl(IVideo::URL_VIDEO_WEBSITE); lPopup->close(); if (!lUrl.isValid()) return; QDesktopServices::openUrl(lUrl); }); lPopup->layout()->addWidget(lButton); lButton = new QPushButton(lPopup); lButton->setText("Download ..."); QObject::connect(lButton, &QPushButton::clicked, [pVideo,lPopup] { lPopup->setEnabled(false); IDownloader * lDownloader = pVideo->downloader(); lPopup->close(); if (lDownloader == nullptr) return; DownloadWindow * lWindow = new DownloadWindow(lDownloader); lWindow->setAttribute(Qt::WA_DeleteOnClose); lWindow->show(); }); lPopup->layout()->addWidget(lButton); lPopup->move(QCursor::pos() - QPoint(5, 10)); lPopup->show(); }
bool RdpView::start() { m_containerWidget->show(); if (m_url.userName().isEmpty()) { QString userName; bool ok = false; userName = QInputDialog::getText(this, i18n("Enter Username"), i18n("Please enter the username you would like to use for login."), QLineEdit::Normal, Settings::defaultRdpUserName(), &ok); if (ok) { m_url.setUserName(userName); } } if (!m_url.userName().isEmpty()) { const bool useLdapLogin = Settings::recognizeLdapLogins() && m_url.userName().contains(QLatin1Char('\\')); qCDebug(KRDC) << "Is LDAP login:"******"Access to the system requires a password.")); if (dialog.exec() == KPasswordDialog::Accepted) { m_url.setPassword(dialog.password()); if (m_hostPreferences->walletSupport()) { saveWalletPassword(dialog.password(), useLdapLogin); } } } } // Check the version of FreeRDP so we can use pre-1.1 switches if needed QProcess *xfreeRDPVersionCheck = new QProcess(this); xfreeRDPVersionCheck->start(QStringLiteral("xfreerdp"), QStringList(QStringLiteral("--version"))); xfreeRDPVersionCheck->waitForFinished(); QString versionOutput = QString::fromUtf8(xfreeRDPVersionCheck->readAllStandardOutput().constData()); xfreeRDPVersionCheck->deleteLater(); m_process = new QProcess(m_container); QStringList arguments; int width, height; if (m_hostPreferences->width() > 0) { width = m_hostPreferences->width(); height = m_hostPreferences->height(); } else { width = this->parentWidget()->size().width(); height = this->parentWidget()->size().height(); } m_containerWidget->setFixedWidth(width); m_containerWidget->setFixedHeight(height); setMaximumSize(width, height); if (versionOutput.contains(QLatin1String(" 1.0"))) { qCDebug(KRDC) << "Use FreeRDP 1.0 compatible arguments"; arguments << QStringLiteral("-g") << QString::number(width) + QLatin1Char('x') + QString::number(height); arguments << QStringLiteral("-k") << keymapToXfreerdp(m_hostPreferences->keyboardLayout()); if (!m_url.userName().isEmpty()) { // if username contains a domain, it needs to be set with another parameter if (m_url.userName().contains(QLatin1Char('\\'))) { const QStringList splittedName = m_url.userName().split(QLatin1Char('\\')); arguments << QStringLiteral("-d") << splittedName.at(0); arguments << QStringLiteral("-u") << splittedName.at(1); } else { arguments << QStringLiteral("-u") << m_url.userName(); } } else { arguments << QStringLiteral("-u") << QStringLiteral(""); } arguments << QStringLiteral("-D"); // request the window has no decorations arguments << QStringLiteral("-X") << QString::number(m_container->winId()); arguments << QStringLiteral("-a") << QString::number((m_hostPreferences->colorDepth() + 1) * 8); switch (m_hostPreferences->sound()) { case 1: arguments << QStringLiteral("-o"); break; case 0: arguments << QStringLiteral("--plugin") << QStringLiteral("rdpsnd"); break; case 2: default: break; } if (!m_hostPreferences->shareMedia().isEmpty()) { QStringList shareMedia; shareMedia << QStringLiteral("--plugin") << QStringLiteral("rdpdr") << QStringLiteral("--data") << QStringLiteral("disk:media:") + m_hostPreferences->shareMedia() << QStringLiteral("--"); arguments += shareMedia; } QString performance; switch (m_hostPreferences->performance()) { case 0: performance = QLatin1Char('m'); break; case 1: performance = QLatin1Char('b'); break; case 2: performance = QLatin1Char('l'); break; default: break; } arguments << QStringLiteral("-x") << performance; if (m_hostPreferences->console()) { arguments << QStringLiteral("-0"); } if (m_hostPreferences->remoteFX()) { arguments << QStringLiteral("--rfx"); } if (!m_hostPreferences->extraOptions().isEmpty()) { const QStringList additionalArguments = KShell::splitArgs(m_hostPreferences->extraOptions()); arguments += additionalArguments; } // krdc has no support for certificate management yet; it would not be possbile to connect to any host: // "The host key for example.com has changed" ... // "Add correct host key in ~/.freerdp/known_hosts to get rid of this message." arguments << QStringLiteral("--ignore-certificate"); // clipboard sharing is activated in KRDC; user can disable it at runtime arguments << QStringLiteral("--plugin") << QStringLiteral("cliprdr"); arguments << QStringLiteral("-t") << QString::number(m_port); arguments << m_host; qCDebug(KRDC) << "Starting xfreerdp with arguments: " << arguments.join(QStringLiteral(" ")); arguments.removeLast(); // host must be last, remove and re-add it after the password if (!m_url.password().isNull()) arguments << QStringLiteral("-p") << m_url.password(); arguments << m_host; } else { qCDebug(KRDC) << "Use FreeRDP 1.1+ compatible arguments"; arguments << QStringLiteral("-decorations"); arguments << QStringLiteral("/w:") + QString::number(width); arguments << QStringLiteral("/h:") + QString::number(height); arguments << QStringLiteral("/kbd:") + keymapToXfreerdp(m_hostPreferences->keyboardLayout()); if (!m_url.userName().isEmpty()) { // if username contains a domain, it needs to be set with another parameter if (m_url.userName().contains(QLatin1Char('\\'))) { const QStringList splittedName = m_url.userName().split(QLatin1Char('\\')); arguments << QStringLiteral("/d:") + splittedName.at(0); arguments << QStringLiteral("/u:") + splittedName.at(1); } else { arguments << QStringLiteral("/u:") + m_url.userName(); } } else { arguments << QStringLiteral("/u:"); } arguments << QStringLiteral("/parent-window:") + QString::number(m_container->winId()); arguments << QStringLiteral("/bpp:") + QString::number((m_hostPreferences->colorDepth() + 1) * 8); arguments << QStringLiteral("/audio-mode:") + QString::number(m_hostPreferences->sound()); switch (m_hostPreferences->soundSystem()) { case 0: arguments << QStringLiteral("/sound:sys:alsa"); break; case 1: arguments << QStringLiteral("/sound:sys:pulse"); break; default: break; } if (!m_hostPreferences->shareMedia().isEmpty()) { QStringList shareMedia; shareMedia << QStringLiteral("/drive:media,") + m_hostPreferences->shareMedia(); arguments += shareMedia; } QString performance; switch (m_hostPreferences->performance()) { case 0: performance = QStringLiteral("modem"); break; case 1: performance = QStringLiteral("broadband"); break; case 2: performance = QStringLiteral("lan"); break; default: break; } arguments << QStringLiteral("/network:") + performance; if (m_hostPreferences->console()) { arguments << QStringLiteral("/admin"); } if (m_hostPreferences->remoteFX()) { arguments << QStringLiteral("/rfx"); } if (!m_hostPreferences->extraOptions().isEmpty()) { const QStringList additionalArguments = KShell::splitArgs(m_hostPreferences->extraOptions()); arguments += additionalArguments; } // krdc has no support for certificate management yet; it would not be possbile to connect to any host: // "The host key for example.com has changed" ... // "Add correct host key in ~/.freerdp/known_hosts to get rid of this message." arguments << QStringLiteral("/cert-ignore"); // clipboard sharing is activated in KRDC; user can disable it at runtime arguments << QStringLiteral("+clipboard"); arguments << QStringLiteral("/port:") + QString::number(m_port); arguments << QStringLiteral("/v:") + m_host; qCDebug(KRDC) << "Starting xfreerdp with arguments: " << arguments.join(QStringLiteral(" ")); //avoid printing the password in debug if (!m_url.password().isNull()) { arguments << QStringLiteral("/p:") + m_url.password(); } } setStatus(Connecting); connect(m_process, SIGNAL(error(QProcess::ProcessError)), SLOT(processError(QProcess::ProcessError))); connect(m_process, SIGNAL(readyReadStandardError()), SLOT(receivedStandardError())); connect(m_process, SIGNAL(readyReadStandardOutput()), SLOT(receivedStandardOutput())); connect(m_process, SIGNAL(finished(int, QProcess::ExitStatus)), SLOT(connectionClosed())); connect(m_process, SIGNAL(started()), SLOT(connectionOpened())); m_process->start(QStringLiteral("xfreerdp"), arguments); return true; }
bool RunProcessAsAdmin(const QString &fullExecutablePath, const QStringList ¶ms, std::function<void()> finishedCallback) { #if defined(Q_OS_WIN32) std::wstring wideExe = fullExecutablePath.toStdWString(); std::wstring wideParams = params.join(QChar(' ')).toStdWString(); SHELLEXECUTEINFOW info = {}; info.cbSize = sizeof(info); info.fMask = SEE_MASK_NOCLOSEPROCESS; info.lpVerb = L"runas"; info.lpFile = wideExe.c_str(); info.lpParameters = wideParams.c_str(); info.nShow = SW_SHOWNORMAL; ShellExecuteExW(&info); if((uintptr_t)info.hInstApp > 32 && info.hProcess != NULL) { if(finishedCallback) { HANDLE h = info.hProcess; // do the wait on another thread LambdaThread *thread = new LambdaThread([h, finishedCallback]() { WaitForSingleObject(h, 30000); CloseHandle(h); GUIInvoke::call(finishedCallback); }); thread->selfDelete(true); thread->start(); } else { CloseHandle(info.hProcess); } return true; } return false; #else // try to find a way to run the application elevated. const QString graphicalSudo[] = { "pkexec", "kdesudo", "gksudo", "beesu", }; // if none of the graphical options, then look for sudo and either const QString termEmulator[] = { "x-terminal-emulator", "gnome-terminal", "knosole", "xterm", }; for(const QString &sudo : graphicalSudo) { QString inPath = QStandardPaths::findExecutable(sudo); // can't find in path if(inPath.isEmpty()) continue; QProcess *process = new QProcess; QStringList sudoParams; sudoParams << fullExecutablePath; for(const QString &p : params) sudoParams << p; qInfo() << "Running" << sudo << "with params" << sudoParams; // run with sudo process->start(sudo, sudoParams); // when the process exits, call the callback and delete QObject::connect(process, OverloadedSlot<int>::of(&QProcess::finished), [process, finishedCallback](int exitCode) { process->deleteLater(); GUIInvoke::call(finishedCallback); }); return true; } QString sudo = QStandardPaths::findExecutable("sudo"); if(sudo.isEmpty()) { qCritical() << "Couldn't find graphical or terminal sudo program!\n" << "Please run " << fullExecutablePath << "with args" << params << "manually."; return false; } for(const QString &term : termEmulator) { QString inPath = QStandardPaths::findExecutable(term); // can't find in path if(inPath.isEmpty()) continue; QProcess *process = new QProcess; // run terminal sudo with emulator QStringList termParams; termParams << "-e" << QString("bash -c 'sudo %1 %2'").arg(fullExecutablePath).arg(params.join(QChar(' '))); process->start(term, termParams); // when the process exits, call the callback and delete QObject::connect(process, OverloadedSlot<int>::of(&QProcess::finished), [process, finishedCallback](int exitCode) { process->deleteLater(); GUIInvoke::call(finishedCallback); }); return true; } qCritical() << "Couldn't find graphical or terminal emulator to launch sudo.\n" << "Please run " << fullExecutablePath << "with args" << params << "manually."; return false; #endif }
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; }
void Installer::installpkg() { QString url = sender()->property("url").toString(); uint bsize = sender()->property("bsize").toUInt(); wait = new QProgressDialog(this); wait->setModal(true); wait->setMaximum(bsize+1); wait->setLabelText(QString("Downloading ") + url + " ..."); wait->show(); reply = qnam.get(QNetworkRequest(QUrl(url))); reply->setReadBufferSize(bsize*2); QEventLoop loop; connect(reply, SIGNAL(finished()), &loop, SLOT(quit())); connect(reply, SIGNAL(downloadProgress(qint64,qint64)), this, SLOT(dlProgress(qint64,qint64))); loop.exec(); QString appdata_path = DATALOCATION; QDir().mkpath(appdata_path); QDir appdata(appdata_path); appdata.remove("data.tmp"); appdata.remove("data.tar"); appdata.remove("data.tar.xz"); appdata.remove("debian-binary"); appdata.remove("control.tar.gz"); QFile file(appdata.filePath("data.tmp")); file.open(QIODevice::WriteOnly); file.write(reply->readAll()); file.close(); QDir exep(QCoreApplication::applicationDirPath()); wait->setLabelText("Unpacking ..."); QProcess *up = new QProcess(this); up->setWorkingDirectory(appdata_path); #if defined(Q_OS_WIN) || defined(Q_OS_MAC) up->start(exep.absoluteFilePath("7z"), QStringList() << "x" << "-y" << "data.tmp"); #else up->start("ar", QStringList() << "x" << "data.tmp"); #endif up->waitForStarted(); up->waitForFinished(); up->deleteLater(); if (appdata.exists("data.tar")) { QProcess *up = new QProcess(this); up->setWorkingDirectory(appdata_path); up->start(exep.absoluteFilePath("7z"), QStringList() << "x" << "-y" << "data.tar"); up->waitForStarted(); up->waitForFinished(); up->deleteLater(); } if (appdata.exists("data.tar.xz")) { QProcess *up = new QProcess(this); up->setWorkingDirectory(appdata_path); up->start("tar", QStringList() << "-Jxf" << "data.tar.xz"); up->waitForStarted(); up->waitForFinished(); up->deleteLater(); } wait->close(); wait->deleteLater(); appdata.remove("data.tmp"); appdata.remove("data.tar"); appdata.remove("data.tar.xz"); appdata.remove("debian-binary"); appdata.remove("control.tar.gz"); QSettings conf; conf.setValue(sender()->property("name").toString(), sender()->property("lm").toString()); }
void FilePrinter::doPrintFile( QPrinter &printer, const QString &file, FileDeletePolicy fileDeletePolicy, PageSelectPolicy pageSelectPolicy, const QString &pageRange ) { if (!QFile::exists(file)) { return; } bool doDeleteFile = (fileDeletePolicy == FilePrinter::SystemDeletesFiles); if ( printer.printerState() == QPrinter::Aborted || printer.printerState() == QPrinter::Error ) { if ( doDeleteFile ) { QFile::remove( file ); } return; } // Print to a printer via lpr command //Decide what executable to use to print with, need the CUPS version of lpr if available //Some distros name the CUPS version of lpr as lpr-cups or lpr.cups so try those first //before default to lpr, or failing that to lp QString exe; if ( !QStandardPaths::findExecutable(QStringLiteral("lpr-cups")).isEmpty() ) { exe = QStringLiteral("lpr-cups"); } else if ( !QStandardPaths::findExecutable(QStringLiteral("lpr.cups")).isEmpty() ) { exe = QStringLiteral("lpr.cups"); } else if ( !QStandardPaths::findExecutable(QStringLiteral("lpr")).isEmpty() ) { exe = QStringLiteral("lpr"); } else if ( !QStandardPaths::findExecutable(QStringLiteral("lp")).isEmpty() ) { exe = QStringLiteral("lp"); } else { if ( doDeleteFile ) { QFile::remove( file ); } return; } bool useCupsOptions = cupsAvailable(); QStringList argList = printArguments( printer, fileDeletePolicy, pageSelectPolicy, useCupsOptions, pageRange, exe ) << file; QProcess *process = new QProcess(); QObject::connect(process, static_cast<void (QProcess::*)(QProcess::ProcessError)>(&QProcess::error), [=](QProcess::ProcessError) { if ( doDeleteFile ) { QFile::remove( file ); } process->deleteLater(); }); QObject::connect(process, static_cast<void (QProcess::*)(int, QProcess::ExitStatus)>(&QProcess::finished), [=](int exitCode, QProcess::ExitStatus exitStatus) { if ( doDeleteFile && (exitStatus != QProcess::NormalExit || exitCode != 0) ) { // lpr failed, so delete the temporary file in case it still exists. // In case of success, we let lpr delete it, it knows best when it is safe to do so. // (lpr queues jobs asynchronously.) QFile::remove( file ); } process->deleteLater(); }); process->start( exe, argList ); }