void CommandHandler::processCommand(const Command &command) const { QWebEngineView *webView = ElectricWebView::instance()->webView(); if (command.name() == "load") { if (command.arguments().isEmpty()) webView->load(QUrl("about:blank")); else webView->load(QUrl(command.arguments().first())); } else if (command.name() == "stop") { webView->stop(); } else if (command.name() == "reload") { webView->reload(); } else if (command.name() == "back") { webView->back(); } else if (command.name() == "forward") { webView->forward(); } else if (command.name() == "open") { QString mode = command.arguments().value(0); if (mode == "maximized") { webView->showMaximized(); } else if (mode == "fullscreen") { webView->setGeometry(qApp->desktop()->screenGeometry()); webView->showFullScreen(); } } else if (command.name() == "close") { webView->close(); } else if (command.name() == "current_url") { command.sendResponse(webView->url().toString().toLocal8Bit()); } else if (command.name() == "set_html") { QString type = command.arguments().value(0); QString value = command.arguments().mid(1, -1).join(' '); if (type == "string") { webView->page()->setHtml(value.toLocal8Bit()); } else if (type == "file") { QFile file(value); file.open(QFile::ReadOnly); webView->page()->setHtml(file.readAll()); } } else if (command.name() == "get_html") { QString format = command.arguments().value(0); QEventLoop loop; if (format == "html") { webView->page()->toHtml([&command, &loop](const QString &html) { if (!command.client().isNull()) { command.sendResponse(QUrl::toPercentEncoding(html)); if (command.isGetter()) command.client()->close(); } loop.quit(); }); } else if (format == "text") { webView->page()->toPlainText([&command, &loop](const QString &text) { if (!command.client().isNull()) { command.sendResponse(QUrl::toPercentEncoding(text)); if (command.isGetter()) command.client()->close(); } loop.quit(); }); } 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); } }
void QtDcmConvert::convert() { if (QtDcmPreferences::instance()->useDcm2nii()) { QString program = QtDcmPreferences::instance()->getDcm2niiPath(); QStringList arguments; arguments << "-x" << "N"; arguments << "-r" << "N"; arguments << "-g" << "N"; arguments << "-o" << d->outputDirectory << d->inputDirectory; QProcess * process = new QProcess(this); process->setStandardOutputFile(d->tempDirectory + QDir::separator() + "logs" + QDir::separator() + d->serieUID + ".txt"); process->start(program, arguments); process->waitForFinished(); delete process; } else { typedef signed short PixelType; const unsigned int Dimension = 3; typedef itk::Image< PixelType, Dimension > ImageType; typedef itk::ImageSeriesReader< ImageType > ReaderType; typedef itk::ImageFileWriter<ImageType> WriterType; typedef itk::GDCMImageIO ImageIOType; typedef itk::GDCMSeriesFileNames NamesGeneratorType; typedef std::vector< std::string > FileNamesContainer; typedef std::vector< std::string > SeriesIdContainer; // ImageType::Pointer image = 0; ReaderType::Pointer reader = ReaderType::New(); ImageIOType::Pointer dicomIO = ImageIOType::New(); NamesGeneratorType::Pointer inputNames = NamesGeneratorType::New(); inputNames->SetUseSeriesDetails ( true ); inputNames->AddSeriesRestriction ( "0008|0021" ); inputNames->AddSeriesRestriction ( "0020,0037" ); inputNames->LoadSequencesOn(); inputNames->LoadPrivateTagsOn(); inputNames->SetInputDirectory ( d->inputDirectory.toStdString() ); try { const SeriesIdContainer & seriesUID = inputNames->GetSeriesUIDs(); std::string seriesIdentifier = seriesUID.begin()->c_str(); FileNamesContainer filenames = inputNames->GetFileNames ( seriesIdentifier ); dicomIO->SetFileName ( filenames.begin()->c_str() ); try { dicomIO->ReadImageInformation(); } catch ( itk::ExceptionObject &e ) { qDebug() << e.GetDescription(); return; } reader->UseStreamingOn(); reader->SetFileNames ( filenames ); reader->SetImageIO ( dicomIO ); try { reader->Update(); } catch ( itk::ExceptionObject &excp ) { std::cerr << excp << std::endl; return; } // IteratorType itOut; // // image = reader->GetOutput(); // // RegionType region; // region.SetSize ( 0, image->GetLargestPossibleRegion().GetSize() [0] ); // region.SetSize ( 1, image->GetLargestPossibleRegion().GetSize() [1] ); // region.SetSize ( 2, image->GetLargestPossibleRegion().GetSize() [2] ); // image->SetRegions ( region ); // image->Allocate(); // SpacingType spacing; // spacing[0] = image->GetSpacing() [0]; // spacing[1] = image->GetSpacing() [1]; // spacing[2] = image->GetSpacing() [2]; // spacing[3] = 1; // image->SetSpacing ( spacing ); // PointType origin; // origin[0] = image->GetOrigin() [0]; // origin[1] = image->GetOrigin() [1]; // origin[2] = image->GetOrigin() [2]; // origin[3] = 0; // image->SetOrigin ( origin ); // DirectionType direction; // for ( unsigned int i=0; i<4; i++ ) // for ( unsigned int j=0; j<4; j++ ) // { // if ( ( i < 3 ) && ( j < 3 ) ) // direction[i][j] = image->GetDirection() [i][j]; // else // direction[i][j] = ( i == j ) ? 1 : 0; // } // image->SetDirection ( direction ); // itOut = IteratorType ( image, region ); // // image->SetMetaDataDictionary ( dicomIO->GetMetaDataDictionary() ); // // // itk::ImageRegionIterator<ImageType> itIn ( image, image->GetLargestPossibleRegion() ); // while ( !itIn.IsAtEnd() ) // { // itOut.Set ( itIn.Get() ); // ++itIn; // ++itOut; // } WriterType::Pointer writer = WriterType::New(); QString completeFilename = d->outputDirectory + QDir::separator() + d->outputFilename; writer->SetFileName ( completeFilename.toStdString() ); writer->SetInput ( reader->GetOutput() ); // writer->SetInput ( image ); try { writer->Update(); } catch ( itk::ExceptionObject &ex ) { std::cout << ex << std::endl; return; } } catch ( itk::ExceptionObject &ex ) { std::cout << ex << std::endl; return; } } }
int main(int argc, char ** argv) { QString appDir = QFileInfo(argv[0]).absolutePath(); appDir += "/texiteasyPath.txt"; FILE * file = fopen(appDir.toLatin1().data(), "r"); //FILE * log = fopen("C:\\Users\\Wybot\\AppData\\Roaming\\TexitEasy\\log.txt", "w"); //fwrite(appDir.toLatin1().data(), sizeof(char), appDir.toLatin1().size(), log); if(!file) { //fwrite("Unable to open", sizeof(char), 14, log); return 1; } char start[5000]; size_t s = fread(start, sizeof(char), 5000, file); start[s] = '\0'; QtSingleCoreApplication a("TexitEasy",argc, argv); QProcess* proc = new QProcess(); QString str(start); QStringList args = a.arguments(); args.pop_front(); /*for(int i = 1; i < argc; ++i) { args << argv[i]; }*/ if ( a.isRunning() && !args.contains("-n") && !args.contains("--new-window")) { proc->start(str+"/TexitEasy.exe", args); return 0; } QCoreApplication::setOrganizationName("TexitEasy"); QCoreApplication::setOrganizationDomain("texiteasy.com"); QCoreApplication::setApplicationName("TexitEasy"); QSettings::setDefaultFormat(QSettings::IniFormat); //fwrite(start, sizeof(char), s, log); QString dataLocation = QStandardPaths::writableLocation(QStandardPaths::DataLocation); QFile updateFile(dataLocation+"/updateFiles.zip"); if(updateFile.exists()) { QStringList l; //l << str+"/texiteasy_upgrade.exe"; l << dataLocation+"/updateFiles.zip"; l << str; proc->start(str+"/texiteasy_upgrade.exe", l); return 0; } QFile updateFileExe(dataLocation+"/updateFiles.exe"); if(updateFileExe.exists()) { QStringList l; updateFileExe.rename(dataLocation+"/updateTexitEasy.exe"); //l << str+"/texiteasy_upgrade.exe"; l << dataLocation+"/updateTexitEasy.exe"; // l << str; proc->start(str+"/elevate.exe", l); return 0; } proc->start(str+"/TexitEasy.exe", args); }
bool AssignmentThread::traditionalTaskPrepare() { compileState = NoValidSourceFile; QDir contestantDir = QDir(Settings::sourcePath() + contestantName); QList<Compiler*> compilerList = settings->getCompilerList(); for (int i = 0; i < compilerList.size(); i ++) { if (task->getCompilerConfiguration(compilerList[i]->getCompilerName()) == "disable") continue; QStringList filters = compilerList[i]->getSourceExtensions(); for (int j = 0; j < filters.size(); j ++) { filters[j] = task->getSourceFileName() + "." + filters[j]; } QStringList files = contestantDir.entryList(filters, QDir::Files); sourceFile = ""; for (int j = 0; j < files.size(); j ++) { qint64 fileSize = QFileInfo(Settings::sourcePath() + contestantName + QDir::separator() + files[j]).size(); if (fileSize <= settings->getFileSizeLimit() * 1024) { sourceFile = files[j]; break; } } if (! sourceFile.isEmpty()) { QDir(Settings::temporaryPath()).mkdir(contestantName); QFile::copy(Settings::sourcePath() + contestantName + QDir::separator() + sourceFile, Settings::temporaryPath() + contestantName + QDir::separator() + sourceFile); QStringList configurationNames = compilerList[i]->getConfigurationNames(); QStringList compilerArguments = compilerList[i]->getCompilerArguments(); QStringList interpreterArguments = compilerList[i]->getInterpreterArguments(); QString currentConfiguration = task->getCompilerConfiguration(compilerList[i]->getCompilerName()); for (int j = 0; j < configurationNames.size(); j ++) { if (configurationNames[j] == currentConfiguration) { timeLimitRatio = compilerList[i]->getTimeLimitRatio(); memoryLimitRatio = compilerList[i]->getMemoryLimitRatio(); disableMemoryLimitCheck = compilerList[i]->getDisableMemoryLimitCheck(); environment = compilerList[i]->getEnvironment(); QStringList values = environment.toStringList(); for (int k = 0; k < values.size(); k ++) { int tmp = values[k].indexOf("="); QString variable = values[k].mid(0, tmp); environment.insert(variable, environment.value(variable) + ";" + QProcessEnvironment::systemEnvironment().value(variable)); } if (compilerList[i]->getCompilerType() == Compiler::Typical) { #ifdef Q_OS_WIN32 executableFile = task->getSourceFileName() + ".exe"; #endif #ifdef Q_OS_LINUX executableFile = task->getSourceFileName(); #endif interpreterFlag = false; } else { executableFile = compilerList[i]->getInterpreterLocation(); arguments = interpreterArguments[j]; arguments.replace("%s.*", sourceFile); arguments.replace("%s", task->getSourceFileName()); interpreterFlag = true; } if (compilerList[i]->getCompilerType() != Compiler::InterpretiveWithoutByteCode) { QString arguments = compilerArguments[j]; arguments.replace("%s.*", sourceFile); arguments.replace("%s", task->getSourceFileName()); QProcess *compiler = new QProcess(this); compiler->setProcessChannelMode(QProcess::MergedChannels); compiler->setProcessEnvironment(environment); compiler->setWorkingDirectory(Settings::temporaryPath() + contestantName); compiler->start(QString("\"") + compilerList[i]->getCompilerLocation() + "\" " + arguments); if (! compiler->waitForStarted(-1)) { compileState = InvalidCompiler; delete compiler; break; } QElapsedTimer timer; timer.start(); bool flag = false; while (timer.elapsed() < settings->getCompileTimeLimit()) { if (compiler->state() != QProcess::Running) { flag = true; break; } QCoreApplication::processEvents(); if (stopJudging) { compiler->kill(); delete compiler; return false; } msleep(10); } if (! flag) { compiler->kill(); compileState = CompileTimeLimitExceeded; } else if (compiler->exitCode() != 0) { compileState = CompileError; compileMessage = QString::fromLocal8Bit(compiler->readAllStandardOutput().data()); } else { if (compilerList[i]->getCompilerType() == Compiler::Typical) { if (! QDir(Settings::temporaryPath() + contestantName).exists(executableFile)) { compileState = InvalidCompiler; } else { compileState = CompileSuccessfully; } } else { QStringList filters = compilerList[i]->getBytecodeExtensions(); for (int k = 0; k < filters.size(); k ++) { filters[k] = QString("*.") + filters[k]; } if (QDir(Settings::temporaryPath() + contestantName) .entryList(filters, QDir::Files).size() == 0) { compileState = InvalidCompiler; } else { compileState = CompileSuccessfully; } } } delete compiler; } if (compilerList[i]->getCompilerType() == Compiler::InterpretiveWithoutByteCode) compileState = CompileSuccessfully; break; } } break; } } if (compileState != CompileSuccessfully) { emit compileError(task->getTotalTimeLimit(), (int)compileState); return false; } return true; }
int main(int argc, char **argv){ //Run all the actual code in a separate function to have as little memory usage // as possible aside from the main application when running //Make sure the XDG environment variables exist first LXDG::setEnvironmentVars(); //now get the command QString cmd, args, path; bool watch = true; //enable the crash handler by default (only disabled for some *.desktop inputs) getCMD(argc, argv, cmd, args, path, watch); //qDebug() << "Run CMD:" << cmd << args; //Now run the command (move to execvp() later?) if(cmd.isEmpty()){ return 0; } //no command to run (handled internally) qDebug() << "[lumina-open] Running Cmd:" << cmd; int retcode = 0; if(!watch && path.isEmpty()){ //Nothing special about this one - just start it detached (less overhead) QProcess::startDetached(cmd); }else{ //Keep an eye on this process for errors and notify the user if it crashes QString log; if(cmd.contains("\\\\")){ //Special case (generally for Wine applications) cmd = cmd.replace("\\\\","\\"); retcode = system(cmd.toLocal8Bit()); //need to run it through the "system" instead of QProcess }else{ QProcess *p = new QProcess(); p->setProcessEnvironment(QProcessEnvironment::systemEnvironment()); if(!path.isEmpty() && QFile::exists(path)){ //qDebug() << " - Setting working path:" << path; p->setWorkingDirectory(path); } p->start(cmd); //Now check up on it once every minute until it is finished while(!p->waitForFinished(60000)){ //qDebug() << "[lumina-open] process check:" << p->state(); if(p->state() != QProcess::Running){ break; } //somehow missed the finished signal } retcode = p->exitCode(); if( (p->exitStatus()==QProcess::CrashExit) && retcode ==0){ retcode=1; } //so we catch it later log = QString(p->readAllStandardError()); if(log.isEmpty()){ log = QString(p->readAllStandardOutput()); } } //qDebug() << "[lumina-open] Finished Cmd:" << cmd << retcode << p->exitStatus(); if( QFile::exists("/tmp/.luminastopping") ){ watch = false; } //closing down session - ignore "crashes" (app could have been killed during cleanup) if( (retcode > 0) && watch && !(retcode==1 && cmd.startsWith("pc-su ")) ){ //pc-su returns 1 if the user cancelles the operation qDebug() << "[lumina-open] Application Error:" << retcode; //Setup the application QApplication App(argc, argv); LuminaThemeEngine theme(&App); LUtils::LoadTranslation(&App,"lumina-open"); QMessageBox dlg(QMessageBox::Critical, QObject::tr("Application Error"), QObject::tr("The following application experienced an error and needed to close:")+"\n\n"+cmd ); if(!log.isEmpty()){ dlg.setDetailedText(log); } dlg.exec(); } } return retcode; }
void Common::mailTo( const QUrl &url ) { #if defined(Q_OS_WIN32) QString file = url.queryItemValue( "attachment" ); QByteArray filePath = QDir::toNativeSeparators( file ).toLatin1(); QByteArray fileName = QFileInfo( file ).fileName().toLatin1(); QByteArray subject = url.queryItemValue( "subject" ).toLatin1(); MapiFileDesc doc[1]; doc[0].ulReserved = 0; doc[0].flFlags = 0; doc[0].nPosition = -1; doc[0].lpszPathName = const_cast<char*>(filePath.constData()); doc[0].lpszFileName = const_cast<char*>(fileName.constData()); doc[0].lpFileType = NULL; // Create message MapiMessage message; message.ulReserved = 0; message.lpszSubject = const_cast<char*>(subject.constData()); message.lpszNoteText = ""; message.lpszMessageType = NULL; message.lpszDateReceived = NULL; message.lpszConversationID = NULL; message.flFlags = 0; message.lpOriginator = NULL; message.nRecipCount = 0; message.lpRecips = NULL; message.nFileCount = 1; message.lpFiles = (lpMapiFileDesc)&doc; QLibrary lib("mapi32"); typedef ULONG (PASCAL *SendMail)(ULONG,ULONG,MapiMessage*,FLAGS,ULONG); SendMail mapi = (SendMail)lib.resolve("MAPISendMail"); if( mapi ) { mapi( NULL, 0, &message, MAPI_LOGON_UI|MAPI_DIALOG, 0 ); return; } #elif defined(Q_OS_MAC) CFURLRef emailUrl = CFURLCreateWithString( kCFAllocatorDefault, CFSTR("mailto:"), 0 ); CFURLRef appUrl = 0; CFStringRef appPath = 0; if( LSGetApplicationForURL( emailUrl, kLSRolesAll, NULL, &appUrl ) == noErr ) { appPath = CFURLCopyFileSystemPath( appUrl, kCFURLPOSIXPathStyle ); CFRelease( appUrl ); } CFRelease( emailUrl ); if( appPath ) { QProcess p; p.start( "/usr/bin/osascript", QStringList() << "-" << url.queryItemValue("attachment") << url.queryItemValue("subject") ); p.waitForStarted(); QTextStream s( &p ); if( CFStringCompare( appPath, CFSTR("/Applications/Mail.app"), 0 ) == kCFCompareEqualTo ) { s << "on run argv" << endl << "set vattachment to (item 1 of argv)" << endl << "set vsubject to (item 2 of argv)" << endl << "tell application \"Mail\"" << endl << "set composeMessage to make new outgoing message at beginning with properties {visible:true}" << endl << "tell composeMessage" << endl << "set subject to vsubject" << endl << "set content to \" \"" << endl << "tell content" << endl << "make new attachment with properties {file name: vattachment} at after the last word of the last paragraph" << endl << "end tell" << endl << "end tell" << endl << "activate" << endl << "end tell" << endl << "end run" << endl; } else if( CFStringFind( appPath, CFSTR("Entourage"), 0 ).location != kCFNotFound ) { s << "on run argv" << endl << "set vattachment to (item 1 of argv)" << endl << "set vsubject to (item 2 of argv)" << endl << "tell application \"Microsoft Entourage\"" << endl << "set vmessage to make new outgoing message with properties" << endl << "{subject:vsubject, attachments:vattachment}" << endl << "open vmessage" << endl << "activate" << endl << "end tell" << endl << "end run" << endl; } #if 0 else if(CFStringCompare(appPath, CFSTR("/Applications/Thunderbird.app"), 0) == kCFCompareEqualTo) { // TODO: Handle Thunderbird here? Impossible? } #endif CFRelease( appPath ); p.closeWriteChannel(); p.waitForFinished(); if( p.exitCode() == 0 ) return; } #elif defined(Q_OS_LINUX) QByteArray thunderbird; QProcess p; QStringList env = QProcess::systemEnvironment(); if( env.indexOf( QRegExp("KDE_FULL_SESSION.*") ) != -1 ) { p.start( "kreadconfig", QStringList() << "--file" << "emaildefaults" << "--group" << "PROFILE_Default" << "--key" << "EmailClient" ); p.waitForFinished(); QByteArray data = p.readAllStandardOutput().trimmed(); if( data.contains("thunderbird") ) thunderbird = data; } else if( env.indexOf( QRegExp("GNOME_DESKTOP_SESSION_ID.*") ) != -1 ) { p.start( "gconftool-2", QStringList() << "--get" << "/desktop/gnome/url-handlers/mailto/command" ); p.waitForFinished(); QByteArray data = p.readAllStandardOutput(); if( data.contains("thunderbird") ) thunderbird = data.split(' ').value(0); } /* else { p.start( "xprop", QStringList() << "-root" << "_DT_SAVE_MODE" ); p.waitForFinished(); if( p.readAllStandardOutput().contains("xfce4") ) {} }*/ if( !thunderbird.isEmpty() ) { if( p.startDetached( thunderbird, QStringList() << "-compose" << QString( "subject='%1',attachment='%2'" ) .arg( url.queryItemValue( "subject" ) ) .arg( QUrl::fromLocalFile( url.queryItemValue( "attachment" ) ).toString() ) ) ); return; } else { if( p.startDetached( "xdg-email", QStringList() << "--subject" << url.queryItemValue( "subject" ) << "--attach" << url.queryItemValue( "attachment" ) ) ) return; } #endif QDesktopServices::openUrl( url ); }
void TestRailInterface::addRun() { QString filename = _outputDirectory + "/addRun.py"; if (QFile::exists(filename)) { QFile::remove(filename); } QFile file(filename); if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) { QMessageBox::critical(0, "Internal error: " + QString(__FILE__) + ":" + QString::number(__LINE__), "Could not create " + filename); exit(-1); } QTextStream stream(&file); // Code to access TestRail stream << "from testrail import *\n"; stream << "client = APIClient('" << _url.toStdString().c_str() << "')\n"; stream << "client.user = '******'\n"; stream << "client.password = '******'\n\n"; // A test suite is a forest. Each node is a section and leaves are either sections or test cases // The user has selected a root for the run // To find the cases in this tree we need all the sections in the tree // These are found by building a set of all relevant sections. The first section is the selected root // As the sections are in an ordered array we use the following snippet to find the relevant sections: // initialize section set with the root // for each section in the ordered array of sections in the suite // if the parent of the section is in the section set then // add this section to the section set // stream << "sections = client.send_get('get_sections/" + _projectID + "&suite_id=" + _suiteID + "')\n\n"; int sectionID = _sectionIDs[_testRailRunSelectorWindow.getSectionID()]; stream << "relevantSections = { " + QString::number(sectionID) + " }\n"; stream << "for section in sections:\n"; stream << "\tif section['parent_id'] in relevantSections:\n"; stream << "\t\trelevantSections.add(section['id'])\n\n"; // We now loop over each section in the set and collect the cases into an array stream << "cases = []\n"; stream << "for section_id in relevantSections:\n"; stream << "\tcases = cases + client.send_get('get_cases/" + _projectID + "&suite_id=" + _suiteID + "§ion_id=' + str(section_id))\n\n"; // To create a run we need an array of the relevant case ids stream << "case_ids = []\n"; stream << "for case in cases:\n"; stream << "\tcase_ids.append(case['id'])\n\n"; // Now, we can create the run stream << "data = { 'name': '" + _sectionNames[_testRailRunSelectorWindow.getSectionID()].replace("Section", "Run") + "[" + QHostInfo::localHostName() + "]" + "', 'suite_id': " + _suiteID + ", 'include_all': False, 'case_ids': case_ids}\n"; stream << "run = client.send_post('add_run/" + _projectID + "', data)\n"; file.close(); if (QMessageBox::Yes == QMessageBox(QMessageBox::Information, "Python script has been created", "Do you want to run the script and update TestRail?", QMessageBox::Yes | QMessageBox::No).exec() ) { QProcess* process = new QProcess(); connect(process, &QProcess::started, this, [=]() { _busyWindow.exec(); }); connect(process, SIGNAL(finished(int)), process, SLOT(deleteLater())); connect(process, static_cast<void (QProcess::*)(int, QProcess::ExitStatus)>(&QProcess::finished), this, [=](int exitCode, QProcess::ExitStatus exitStatus) { _busyWindow.hide(); }); #ifdef Q_OS_WIN QStringList parameters = QStringList() << _outputDirectory + "/addRun.py"; process->start(_pythonCommand, parameters); #elif defined Q_OS_MAC QStringList parameters = QStringList() << "-c" << _pythonCommand + " " + _outputDirectory + "/addRun.py"; process->start("sh", parameters); #endif } }
static QString getOperatingSystem() { #if defined (Q_OS_WIN32) switch(QSysInfo::windowsVersion()) { case QSysInfo::WV_NT: return QString::fromLatin1("Windows NT"); case QSysInfo::WV_2000: return QString::fromLatin1("Windows 2000"); case QSysInfo::WV_XP: return QString::fromLatin1("Windows XP"); case QSysInfo::WV_2003: return QString::fromLatin1("Windows Server 2003"); case QSysInfo::WV_VISTA: return QString::fromLatin1("Windows Vista"); case QSysInfo::WV_WINDOWS7: return QString::fromLatin1("Windows 7"); case QSysInfo::WV_WINDOWS8: return QString::fromLatin1("Windows 8"); #if ((QT_VERSION >= 0x050200) || (QT_VERSION >= 0x040806 && QT_VERSION < 0x050000)) case QSysInfo::WV_WINDOWS8_1: return QString::fromLatin1("Windows 8.1"); #endif #if QT_VERSION >= 0x040807 case QSysInfo::WV_WINDOWS10: return QString::fromLatin1("Windows 10"); #endif default: return QString::fromLatin1("Windows"); } #elif defined (Q_OS_MAC) switch(QSysInfo::MacVersion()) { case QSysInfo::MV_10_3: return QString::fromLatin1("Mac OS X 10.3"); case QSysInfo::MV_10_4: return QString::fromLatin1("Mac OS X 10.4"); case QSysInfo::MV_10_5: return QString::fromLatin1("Mac OS X 10.5"); case QSysInfo::MV_10_6: return QString::fromLatin1("Mac OS X 10.6"); case QSysInfo::MV_10_7: return QString::fromLatin1("Mac OS X 10.7"); case QSysInfo::MV_10_8: return QString::fromLatin1("Mac OS X 10.8"); case QSysInfo::MV_10_9: return QString::fromLatin1("Mac OS X 10.9"); default: return QString::fromLatin1("Mac OS X"); } #elif defined (Q_OS_LINUX) QString exe(QLatin1String("lsb_release")); QStringList args; args << QLatin1String("-ds"); QProcess proc; proc.setEnvironment(QProcess::systemEnvironment()); proc.start(exe, args); if (proc.waitForStarted() && proc.waitForFinished()) { QByteArray info = proc.readAll(); info.replace('\n',""); return QString::fromLatin1((const char*)info); } return QString::fromLatin1("Linux"); #elif defined (Q_OS_UNIX) return QString::fromLatin1("UNIX"); #else return QString(); #endif }
void AlignmentDialog::align() { // get & convert indi current ra to double bool ok; indiRa_dh = QString(talk_indi("ra",0)).toDouble(&ok); //TODO check if valid ui->debug->append("RA" + QString::number(indiRa_dh)); QTime indiRa(0,0,0); indiRa = indiRa.addSecs(indiRa_dh*3600); ui->label_MountRa->setText(indiRa.toString("hh:mm:ss")); // get & convert indi current dec to double bool ok2; indiDe_dh = QString(talk_indi("de",0)).toDouble(&ok2); //TODO check if valid ui->debug->append("DE" + QString::number(indiDe_dh)); // convert polaris hour angle from qtime to double double pha_d = pha.hour() + pha.minute() / 60.0 + pha.second() / 3600.0; // QTime to double ui->debug->append("PHA=" + QString::number(pha_d)); ui->label_pha->setText(pha.toString("hh:mm:ss")); // calculate destination ra decimal & QTime double destRa_d = (24.0 - pha_d) + indiRa_dh; if(destRa_d > 24.0){ destRa_d = destRa_d - 24.0; } ui->debug->append("destRa_d=" + QString::number(destRa_d)); QTime destRa(0,0,0); destRa = destRa.addSecs(destRa_d*3600); ui->label_destRa->setText(destRa.toString("hh:mm:ss")); //NOTE set track after set destRa, default for everyone? EQMod Mount.ON_COORD_SET.TRACK=On QString message = "be shure your mount does not bump onto cables etc... You can always press " "STOP MOTION if you fear collision, but also keep an eye on the power plug, just in case. I am not responsible for any damage.\n\n" "Slewing RA from " + indiRa.toString("hh:mm:ss") + " to " + destRa.toString("hh:mm:ss"); QMessageBox::StandardButton reply; reply = QMessageBox::warning(this,"Please NOTICE!", message,QMessageBox::Yes|QMessageBox::No); if(reply == QMessageBox::Yes){ if(ok){ // disable limits QStringList arguments; arguments << "-h" << indi_server << "-p" << indi_port << "EQMod Mount.HORIZONLIMITSONLIMIT.HORIZONLIMITSONLIMITTRACK=Off"; QProcess *myProcess = new QProcess(this); myProcess->start(indiset, arguments); myProcess->waitForFinished(); arguments.clear(); arguments << "-h" << indi_server << "-p" << indi_port << "EQMod Mount.HORIZONLIMITSLIMITGOTO.HORIZONLIMITSLIMITGOTODISABLE=On"; myProcess->start(indiset, arguments); myProcess->waitForFinished(); QString destArgs; destArgs = "EQMod Mount.EQUATORIAL_EOD_COORD.RA;DEC=" + QString::number(destRa_d) + ";" + QString::number(indiDe_dh); // goto destRa arguments.clear(); arguments << "-h" << indi_server << "-p" << indi_port << destArgs; myProcess->start(indiset, arguments); myProcess->waitForFinished(); } else{ QMessageBox::warning(this,"ERROR", "RA is not valid, will not slew!"); } } }
QString AlignmentDialog::talk_indi(QString const &cmd, bool const &getset) { QString ret; QString indicmd; QString prop; QStringList arguments; QProcess *myProcess = new QProcess(this); if (getset == 0){ // get property indicmd = indiget; if (cmd == "connect"){ prop = movecmds.at(25); } else if (cmd == "park"){ prop = movecmds.at(26); } else if (cmd == "ra"){ prop = movecmds.at(24); } else if (cmd == "de"){ prop = movecmds.at(23); } else if(cmd == "idle"){ QStringList a,b; b << "Busy" << "Busy" << "Busy" << "Busy"; for(unsigned int i=27;i<31;i++){ prop = movecmds.at(i); arguments << "-1" << "-h" << indi_server << "-p" << indi_port << prop; myProcess->start(indicmd, arguments); myProcess->waitForFinished(); a << myProcess->readAllStandardOutput().simplified(); ui->debug->append(a.join(" ")); arguments.clear(); prop.clear(); ret = (a==b)?"idle":"busy"; } } } else if (getset == 1){ // set property indicmd = indiset; if (cmd == "connect"){ prop = movecmds.at(4); } else if(cmd == "park"){ prop = movecmds.at(6); } else if(cmd == "unpark"){ prop = movecmds.at(5); } else if(cmd == "abort"){ prop = movecmds.at(3); } else if(cmd == "move.dec.pos.start"){ prop = movecmds.at(7); } else if(cmd == "move.dec.pos.stop"){ prop = movecmds.at(8); } else if(cmd == "move.dec.neg.start"){ prop = movecmds.at(9); } else if(cmd == "move.dec.neg.stop"){ prop = movecmds.at(10); } else if(cmd == "move.ra.pos.start"){ prop = movecmds.at(11); } else if(cmd == "move.ra.pos.stop"){ prop = movecmds.at(12); } else if(cmd == "move.ra.neg.start"){ prop = movecmds.at(13); } else if(cmd == "move.ra.neg.stop"){ prop = movecmds.at(14); } else if(cmd == "speed"){ if(ui->comboBox_speed->currentText() == "64"){ prop = movecmds.at(32); } else if(ui->comboBox_speed->currentText() == "128"){ prop = movecmds.at(33); } else { prop = movecmds.at(34); } } } else { ui->debug->append("ERROR, getset is not 0,1"); } if (getset == 0){ arguments << "-1" << "-h" << indi_server << "-p" << indi_port << prop; } else { arguments << "-h" << indi_server << "-p" << indi_port << prop; } if (cmd != "idle"){ myProcess->start(indicmd, arguments); myProcess->waitForFinished(); ret = myProcess->readAllStandardOutput().simplified(); exitcode = myProcess->exitCode(); if (myProcess->exitCode() != 0){ ui->debug->append("Exitcode " + QString::number(myProcess->exitCode()) + " at " + arguments.join(" ")); } } ui->debug->append("return value =" + ret); return ret; }
void MainWindow::start_new_client() { QProcess *p = new QProcess(this); p->start(_process_name, QStringList("client")); }
int main(int argc, char *argv[]) { bool running = false; TFullName res; TFindProcess find; while(find.Next(res) == KErrNone) { RProcess ph; ph.Open(res); if(ph.SecureId() == 0x2002B30D) if (ph.ExitType() == EExitPending) { running = true; break; } ph.Close(); } if (running == false) { QProcess *myProcess = new QProcess; myProcess->start("whatsapp.exe"); } else { QApplication app(argc, argv); CAknConfirmationNote* run = new (ELeave) CAknConfirmationNote; QT_TRAP_THROWING(run->ExecuteLD(_L("Closed WhatsApp"))); TFullName res1; TFindProcess find1(_L("*[2002B306]*")); while(find1.Next(res1) == KErrNone) { RProcess ph1; ph1.Open(find1); ph1.Kill(KErrNone); ph1.Close(); } TFullName res2; TFindProcess find2(_L("*[2002B310]*")); while(find2.Next(res2) == KErrNone) { RProcess ph2; ph2.Open(find2); ph2.Kill(KErrNone); ph2.Close(); } TFullName res3; TFindProcess find3(_L("*[2002B30D]*")); while(find3.Next(res3) == KErrNone) { RProcess ph3; ph3.Open(find3); ph3.Kill(KErrNone); ph3.Close(); } QTest::qWait(1500); } return 1; }
void AssignmentClientMonitor::spawnChildClient() { QProcess* assignmentClient = new QProcess(this); // unparse the parts of the command-line that the child cares about QStringList _childArguments; if (_assignmentPool != "") { _childArguments.append("--" + ASSIGNMENT_POOL_OPTION); _childArguments.append(_assignmentPool); } if (!_walletUUID.isNull()) { _childArguments.append("--" + ASSIGNMENT_WALLET_DESTINATION_ID_OPTION); _childArguments.append(_walletUUID.toString()); } if (_assignmentServerHostname != "") { _childArguments.append("--" + CUSTOM_ASSIGNMENT_SERVER_HOSTNAME_OPTION); _childArguments.append(_assignmentServerHostname); } if (_assignmentServerPort != DEFAULT_DOMAIN_SERVER_PORT) { _childArguments.append("--" + CUSTOM_ASSIGNMENT_SERVER_PORT_OPTION); _childArguments.append(QString::number(_assignmentServerPort)); } if (_requestAssignmentType != Assignment::AllTypes) { _childArguments.append("--" + ASSIGNMENT_TYPE_OVERRIDE_OPTION); _childArguments.append(QString::number(_requestAssignmentType)); } // tell children which assignment monitor port to use // for now they simply talk to us on localhost _childArguments.append("--" + ASSIGNMENT_CLIENT_MONITOR_PORT_OPTION); _childArguments.append(QString::number(DependencyManager::get<NodeList>()->getLocalSockAddr().getPort())); QString nowString, stdoutFilenameTemp, stderrFilenameTemp, stdoutPathTemp, stderrPathTemp; if (_wantsChildFileLogging) { // Setup log files const QString DATETIME_FORMAT = "yyyyMMdd.hh.mm.ss.zzz"; if (!_logDirectory.exists()) { qDebug() << "Log directory (" << _logDirectory.absolutePath() << ") does not exist, creating."; _logDirectory.mkpath(_logDirectory.absolutePath()); } nowString = QDateTime::currentDateTime().toString(DATETIME_FORMAT); stdoutFilenameTemp = QString("ac-%1-stdout.txt").arg(nowString); stderrFilenameTemp = QString("ac-%1-stderr.txt").arg(nowString); stdoutPathTemp = _logDirectory.absoluteFilePath(stdoutFilenameTemp); stderrPathTemp = _logDirectory.absoluteFilePath(stderrFilenameTemp); // reset our output and error files assignmentClient->setStandardOutputFile(stdoutPathTemp); assignmentClient->setStandardErrorFile(stderrPathTemp); } // make sure that the output from the child process appears in our output assignmentClient->setProcessChannelMode(QProcess::ForwardedChannels); assignmentClient->start(QCoreApplication::applicationFilePath(), _childArguments); QString stdoutPath, stderrPath; if (_wantsChildFileLogging) { // Update log path to use PID in filename auto stdoutFilename = QString("ac-%1_%2-stdout.txt").arg(nowString).arg(assignmentClient->processId()); auto stderrFilename = QString("ac-%1_%2-stderr.txt").arg(nowString).arg(assignmentClient->processId()); stdoutPath = _logDirectory.absoluteFilePath(stdoutFilename); stderrPath = _logDirectory.absoluteFilePath(stderrFilename); qDebug() << "Renaming " << stdoutPathTemp << " to " << stdoutPath; if (!_logDirectory.rename(stdoutFilenameTemp, stdoutFilename)) { qDebug() << "Failed to rename " << stdoutFilenameTemp; stdoutPath = stdoutPathTemp; stdoutFilename = stdoutFilenameTemp; } qDebug() << "Renaming " << stderrPathTemp << " to " << stderrPath; if (!QFile::rename(stderrPathTemp, stderrPath)) { qDebug() << "Failed to rename " << stderrFilenameTemp; stderrPath = stderrPathTemp; stderrFilename = stderrFilenameTemp; } qDebug() << "Child stdout being written to: " << stdoutFilename; qDebug() << "Child stderr being written to: " << stderrFilename; } if (assignmentClient->processId() > 0) { auto pid = assignmentClient->processId(); // make sure we hear that this process has finished when it does connect(assignmentClient, static_cast<void(QProcess::*)(int, QProcess::ExitStatus)>(&QProcess::finished), this, [this, pid]() { childProcessFinished(pid); }); qDebug() << "Spawned a child client with PID" << assignmentClient->processId(); _childProcesses.insert(assignmentClient->processId(), { assignmentClient, stdoutPath, stderrPath }); } }
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 ); }
bool generate(const ToolListType & tools, const String & prefix, const String & binary_directory) { bool errors_occured = false; for (ToolListType::const_iterator it = tools.begin(); it != tools.end(); ++it) { //start process QProcess process; process.setProcessChannelMode(QProcess::MergedChannels); QStringList env = QProcess::systemEnvironment(); env << String("COLUMNS=110").toQString(); // Add an environment variable (used by each TOPP tool to determine width of help text (see TOPPBase)) process.setEnvironment(env); String command = binary_directory + it->first; #if defined(__APPLE__) if (it->first == "TOPPView" || it->first == "TOPPAS") { command = binary_directory + it->first + ".app/Contents/MacOS/" + it->first; } #endif #ifdef OPENMS_WINDOWSPLATFORM command += ".exe"; // otherwise File::exists() will fail #endif ofstream f((String("output/") + prefix + it->first + ".cli").c_str()); if (!File::exists(command)) { stringstream ss; ss << "Errors occurred while generating the command line documentation for " << it->first << "!" << endl; ss << "Tool could not be found at '" << command << "'\n " << command << endl; f << ss.str(); cerr << ss.str(); errors_occured = true; f.close(); continue; } else { process.start(String(command + " --help").toQString()); process.waitForFinished(); std::string lines = QString(process.readAll()).toStdString(); if (process.error() != QProcess::UnknownError) { // error while generation cli docu stringstream ss; f << "Errors occurred while generating the command line documentation for " << it->first << "!" << endl; f << "Output was: \n" << lines << endl; f << "Command line was: \n " << command << endl; f << ss.str(); cerr << ss.str(); errors_occured = true; f.close(); continue; } else { // write output f << lines; } } f.close(); ////// // get the INI file and convert it into HTML ////// if (it->first == "GenericWrapper") continue; // does not support -write_ini without a type if (it->first == "TOPPView") continue; // does not support -write_ini if (it->first == "TOPPAS") continue; // does not support -write_ini String tmp_file = File::getTempDirectory() + "/" + File::getUniqueName() + "_" + it->first + ".ini"; process.start((command + " -write_ini " + tmp_file).toQString()); process.waitForFinished(); Param p; ParamXMLFile pf; pf.load(tmp_file, p); File::remove(tmp_file); ofstream f_html((String("output/") + prefix + it->first + ".html").c_str()); convertINI2HTML(p, f_html); f_html.close(); } return errors_occured; }
void US_Win::launch( int index ) { static const int trig_secs=3600; index -= P_CONFIG; QString pname = p[ index ].name; // At each launch, check for notices if last check was over 24 hours ago if ( ln_time.secsTo( QDateTime::currentDateTime() ) > trig_secs ) notice_check(); if ( p[ index ].maxRunCount <= p[ index ].currentRunCount && p[ index ].maxRunCount > 0 ) { if ( p[ index ].index == P_CONFIG ) { QMessageBox::information( this, tr( "Already Running" ), tr( "The configuration program is already running.\n" "Click on the task bar item named UltraScan " "Configuration to continue." ) ); } else { QMessageBox::warning( this, tr( "Error" ), pname + tr( " is already running." ) ); } return; } statusBar()->showMessage( tr( "Loading " ) + p[ index ].runningMsg + "..." ); QProcess* process = new QProcess( 0 ); process->closeReadChannel( QProcess::StandardOutput ); process->closeReadChannel( QProcess::StandardError ); connect ( process, SIGNAL( finished ( int, QProcess::ExitStatus ) ), this , SLOT ( terminated( int, QProcess::ExitStatus ) ) ); #ifndef Q_OS_MAC process->start( pname ); #else QString procbin = US_Settings::appBaseDir() + "/bin/" + pname; QString procapp = procbin + ".app"; if ( !QFile( procapp ).exists() ) procapp = procbin; process->start( "open", QStringList(procapp) ); #endif if ( ! process->waitForStarted( 10000 ) ) // 10 second timeout { QMessageBox::information( this, tr( "Error" ), tr( "There was a problem creating a subprocess\nfor " ) + pname ); } else { p[ index ].currentRunCount++; procData* pr = new procData; pr->proc = process; pr->name = pname; pr->index = index; procs << pr; } statusBar()->showMessage( tr( "Loaded " ) + p[ index ].runningMsg + "..." ); }
/** * Slot called when a column is clicked in the tree displaying the attribute data * @param theItem - The tree widget item click * @param theColumn - The column that was clicked */ void eVisGenericEventBrowserGui::launchExternalApplication( QTreeWidgetItem * theItem, int theColumn ) { // At this point there is only attribute data with no children, ignore clicks on field name if ( 1 == theColumn ) { int myIterator = 0; bool startsWithExtension = false; while ( myIterator < tableFileTypeAssociations->rowCount() ) { if ( theItem->text( theColumn ).startsWith( tableFileTypeAssociations->item( myIterator, 0 )->text() + ':', Qt::CaseInsensitive ) ) { startsWithExtension = true; break; } else if ( theItem->text( theColumn ).endsWith( tableFileTypeAssociations->item( myIterator, 0 )->text(), Qt::CaseInsensitive ) ) { startsWithExtension = false; break; } else myIterator++; } if ( myIterator != tableFileTypeAssociations->rowCount() ) { QProcess *myProcess = new QProcess(); QString myApplication = tableFileTypeAssociations->item( myIterator, 1 )->text(); QString myDocument = theItem->text( theColumn ); if ( startsWithExtension ) { myDocument = theItem->text( theColumn ).remove( tableFileTypeAssociations->item( myIterator, 0 )->text() + ':', Qt::CaseInsensitive ); } if ( "" != myApplication ) { if ( mConfiguration.isApplyPathRulesToDocsSet() ) { int myDocumentNameMarker = 0; if ( myDocument.contains( '/' ) ) { myDocumentNameMarker = myDocument.lastIndexOf( '/' ); } else { myDocumentNameMarker = myDocument.lastIndexOf( '\\' ); } QString myDocumentName = myDocument; myDocumentName.remove( 0, myDocumentNameMarker + 1 ); if ( mConfiguration.isUseOnlyFilenameSet() ) { myDocument = mConfiguration.basePath() + myDocumentName; } else { if ( mConfiguration.isEventImagePathRelative() ) { myDocument = mConfiguration.basePath() + myDocument; } } } myProcess->start( myApplication, QStringList() << myDocument ); } } else { QMessageBox::information( this, tr( "Attribute Contents" ), theItem->text( theColumn ) ); } } }
// Function which checks for our GUI package schema data, and sets found if its located QList<QStringList> Backend::getPackageData(bool &found, QString pkgset) { if ( pkgset.isEmpty() ) pkgset="pcbsd"; QList<QStringList> metaPkgs; found=false; bool onDisk; onDisk=true; QString tmp, mName, mDesc, mIcon, mParent, mDesktop, mPkgFileList; QStringList package; QProcess pcmp; qDebug() << "Searching for meta-pkgs..."; pcmp.start(QString("/root/get-pkgset.sh"), QStringList()); if (pcmp.waitForFinished()) { while (pcmp.canReadLine()) { tmp = pcmp.readLine().simplified(); if ( tmp.indexOf("Meta Package: ") == 0) { mName = tmp.replace("Meta Package: ", ""); continue; } if ( tmp.indexOf("Description: ") == 0) { mDesc = tmp.replace("Description: ", ""); continue; } if ( tmp.indexOf("Icon: ") == 0) { mIcon = tmp.replace("Icon: ", ""); mPkgFileList = mIcon; mPkgFileList.replace("pkg-icon.png", "pkg-list"); continue; } if ( tmp.indexOf("Parent: ") == 0) { mParent = tmp.replace("Parent: ", ""); continue; } if ( tmp.indexOf("Desktop: ") == 0) { mDesktop = tmp.replace("Desktop: ", ""); continue; } if ( tmp.indexOf("Category Entry") == 0) { // Now add this category to the string list package.clear(); //qDebug() << "Found Category" << mName << mDesc << mIcon << mParent<< mDesktop << "CATEGORY"; package << mName << mDesc << mIcon << mParent << mDesktop << "CATEGORY"; metaPkgs.append(package); mName=""; mDesc=""; mIcon=""; mParent=""; mDesktop=""; mPkgFileList=""; } if ( tmp.indexOf("Required Packages:") == 0) { // Now add this meta-pkg to the string list package.clear(); //qDebug() << "Found Package" << mName << mDesc << mIcon << mParent << mDesktop << "NO" << mPkgFileList; package << mName << mDesc << mIcon << mParent << mDesktop << "NO" << mPkgFileList; metaPkgs.append(package); found = true; mName=""; mDesc=""; mIcon=""; mParent=""; mDesktop=""; mPkgFileList=""; } } } return metaPkgs; }
static int getWordSizeOfOS() { #if defined(Q_OS_WIN64) return 64; // 64-bit process running on 64-bit windows #elif defined(Q_OS_WIN32) // determine if 32-bit process running on 64-bit windows in WOW64 emulation // or 32-bit process running on 32-bit windows // default bIsWow64 to false for 32-bit process on 32-bit windows BOOL bIsWow64 = false; // must default to false typedef BOOL (WINAPI *LPFN_ISWOW64PROCESS) (HANDLE, PBOOL); LPFN_ISWOW64PROCESS fnIsWow64Process = (LPFN_ISWOW64PROCESS) GetProcAddress( GetModuleHandle("kernel32"), "IsWow64Process"); if (NULL != fnIsWow64Process) { if (!fnIsWow64Process(GetCurrentProcess(), &bIsWow64)) { assert(false); // something went majorly wrong } } return bIsWow64 ? 64 : 32; #elif defined (Q_OS_LINUX) // http://stackoverflow.com/questions/246007/how-to-determine-whether-a-given-linux-is-32-bit-or-64-bit QString exe(QLatin1String("getconf")); QStringList args; args << QLatin1String("LONG_BIT"); QProcess proc; proc.setEnvironment(QProcess::systemEnvironment()); proc.start(exe, args); if (proc.waitForStarted() && proc.waitForFinished()) { QByteArray info = proc.readAll(); info.replace('\n',""); return info.toInt(); } return 0; // failed #elif defined (Q_OS_UNIX) || defined (Q_OS_MAC) QString exe(QLatin1String("uname")); QStringList args; args << QLatin1String("-m"); QProcess proc; proc.setEnvironment(QProcess::systemEnvironment()); proc.start(exe, args); if (proc.waitForStarted() && proc.waitForFinished()) { QByteArray info = proc.readAll(); info.replace('\n',""); if (info.indexOf("x86_64") >= 0) return 64; else if (info.indexOf("amd64") >= 0) return 64; else if (info.indexOf("ia64") >= 0) return 64; else if (info.indexOf("ppc64") >= 0) return 64; else if (info.indexOf("i386") >= 0) return 32; else if (info.indexOf("i686") >= 0) return 32; else if (info.indexOf("x86") >= 0) return 32; } return 0; // failed #else return 0; // unknown #endif }
int main(int argc, char **argv) { QApplication app(argc, argv, true); QTranslator custranldr; QTranslator translator; QString tnapplang; QString tnappcoun; QString clangcode = ""; QStringList allappargs = app.arguments(); QList<QPair<QString, QString> > oppairs; for (QList<QString>::const_iterator i = allappargs.constBegin(); i < allappargs.constEnd(); ++i) { if (i->count('=') == 1) oppairs.append(QPair<QString, QString>(i->section('=', 0, 0).simplified(), i->section('=',1, 1).simplified())); } for (QList<QPair<QString, QString> >::const_iterator i = oppairs.constBegin(); i < oppairs.constEnd(); ++i) { if (i->first.contains("lang", Qt::CaseInsensitive)) { clangcode = i->second; tnapplang = clangcode.left(2); if (clangcode.contains('_') && clangcode.size() == 5) { tnappcoun = clangcode.section('_', -1, -1); } break; } } if (clangcode.isEmpty()) { clangcode = QLocale::system().name(); tnapplang = clangcode.left(2); if (clangcode.contains('_') && clangcode.size() == 5) { tnappcoun = clangcode.section('_', -1, -1); } } QDir applocdir(app.applicationDirPath()); QStringList applocfiles = applocdir.entryList(QStringList() << "*.qm", QDir::Files); if (!applocfiles.isEmpty()) { QString custqmfilepath = applocfiles.at(0); if (!applocfiles.filter("unetbootin").isEmpty()) { custqmfilepath = applocfiles.filter("unetbootin").at(0); if (!applocfiles.filter("unetbootin").filter(tnapplang).isEmpty()) { custqmfilepath = applocfiles.filter("unetbootin").filter(tnapplang).at(0); if (!tnappcoun.isEmpty() && !applocfiles.filter("unetbootin").filter(tnapplang).filter(tnappcoun).isEmpty()) custqmfilepath = applocfiles.filter("unetbootin").filter(tnapplang).filter(tnappcoun).at(0); } } if (custranldr.load(custqmfilepath, app.applicationDirPath())) app.installTranslator(&custranldr); } if (!tnappcoun.isEmpty() && QFile::exists(QString("%1/unetbootin_%2_%3.qm").arg(app.applicationDirPath()).arg(tnapplang).arg(tnappcoun)) && translator.load(QString("%1/unetbootin_%2_%3.qm").arg(app.applicationDirPath()).arg(tnapplang).arg(tnappcoun))) { app.installTranslator(&translator); } else if (!tnappcoun.isEmpty() && QFile::exists(QString(":/unetbootin_%1_%2.qm").arg(tnapplang).arg(tnappcoun)) && translator.load(QString(":/unetbootin_%1_%2.qm").arg(tnapplang).arg(tnappcoun))) { app.installTranslator(&translator); } else if (!tnappcoun.isEmpty() && QFile::exists(QString("/usr/share/unetbootin/unetbootin_%1_%2.qm").arg(tnapplang).arg(tnappcoun)) && translator.load(QString("/usr/share/unetbootin/unetbootin_%1_%2.qm").arg(tnapplang).arg(tnappcoun))) { app.installTranslator(&translator); } else if (QFile::exists(QString("%1/unetbootin_%2.qm").arg(app.applicationDirPath(), tnapplang)) && translator.load(QString("%1/unetbootin_%2.qm").arg(app.applicationDirPath(), tnapplang))) { app.installTranslator(&translator); } else if (QFile::exists(QString(":/unetbootin_%1.qm").arg(tnapplang)) && translator.load(QString(":/unetbootin_%1.qm").arg(tnapplang))) { app.installTranslator(&translator); } else if (QFile::exists(QString("/usr/share/unetbootin/unetbootin_%1.qm").arg(tnapplang)) && translator.load(QString("/usr/share/unetbootin/unetbootin_%1.qm").arg(tnapplang))) { app.installTranslator(&translator); } else { tnapplang = "en"; tnappcoun = "US"; clangcode = "en_US"; } app.installTranslator(&translator); if (QObject::tr("LeftToRight") == "RightToLeft") app.setLayoutDirection(Qt::RightToLeft); #ifdef Q_OS_UNIX bool disabledrootcheck = false; for (QList<QPair<QString, QString> >::const_iterator i = oppairs.constBegin(); i < oppairs.constEnd(); ++i) { if (i->first.contains("rootcheck", Qt::CaseInsensitive)) { if (i->second.contains('n', Qt::CaseInsensitive)) disabledrootcheck = true; break; } } if (!disabledrootcheck) { QProcess whoamip; whoamip.start("whoami"); whoamip.waitForFinished(); if (QString(whoamip.readAll()).remove("\r").remove("\n") != "root") { QString argsconc = ""; for (int i = 1; i < allappargs.size(); ++i) { argsconc += QString("\"%1\" ").arg(allappargs.at(i)); } argsconc += "'rootcheck=no'"; QString gksulocation = checkforgraphicalsu("gksu"); if (gksulocation != "REQCNOTFOUND") { QProcess::startDetached(QString("%1 %2 %3").arg(gksulocation).arg(app.applicationFilePath()).arg(argsconc)); return 0; } QString kdesulocation = checkforgraphicalsu("kdesu"); if (kdesulocation != "REQCNOTFOUND") { QProcess::startDetached(QString("%1 %2 %3").arg(kdesulocation).arg(app.applicationFilePath()).arg(argsconc)); return 0; } QString gnomesulocation = checkforgraphicalsu("gnomesu"); if (gnomesulocation != "REQCNOTFOUND") { QProcess::startDetached(QString("%1 %2 %3").arg(gnomesulocation).arg(app.applicationFilePath()).arg(argsconc)); return 0; } QString kdesudolocation = checkforgraphicalsu("kdesudo"); if (kdesudolocation != "REQCNOTFOUND") { QProcess::startDetached(QString("%1 %2 %3").arg(kdesudolocation).arg(app.applicationFilePath()).arg(argsconc)); return 0; } QMessageBox rootmsgb; rootmsgb.setIcon(QMessageBox::Warning); rootmsgb.setWindowTitle(uninstaller::tr("Must run as root")); rootmsgb.setTextFormat(Qt::RichText); rootmsgb.setText(uninstaller::tr("%2 must be run as root. Close it, and re-run using either:<br/><b>sudo %1</b><br/>or:<br/><b>su -c '%1'</b>").arg(app.applicationFilePath()).arg(UNETBOOTINB)); rootmsgb.setStandardButtons(QMessageBox::Ok); switch (rootmsgb.exec()) { case QMessageBox::Ok: break; default: break; } } } #endif #ifdef Q_OS_WIN32 QSettings chkinst("HKEY_LOCAL_MACHINE\\Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\UNetbootin", QSettings::NativeFormat); #endif #ifdef Q_OS_UNIX QSettings chkinst(QSettings::SystemScope, "UNetbootin"); #endif if (chkinst.contains("Location")) { QMessageBox uninstmsgb; uninstmsgb.setIcon(QMessageBox::Information); uninstmsgb.setWindowTitle(uninstaller::tr("%1 Uninstaller").arg(UNETBOOTINB)); uninstmsgb.setText(uninstaller::tr("%1 is currently installed. Remove the existing version?").arg(UNETBOOTINB)); uninstmsgb.setStandardButtons(QMessageBox::Ok | QMessageBox::Cancel); switch (uninstmsgb.exec()) { case QMessageBox::Ok: { ubnUninst(); } case QMessageBox::Cancel: break; default: break; } return 0; } unetbootin unetbootin; unetbootin.appNlang = tnapplang; unetbootin.appDir = QDir::toNativeSeparators(QString("%1/").arg(app.applicationDirPath())); unetbootin.appLoc = app.applicationFilePath(); bool automate = unetbootin.ubninitialize(oppairs); unetbootin.show(); if (automate) unetbootin.on_okbutton_clicked(); return app.exec(); }
void TestRailInterface::updateRunWithResults() { QString filename = _outputDirectory + "/updateRunWithResults.py"; if (QFile::exists(filename)) { QFile::remove(filename); } QFile file(filename); if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) { QMessageBox::critical(0, "Internal error: " + QString(__FILE__) + ":" + QString::number(__LINE__), "Could not create " + filename); exit(-1); } QTextStream stream(&file); // Code to access TestRail stream << "from testrail import *\n"; stream << "client = APIClient('" << _url.toStdString().c_str() << "')\n"; stream << "client.user = '******'\n"; stream << "client.password = '******'\n\n"; // It is assumed that all the tests that haven't failed have passed // The failed tests are read, formatted and inserted into a set // A failure named 'Failure_1--tests.content.entity.material.apply.avatars.00000' is formatted to 'content/entity/material/apply/avatars' // This is the name of the test in TestRail // // A success is named `Success_<n>-tests. ... stream << "from os import listdir\n"; stream << "failed_tests = set()\n"; QDir dir(_outputDirectory + "/" + TEMP_NAME); if (dir.exists()) { stream << "for entry in listdir('" + _outputDirectory + "/" + TEMP_NAME + "'):\n"; // skip over successes stream << "\tif entry.split('_')[0] == 'Success':\n"; stream << "\t\tcontinue\n"; stream << "\tparts = entry.split('--tests.')[1].split('.')\n"; stream << "\tfailed_test = parts[0]\n"; stream << "\tfor i in range(1, len(parts) - 1):\n"; stream << "\t\tfailed_test = failed_test + '/' + parts[i]\n"; stream << "\tfailed_tests.add(failed_test)\n\n"; } // Initialize the array of results that will be eventually used to update TestRail stream << "status_ids = []\n"; stream << "case_ids = []\n"; int runID = _runIDs[_testRailResultsSelectorWindow.getRunID()]; stream << "tests = client.send_get('get_tests/" + QString::number(runID) + "')\n\n"; stream << "for test in tests:\n"; // status_id's: 1 - Passed // 2 - Blocked // 3 - Untested // 4 - Retest // 5 - Failed stream << "\tstatus_id = 1\n"; stream << "\tif test['title'] in failed_tests:\n"; stream << "\t\tstatus_id = 5\n"; stream << "\tcase_ids.append(test['case_id'])\n"; stream << "\tstatus_ids.append(status_id)\n\n"; // We can now update the test (note that all tests need to be updated) // An example request is as follows: // // "results" : [ // { 'case_id': 1, 'status_id': 5 }, // { 'case_id': 2, 'status_id': 1 } // ] // stream << "results = []\n"; stream << "for i in range(len(case_ids)):\n"; stream << "\tresults.append({'case_id': case_ids[i], 'status_id': status_ids[i] })\n\n"; stream << "data = { 'results': results }\n"; stream << "client.send_post('add_results_for_cases/' + str(" << runID << "), data)\n"; // Also update the run QStringList parts = _testResults.split('/'); QString resultName = parts[parts.length() - 1].split('.')[0]; stream << "client.send_post('update_run/' + str(" << runID << ")," << " { 'description' : 'https://hifi-qa.s3.amazonaws.com/" << resultName << "/TestResults.html' })\n"; file.close(); if (QMessageBox::Yes == QMessageBox(QMessageBox::Information, "Python script has been created", "Do you want to run the script and update TestRail?", QMessageBox::Yes | QMessageBox::No).exec() ) { QProcess* process = new QProcess(); connect(process, &QProcess::started, this, [=]() { _busyWindow.exec(); }); connect(process, SIGNAL(finished(int)), process, SLOT(deleteLater())); connect(process, static_cast<void (QProcess::*)(int, QProcess::ExitStatus)>(&QProcess::finished), this, [=](int exitCode, QProcess::ExitStatus exitStatus) { _busyWindow.hide(); }); #ifdef Q_OS_WIN QStringList parameters = QStringList() << _outputDirectory + "/updateRunWithResults.py"; process->start(_pythonCommand, parameters); #elif defined Q_OS_MAC QStringList parameters = QStringList() << "-c" << _pythonCommand + " " + _outputDirectory + "/updateRunWithResults.py"; process->start("sh", parameters); #endif } }
void SimpleTextureScene::initialise() { m_funcs = m_context->functions(); m_funcs->initializeOpenGLFunctions(); // mplayer's output is definitely easier to parse than ffmpeg's... QProcess movieFileParameters; movieFileParameters.start("mplayer", QStringList() << "-identify" << "-vo" << "null" << "-ao" << "null" << "-frames" << "0" << "-vc" << "null" << "--" << m_movieFile, QIODevice::ReadOnly); movieFileParameters.waitForFinished(); QString mplayerOutput = QString::fromLocal8Bit(movieFileParameters.readAllStandardOutput()); QRegularExpression widthRe("^ID_VIDEO_WIDTH=(.*)", QRegularExpression::MultilineOption); QRegularExpressionMatch widthMatch = widthRe.match(mplayerOutput); if (widthMatch.hasMatch()) m_frameSize.setWidth(widthMatch.captured(1).toInt()); QRegularExpression heightRe("^ID_VIDEO_HEIGHT=(.*)", QRegularExpression::MultilineOption); QRegularExpressionMatch heightMatch = heightRe.match(mplayerOutput); if (heightMatch.hasMatch()) m_frameSize.setHeight(heightMatch.captured(1).toInt()); if (m_frameSize.width() <= 0 || m_frameSize.height() <= 0) qFatal("Cannot determine the input file frame size!"); qDebug() << "Got frame size:" << m_frameSize; // Set the clear color to black glClearColor( 0.0f, 0.0f, 0.0f, 1.0f ); // Prepare a complete shader program... prepareShaderProgram( ":/shaders/simpletexture.vert", ":/shaders/simpletexture.frag" ); // Prepare the vertex, texture and index buffers prepareVertexBuffers(); // Prepare the VAO prepareVertexArrayObject(); // Prepare the texture data itself (textures and pixel unpack buffer objects) prepareTexture(); // Link texture unit 0 to the "ySampler" variable in the fragment shader m_shader.setUniformValue( "ySampler", 0 ); // Link texture unit 1 to the "uvSampler" variable in the fragment shader m_shader.setUniformValue( "uvSampler", 1 ); m_videoDecoder.start("ffmpeg", QStringList() << "-i" << m_movieFile << "-f" << "rawvideo" << "-vcodec" << "rawvideo" << "-pix_fmt" << "nv12" << "-an" << "-ss" << "180" // jump to 3m << "-", QIODevice::ReadOnly); m_videoDecoder.closeWriteChannel(); m_videoDecoder.closeReadChannel(QProcess::StandardError); }
int main(int argc, char **argv){ QApplication app(argc, argv, true); #ifdef Q_OS_WIN32 app.setFont(QFont("Microsoft YaHei")); #endif #ifdef Q_OS_LINUX app.setFont(QFont("WenQuanYi Micro Hei")); #endif //just for debug //qInstallMessageHandler(crashMessageOutput); loadTranslate(app); #ifdef Q_OS_UNIX bool disabledrootcheck = false; //disabledrootcheck = true; QStringList allappargs = app.arguments(); if (!disabledrootcheck) { QProcess whoamip; whoamip.start("whoami"); whoamip.waitForFinished(); if (QString(whoamip.readAll()).remove("\r").remove("\n") != "root") { QString argsconc = ""; QString argsconcSingleQuote = ""; for (int i = 1; i < allappargs.size(); ++i) { argsconc += QString("\"%1\" ").arg(allappargs.at(i)); argsconcSingleQuote += QString("'%1' ").arg(allappargs.at(i)); } argsconc += "\"rootcheck=no\""; argsconcSingleQuote += "'rootcheck=no'"; #ifdef Q_OS_LINUX QString gksulocation = checkforgraphicalsu("gksu"); if (gksulocation != "REQCNOTFOUND") { QProcess::startDetached(QString("%1 %2 %3").arg(gksulocation).arg(app.applicationFilePath()).arg(argsconc)); return 0; } QString kdesulocation = checkforgraphicalsu("kdesu"); if (kdesulocation != "REQCNOTFOUND") { QProcess::startDetached(QString("%1 %2 %3").arg(kdesulocation).arg(app.applicationFilePath()).arg(argsconc)); return 0; } QString gnomesulocation = checkforgraphicalsu("gnomesu"); if (gnomesulocation != "REQCNOTFOUND") { QProcess::startDetached(QString("%1 %2 %3").arg(gnomesulocation).arg(app.applicationFilePath()).arg(argsconc)); return 0; } QString kdesudolocation = checkforgraphicalsu("kdesudo"); if (kdesudolocation != "REQCNOTFOUND") { QProcess::startDetached(QString("%1 %2 %3").arg(kdesudolocation).arg(app.applicationFilePath()).arg(argsconc)); return 0; } QMessageBox rootmsgb; rootmsgb.setIcon(QMessageBox::Warning); rootmsgb.setWindowTitle(uninstaller::tr("Must run as root")); rootmsgb.setTextFormat(Qt::RichText); rootmsgb.setText(uninstaller::tr("%2 must be run as root. Close it, and re-run using either:<br/><b>sudo %1</b><br/>or:<br/><b>su - -c '%1'</b>").arg(app.applicationFilePath()).arg(UNETBOOTINB)); rootmsgb.setStandardButtons(QMessageBox::Ok); switch (rootmsgb.exec()) { case QMessageBox::Ok: break; default: break; } #endif #ifdef Q_OS_MAC /* QProcess osascriptProc; osascriptProc.start("osascript"); osascriptProc.write(QString("do shell script \""+app.applicationFilePath()+"\" with administrator privileges\n").toAscii().data()); osascriptProc.closeWriteChannel(); osascriptProc.waitForFinished(-1); */ //qDebug() << QString("osascript -e 'do shell script \"%1 %2\" with administrator privileges'").arg(app.applicationFilePath()).arg(argsconc); //QProcess::startDetached(QString("osascript -e 'do shell script \"%1 %2\" with administrator privileges'").arg(app.applicationFilePath()).arg(argsconc)); QProcess::startDetached("osascript", QStringList() << "-e" << QString("do shell script \"'%1' %2\" with administrator privileges").arg(app.applicationFilePath()).arg(argsconcSingleQuote)); return 0; #endif } } #endif qmlRegisterType<BootMaker>("com.deepin.bootmaker", 1, 0, "BootMaker"); qmlRegisterType<DOverrideWindow>("com.deepin.usbcreator", 1, 0, "DOverrideWindow"); qmlRegisterType<DWindow>("com.deepin.usbcreator", 1, 0, "DWindow"); qmlRegisterType<DIcon>("com.deepin.usbcreator", 1, 0, "DIcon"); qmlRegisterType<DDropArea>("com.deepin.usbcreator", 1, 0, "DDropArea"); QQmlApplicationEngine engine; engine.addImportPath("qrc:/qml/"); #ifdef Q_OS_WIN32 if (CheckIsXP()){ app.setFont(QFont("SimHei", 12)); engine.load(QUrl("qrc:/qml/xp-fix-mainui.qml")); } else{ engine.load(QUrl("qrc:/qml/mainui.qml")); } #else engine.load(QUrl("qrc:/qml/mainui.qml")); #endif app.setOverrideCursor( QCursor( Qt::ArrowCursor ) ); QList<QObject *> roots = engine.rootObjects(); QObject *topLevel = roots.value(0); QQuickWindow *window = qobject_cast<QQuickWindow *>(topLevel); if (!window) { qCritical("load qrc:/qml/mainui.qml error!!"); } QIcon icon; icon.addFile(":/image/deepin-boot-maker.png"); window->setIcon(icon); window->show(); window->setTitle(QApplication::tr("Deepin Boot Maker")); return app.exec(); }
/*********************************************************************** * 函数名称: PingAClient * 函数功能: ping 客户端,查看是否可以ping通 * 参数说明: * 作者 : 爱在梦幻谷 * 最后修改: 2013年3月14日21:00:52 ***********************************************************************/ bool login::PingAClient(QString clientip) { if (clientip.isEmpty()) return false; int iTimeOut=2000; QDateTime dd=QDateTime::currentDateTime().addMSecs(iTimeOut); #ifdef WIN32 QString sCommand=QString("ping -n 1 -i 2 %1 ").arg(clientip); #else QString sCommand=QString("ping -c1 -W2 %1 ").arg(clientip); #endif QProcess process; process.start(sCommand); if (!process.waitForStarted(iTimeOut)) { qDebug() << process.errorString(); process.close(); return false; } if (QDateTime::currentDateTime()>=dd) { process.close(); return false; } //2.. if (!process.waitForReadyRead(iTimeOut)) { process.close(); return false; } if (QDateTime::currentDateTime()>=dd) { process.close(); return false; } //3.. QByteArray bb=process.readAll(); process.close(); //4.analyse; QStringList ts; SpilitStr(QString::fromLocal8Bit(bb),"\n",ts); #ifdef WIN32 QString tag1=QString("来自 %1").arg(clientip); #else QString tag1=QString(" from %1").arg(clientip); #endif bool suc=false; for (int i=ts.count()-1;i>=0;i--) { if (QString(ts.value(i)).indexOf(tag1)>0) { suc=true; break; } } return suc; }
/** * Starting point for the retracing thread. * * Overrides QThread::run(). */ void Retracer::run() { QString msg = QLatin1String("Replay finished!"); /* * Construct command line */ QString prog; QStringList arguments; switch (m_api) { case trace::API_GL: prog = QLatin1String("glretrace"); break; case trace::API_EGL: prog = QLatin1String("eglretrace"); break; case trace::API_DX: case trace::API_D3D7: case trace::API_D3D8: case trace::API_D3D9: case trace::API_DXGI: #ifdef Q_OS_WIN prog = QLatin1String("d3dretrace"); #else prog = QLatin1String("wine"); arguments << QLatin1String("d3dretrace.exe"); #endif break; default: emit finished(QLatin1String("Unsupported API")); return; } arguments << retraceArguments() << m_fileName; /* * Support remote execution on a separate target. */ if (m_remoteTarget.length() != 0) { arguments.prepend(prog); arguments.prepend(m_remoteTarget); prog = QLatin1String("ssh"); } /* * Start the process. */ { QDebug debug(QtDebugMsg); debug << "Running:"; debug << prog; foreach (const QString &argument, arguments) { debug << argument; } } QProcess process; process.start(prog, arguments, QIODevice::ReadOnly); if (!process.waitForStarted(-1)) { emit finished(QLatin1String("Could not start process")); return; } /* * Process standard output */ ImageHash thumbnails; QVariantMap parsedJson; trace::Profile* profile = NULL; process.setReadChannel(QProcess::StandardOutput); if (process.waitForReadyRead(-1)) { BlockingIODevice io(&process); if (m_captureState) { parsedJson = decodeUBJSONObject(&io).toMap(); process.waitForFinished(-1); } else if (m_captureThumbnails) { /* * Parse concatenated PNM images from output. */ while (!io.atEnd()) { image::PNMInfo info; char header[512]; qint64 headerSize = 0; int headerLines = 3; // assume no optional comment line for (int headerLine = 0; headerLine < headerLines; ++headerLine) { qint64 headerRead = io.readLine(&header[headerSize], sizeof(header) - headerSize); // if header actually contains optional comment line, ... if (headerLine == 1 && header[headerSize] == '#') { ++headerLines; } headerSize += headerRead; } const char *headerEnd = image::readPNMHeader(header, headerSize, info); // if invalid PNM header was encountered, ... if (headerEnd == NULL || info.channelType != image::TYPE_UNORM8) { qDebug() << "error: invalid snapshot stream encountered"; break; } unsigned channels = info.channels; unsigned width = info.width; unsigned height = info.height; // qDebug() << "channels: " << channels << ", width: " << width << ", height: " << height"; QImage snapshot = QImage(width, height, channels == 1 ? QImage::Format_Mono : QImage::Format_RGB888); int rowBytes = channels * width; for (int y = 0; y < height; ++y) { unsigned char *scanLine = snapshot.scanLine(y); qint64 readBytes = io.read((char *) scanLine, rowBytes); Q_ASSERT(readBytes == rowBytes); (void)readBytes; } QImage thumb = thumbnail(snapshot); thumbnails.insert(info.commentNumber, thumb); } Q_ASSERT(process.state() != QProcess::Running); } else if (isProfiling()) { profile = new trace::Profile(); while (!io.atEnd()) { char line[256]; qint64 lineLength; lineLength = io.readLine(line, 256); if (lineLength == -1) break; trace::Profiler::parseLine(line, profile); } } else { QByteArray output; output = process.readAllStandardOutput(); if (output.length() < 80) { msg = QString::fromUtf8(output); } } } /* * Wait for process termination */ process.waitForFinished(-1); if (process.exitStatus() != QProcess::NormalExit) { msg = QLatin1String("Process crashed"); } else if (process.exitCode() != 0) { msg = QLatin1String("Process exited with non zero exit code"); } /* * Parse errors. */ QList<ApiTraceError> errors; process.setReadChannel(QProcess::StandardError); QRegExp regexp("(^\\d+): +(\\b\\w+\\b): ([^\\r\\n]+)[\\r\\n]*$"); while (!process.atEnd()) { QString line = process.readLine(); if (regexp.indexIn(line) != -1) { ApiTraceError error; error.callIndex = regexp.cap(1).toInt(); error.type = regexp.cap(2); error.message = regexp.cap(3); errors.append(error); } else if (!errors.isEmpty()) { // Probably a multiligne message ApiTraceError &previous = errors.last(); if (line.endsWith("\n")) { line.chop(1); } previous.message.append('\n'); previous.message.append(line); } } /* * Emit signals */ if (m_captureState) { ApiTraceState *state = new ApiTraceState(parsedJson); emit foundState(state); } if (m_captureThumbnails && !thumbnails.isEmpty()) { emit foundThumbnails(thumbnails); } if (isProfiling() && profile) { emit foundProfile(profile); } if (!errors.isEmpty()) { emit retraceErrors(errors); } emit finished(msg); }
/*! returns a string containing the general information about the file \c name and some content specific information (number of columns and lines for ASCII, color-depth for images etc.). */ QString FileDataSource::fileInfoString(const QString &name){ QString infoString; QFileInfo fileInfo; QString fileTypeString; QIODevice *file = new QFile(name); QString fileName; if (name.at(0) != QDir::separator()) { fileName = QDir::homePath() + QDir::separator() + name; } else { fileName = name; } if(file==0) file = new QFile(fileName); if (file->open(QIODevice::ReadOnly)){ QStringList infoStrings; //general information about the file infoStrings << "<u><b>" + fileName + "</b></u><br>"; fileInfo.setFile(fileName); infoStrings << i18n("Readable: %1", fileInfo.isReadable() ? i18n("yes") : i18n("no")); infoStrings << i18n("Writable: %1", fileInfo.isWritable() ? i18n("yes") : i18n("no")); infoStrings << i18n("Executable: %1", fileInfo.isExecutable() ? i18n("yes") : i18n("no")); infoStrings << i18n("Created: %1", fileInfo.created().toString()); infoStrings << i18n("Last modified: %1", fileInfo.lastModified().toString()); infoStrings << i18n("Last read: %1", fileInfo.lastRead().toString()); infoStrings << i18n("Owner: %1", fileInfo.owner()); infoStrings << i18n("Group: %1", fileInfo.group()); infoStrings << i18n("Size: %1", i18np("%1 cByte", "%1 cBytes", fileInfo.size())); #ifdef HAVE_FITS if (fileName.endsWith(QLatin1String(".fits"))) { FITSFilter* fitsFilter = new FITSFilter; infoStrings << i18n("Images: %1", QString::number(fitsFilter->imagesCount(fileName) )); infoStrings << i18n("Tables: %1", QString::number(fitsFilter->tablesCount(fileName) )); delete fitsFilter; } #endif // file type and type specific information about the file #ifdef Q_OS_LINUX QProcess *proc = new QProcess(); QStringList args; args<<"-b"<<fileName; proc->start( "file", args); if(proc->waitForReadyRead(1000) == false){ infoStrings << i18n("Could not open file %1 for reading.", fileName); }else{ fileTypeString = proc->readLine(); if( fileTypeString.contains(i18n("cannot open")) ) fileTypeString=""; else { fileTypeString.remove(fileTypeString.length()-1,1); // remove '\n' } } infoStrings << i18n("File type: %1", fileTypeString); #endif //TODO depending on the file type, generate additional information about the file: //Number of lines for ASCII, color-depth for images etc. Use the specific filters here. // port the old labplot1.6 code. if( fileTypeString.contains("ASCII")){ infoStrings << "<br/>"; infoStrings << i18n("Number of columns: %1", AsciiFilter::columnNumber(fileName)); infoStrings << i18n("Number of lines: %1", AsciiFilter::lineNumber(fileName)); } infoString += infoStrings.join("<br/>"); } else{ infoString += i18n("Could not open file %1 for reading.", fileName); } return infoString; }
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(); QMessageBox::critical(this, "Syntax error !", "One or more of your expressions are wrong !\nNear "+list3[0]+" "+list3[1]+" of dump"); //return NULL; } catch(sort_not_found& sort){ //Catch a error if the user delete a sort before associated actions ! QMessageBox::critical(this, "Error !", "Delete the associated actions before the process !"); } }
void wrapInFunction() { //! [0] QProcess builder; builder.setProcessChannelMode(QProcess::MergedChannels); builder.start("make", QStringList() << "-j2"); if (!builder.waitForFinished()) qDebug() << "Make failed:" << builder.errorString(); else qDebug() << "Make output:" << builder.readAll(); //! [0] //! [1] QProcess more; more.start("more"); more.write("Text to display"); more.closeWriteChannel(); // QProcess will emit readyRead() once "more" starts printing //! [1] //! [2] command1 | command2 //! [2] //! [3] QProcess process1; QProcess process2; process1.setStandardOutputProcess(process2); process1.start("command1"); process2.start("command2"); //! [3] //! [4] class SandboxProcess : public QProcess { ... protected: void setupChildProcess(); ... }; void SandboxProcess::setupChildProcess() { // Drop all privileges in the child process, and enter // a chroot jail. #if defined Q_OS_UNIX ::setgroups(0, 0); ::chroot("/etc/safe"); ::chdir("/"); ::setgid(safeGid); ::setuid(safeUid); ::umask(0); #endif } //! [4] //! [5] QProcess process; process.start("del /s *.txt"); // same as process.start("del", QStringList() << "/s" << "*.txt"); ... //! [5] //! [6] QProcess process; process.start("dir \"My Documents\""); //! [6] //! [7] QProcess process; process.start("dir \"\"\"My Documents\"\"\""); //! [7] //! [8] QStringList environment = QProcess::systemEnvironment(); // environment = {"PATH=/usr/bin:/usr/local/bin", // "USER=greg", "HOME=/home/greg"} //! [8] }
void installWorker::process() { p = new QProcess(this); //p->setProcessChannelMode(QProcess::MergedChannels); connect(p, SIGNAL(finished(int)), this, SLOT(lastProcessFinished(int))); connect(p, SIGNAL(readyReadStandardOutput()), this, SLOT(outputAvaliable())); connect(p, SIGNAL(readyReadStandardError()), this, SLOT(errorAvaliable())); standardOutput.append("[theos_installer] Executing command umount /mnt\n"); emit output(standardOutput); p->start("umount", QStringList() << "/mnt"); p->waitForFinished(-1); if (parentWindow->formatPartition) { lastProcessDone = false; emit message("Formatting " + parentWindow->partition + "..."); standardOutput.append("[theos_installer] Executing command mkfs -t ext4 -F -F " + parentWindow->partition); p->start("mkfs -t ext4 -F -F " + parentWindow->partition); if (!p->waitForStarted()) { standardOutput.append("[theos_installer] Error occurred executing command!\n"); } p->waitForFinished(-1); } emit message("Mounting " + parentWindow->partition + "..."); standardOutput.append("[theos_installer] Executing command mount " + parentWindow->partition + " /mnt\n"); emit output(standardOutput); p->start("mount " + parentWindow->partition + " /mnt"); p->waitForFinished(-1); if (QDir("/sys/firmware/efi").exists()) { standardOutput.append("This system is EFI, attempting to mount ESP onto /boot\n"); emit output(standardOutput); QProcess* lsblk = new QProcess(); lsblk->start("lsblk -r --output NAME,PARTTYPE"); lsblk->waitForStarted(-1); lsblk->waitForFinished(-1); QString lsblkOutput(lsblk->readAllStandardOutput()); for (QString partition : lsblkOutput.split("\n")) { if (partition.split(" ").count() != 1) { if (partition.split(" ").at(1).contains("C12A7328-F81F-11D2-BA4B-00A0C93EC93B", Qt::CaseInsensitive)) { QDir("/mnt").mkdir("boot"); emit message("Mounting " + partition.split(" ").at(0) + "..."); standardOutput.append("[theos_installer] Executing command mount " + parentWindow->partition + " /mnt/boot\n"); emit output(standardOutput); p->start("mount /dev/" + partition.split(" ").at(0) + " /mnt/boot"); p->waitForFinished(-1); break; } } } } emit message("Downloading and copying new files..."); standardOutput.append("[theos_installer] Executing command pacstrap /mnt base base-devel linux-headers\n"); emit output(standardOutput); p->start("pacstrap /mnt base base-devel linux-headers"); p->waitForFinished(-1); if (p->exitCode() != 0) { emit message("An error occurred. Inspect the output to see what happened."); emit failed(); return; } emit message("Configuring system..."); standardOutput.append("[theos_installer] Generating fstab...\n"); emit output(standardOutput); QProcess *fstab = new QProcess(this); fstab->start("genfstab -p /mnt"); fstab->waitForFinished(); QFile fstabFile("/mnt/etc/fstab"); fstabFile.open(QFile::WriteOnly); fstabFile.write(fstab->readAllStandardOutput()); fstabFile.close(); standardOutput.append("[theos_installer] Setting hostname...\n"); while (parentWindow->hostname == "") {} //Stall until hostname is ready QFile hostnameFile("/mnt/etc/hostname"); hostnameFile.open(QFile::WriteOnly); hostnameFile.write(parentWindow->hostname.toUtf8()); hostnameFile.close(); standardOutput.append("[theos_installer] Generating locales...\n"); QFile::copy("/etc/locale.gen", "/mnt/etc/locale.gen"); standardOutput.append("[theos_installer] Executing command arch-chroot /mnt locale-gen \n"); emit output(standardOutput); p->start("arch-chroot /mnt locale-gen"); p->waitForFinished(-1); standardOutput.append("[theos_installer] Executing command arch-chroot /mnt mkinitcpio -p linux\n"); emit output(standardOutput); p->start("arch-chroot /mnt mkinitcpio -p linux"); p->waitForFinished(-1); emit message("Downloading and installing bootloader..."); standardOutput.append("[theos_installer] Executing command pacstrap /mnt os-prober grub\n"); emit output(standardOutput); p->start("pacstrap /mnt os-prober efibootmgr grub"); p->waitForFinished(-1); QString disk = parentWindow->partition; disk.chop(1); if (QDir("/sys/firmware/efi").exists()) { standardOutput.append("[theos_installer] Executing command arch-chroot /mnt grub-install --target=x86_64-efi --efi-directory=/boot/ --bootloader-id=grub\n"); p->start("arch-chroot /mnt grub-install --target=x86_64-efi --efi-directory=/boot/ --bootloader-id=grub"); p->waitForFinished(-1); } else { standardOutput.append("[theos_installer] Executing command arch-chroot /mnt grub-install --target=i386-pc " + disk + "\n"); emit output(standardOutput); p->start("arch-chroot /mnt grub-install --target=i386-pc " + disk); p->waitForFinished(-1); } QFile grubDefault("/mnt/etc/default/grub"); grubDefault.open(QFile::ReadOnly); QString grubDefaults(grubDefault.readAll()); grubDefault.close(); QStringList grubDefaultsArray = grubDefaults.split("\n"); for (QString line : grubDefaultsArray) { if (line.startsWith("GRUB_CMDLINE_LINUX_DEFAULT")) { int index = grubDefaultsArray.indexOf(line); grubDefaultsArray.removeAt(index); grubDefaultsArray.insert(index, "GRUB_CMDLINE_LINUX_DEFAULT=\"quiet splash\""); } } grubDefaults = ""; for (QString line : grubDefaultsArray) { grubDefaults.append(line + "\n"); } p->waitForFinished(-1); grubDefault.open(QFile::WriteOnly); grubDefault.write(grubDefaults.toUtf8()); grubDefault.close(); standardOutput.append("[theos_installer] Executing command arch-chroot /mnt grub-mkconfig -o /boot/grub/grub.cfg\n"); emit output(standardOutput); p->start("arch-chroot /mnt grub-mkconfig -o /boot/grub/grub.cfg"); p->waitForFinished(-1); QFile grubConfig("/mnt/boot/grub/grub.cfg"); grubConfig.open(QFile::ReadWrite); QString grubConfiguration(grubConfig.readAll()); grubConfig.close(); grubConfiguration = grubConfiguration.replace("Arch Linux", "theOS"); grubConfig.open(QFile::ReadWrite); grubConfig.write(grubConfiguration.toUtf8()); grubConfig.close(); emit message("Downloading and installing new files..."); standardOutput.append("[theos_installer] Installing additional packages...\n"); emit output(standardOutput); p->start(QString("pacstrap /mnt xf86-video-vesa xf86-video-intel xf86-video-nouveau xf86-video-vmware kde-cli-tools kdesu") .append(" virtualbox-guest-utils xorg-server xorg-xinit xf86-input-synaptics lightdm breeze breeze-gtk breeze-icons") .append(" breeze-kde4 networkmanager gtk3 breeze-gtk chromium kinfocenter partitionmanager ntfs-3g") .append(" hfsprogs kate bluez bluedevil libreoffice-fresh hunspell hunspell-en kdegraphics-okular") .append(" ksuperkey kscreen user-manager kdeconnect gstreamer0.10 gstreamer0.10-bad gstreamer0.10-plugins") .append(" gstreamer0.10-base gstreamer0.10-base-plugins gstreamer0.10-ffmpeg gstreamer0.10-good") .append(" gstreamer0.10-good-plugins gstreamer0.10-ugly gstreamer0.10-ugly-plugins gst-plugins-good") .append(" gst-plugins-ugly kmail korganizer cups ark kcalc gwenview alsa-utils pulseaudio pulseaudio-alsa festival festival-english")); p->waitForFinished(-1); QDir localPackagesDir("/root/.packages/"); QDirIterator *packageIterator = new QDirIterator(localPackagesDir); while (packageIterator->hasNext()) { QString packageName = packageIterator->next(); QString packageToInstall = packageName; QString installLocation = "/mnt/var/cache/pacman/pkg/" + packageName.remove("/root/.packages/"); if (!QFile::copy(packageToInstall, installLocation)) { standardOutput.append("[theos_installer] Error copying " + packageToInstall + " to " + installLocation); emit output(standardOutput); } p->start("arch-chroot /mnt pacman -U --noconfirm " + installLocation.remove(0, 4)); p->waitForFinished(-1); } emit message("Configuring System..."); standardOutput.append("[theos_installer] Configuring users...\n"); QFile chfnDefault("/mnt/etc/login.defs"); chfnDefault.open(QFile::ReadOnly); QString chfnDefaults(chfnDefault.readAll()); chfnDefault.close(); QStringList chfnDefaultsArray = chfnDefaults.split("\n"); for (QString line : chfnDefaultsArray) { if (line.startsWith("CHFN_RESTRICT")) { int index = chfnDefaultsArray.indexOf(line); chfnDefaultsArray.removeAt(index); chfnDefaultsArray.insert(index, "CHFN_RESTRICT frwh"); } } chfnDefaults = ""; for (QString line : chfnDefaultsArray) { chfnDefaults.append(line + "\n"); } chfnDefault.open(QFile::WriteOnly); chfnDefault.write(chfnDefaults.toUtf8()); chfnDefault.close(); p->start("useradd -R /mnt -g wheel -M " + parentWindow->loginname); p->waitForFinished(-1); p->start("arch-chroot /mnt chfn -f \"" + parentWindow->fullname + "\" " + parentWindow->loginname); p->waitForFinished(-1); p->start("chpasswd -R /mnt"); p->write(QString("root:" + parentWindow->password + "\n").toUtf8()); p->write(QString(parentWindow->loginname + ":" + parentWindow->password + "\n").toUtf8()); p->closeWriteChannel(); p->waitForFinished(-1); QFile sudoersConfig("/mnt/etc/sudoers"); sudoersConfig.open(QFile::ReadWrite); QString sudoersConfiguration(sudoersConfig.readAll()); sudoersConfig.close(); sudoersConfiguration = sudoersConfiguration.replace("# %wheel ALL=(ALL) ALL", "%wheel ALL=(ALL) ALL"); sudoersConfig.open(QFile::ReadWrite); sudoersConfig.write(sudoersConfiguration.toUtf8()); sudoersConfig.close(); standardOutput.append("[theos_installer] Configuring services...\n"); p->start("arch-chroot /mnt systemctl enable NetworkManager"); p->waitForFinished(-1); p->start("arch-chroot /mnt systemctl enable bluetooth"); p->waitForFinished(-1); p->start("arch-chroot /mnt systemctl enable lightdm"); p->waitForFinished(-1); QFile lightdmConf("/mnt/etc/lightdm/lightdm.conf"); lightdmConf.open(QFile::ReadOnly); QString lightdmDefaults(lightdmConf.readAll()); lightdmConf.close(); QStringList lightdmDefaultsArray = lightdmDefaults.split("\n"); for (QString line : lightdmDefaultsArray) { if (line.startsWith("#greeter-session=")) { int index = lightdmDefaultsArray.indexOf(line); lightdmDefaultsArray.removeAt(index); lightdmDefaultsArray.insert(index, "greeter-session=lightdm-webkit2-greeter"); } } lightdmDefaults = ""; for (QString line : lightdmDefaultsArray) { lightdmDefaults.append(line + "\n"); } lightdmConf.open(QFile::WriteOnly); lightdmConf.write(lightdmDefaults.toUtf8()); lightdmConf.close(); QFile lightdmWebkitConf("/mnt/etc/lightdm/lightdm-webkit2-greeter.conf"); lightdmWebkitConf.open(QFile::WriteOnly); lightdmWebkitConf.write(QString("[greeter]\nwebkit-theme=contemporary\n").toUtf8()); lightdmWebkitConf.close(); QFile initConf("/mnt/etc/mkinitcpio.conf"); initConf.open(QFile::ReadOnly); QString init(initConf.readAll()); initConf.close(); QStringList initArray = init.split("\n"); for (QString line : initArray) { if (line.startsWith("HOOKS")) { int index = initArray.indexOf(line); initArray.removeAt(index); initArray.insert(index, "HOOKS=\"base udev plymouth autodetect modconf block filesystems keyboard fsck\""); } else if (line.startsWith("MODULES")) { int index = initArray.indexOf(line); initArray.removeAt(index); initArray.insert(index, "MODULES=\"i915\""); } } init = ""; for (QString line : initArray) { init.append(line + "\n"); } initConf.open(QFile::WriteOnly); initConf.write(init.toUtf8()); initConf.close(); QFile("/etc/os-release").copy("/mnt/etc/os-release"); p->start("arch-chroot /mnt plymouth-set-default-theme theos --rebuild-initrd" ); p->waitForFinished(-1); p->start("cp -r /root /mnt/home/" + parentWindow->loginname); p->waitForFinished(-1); p->start("arch-chroot /mnt chown -R " + parentWindow->loginname + " /home/" + parentWindow->loginname + "/ " ); p->waitForFinished(-1); emit finished(); }
QProcess * EngineSync::startSlaveProcess(int no) { QDir programDir = QFileInfo( QCoreApplication::applicationFilePath() ).absoluteDir(); QProcessEnvironment env = QProcessEnvironment::systemEnvironment(); QString engineExe = QFileInfo( QCoreApplication::applicationFilePath() ).absoluteDir().absoluteFilePath("JASPEngine"); QStringList args; args << QString::number(no); args << QString::number(ProcessInfo::currentPID()); #ifdef __WIN32__ QString rHomePath = programDir.absoluteFilePath("R"); #elif __APPLE__ QString rHomePath = programDir.absoluteFilePath("../Frameworks/R.framework/Versions/" + QString::fromStdString(AppInfo::getRVersion()) + "/Resources"); #else //linux #ifndef R_HOME QString rHomePath = programDir.absoluteFilePath("R/lib/libR.so"); if (QFileInfo(rHomePath).exists() == false) #ifdef FLATPAK_USED rHomePath = "/app/lib64/R/"; #else rHomePath = "/usr/lib/R/"; #endif #else QString rHomePath; if (QDir::isRelativePath(R_HOME)) rHomePath = programDir.absoluteFilePath(R_HOME); else rHomePath = R_HOME; #endif #endif QDir rHome(rHomePath); #ifdef __WIN32__ #if defined(ARCH_32) #define ARCH_SUBPATH "i386" #else #define ARCH_SUBPATH "x64" #endif env.insert("PATH", programDir.absoluteFilePath("R\\library\\RInside\\libs\\" ARCH_SUBPATH) + ";" + programDir.absoluteFilePath("R\\library\\Rcpp\\libs\\" ARCH_SUBPATH) + ";" + programDir.absoluteFilePath("R\\bin\\" ARCH_SUBPATH)); env.insert("R_HOME", rHome.absolutePath()); #undef ARCH_SUBPATH env.insert("R_LIBS", rHome.absoluteFilePath("library")); env.insert("R_ENVIRON", "something-which-doesnt-exist"); env.insert("R_PROFILE", "something-which-doesnt-exist"); env.insert("R_PROFILE_USER", "something-which-doesnt-exist"); env.insert("R_ENVIRON_USER", "something-which-doesnt-exist"); env.insert("R_LIBS_SITE", "something-which-doesnt-exist"); env.insert("R_LIBS_USER", "something-which-doesnt-exist"); #elif __APPLE__ env.insert("R_HOME", rHome.absolutePath()); env.insert("R_LIBS", rHome.absoluteFilePath("library") + ":" + programDir.absoluteFilePath("R/library")); env.insert("R_ENVIRON", "something-which-doesnt-exist"); env.insert("R_PROFILE", "something-which-doesnt-exist"); env.insert("R_PROFILE_USER", "something-which-doesnt-exist"); env.insert("R_ENVIRON_USER", "something-which-doesnt-exist"); env.insert("R_LIBS_SITE", "something-which-doesnt-exist"); env.insert("R_LIBS_USER", "something-which-doesnt-exist"); #else // linux env.insert("LD_LIBRARY_PATH", rHome.absoluteFilePath("lib") + ":" + rHome.absoluteFilePath("library/RInside/lib") + ":" + rHome.absoluteFilePath("library/Rcpp/lib") + ":" + rHome.absoluteFilePath("site-library/RInside/lib") + ":" + rHome.absoluteFilePath("site-library/Rcpp/lib") + ":/app/lib/:/app/lib64/"); env.insert("R_HOME", rHome.absolutePath()); env.insert("R_LIBS", programDir.absoluteFilePath("R/library") + ":" + rHome.absoluteFilePath("library") + ":" + rHome.absoluteFilePath("site-library")); #endif QProcess *slave = new QProcess(this); slave->setProcessChannelMode(QProcess::ForwardedChannels); slave->setProcessEnvironment(env); slave->setWorkingDirectory(QFileInfo( QCoreApplication::applicationFilePath() ).absoluteDir().absolutePath()); #ifdef __WIN32__ /* On Windows, QProcess uses the Win32 API function CreateProcess to start child processes.In some casedesirable to fine-tune the parameters that are passed to CreateProcess. This is done by defining a CreateProcessArgumentModifier function and passing it to setCreateProcessArgumentsModifier bInheritHandles [in] If this parameter is TRUE, each inheritable handle in the calling process is inherited by the new process. If the parameter is FALSE, the handles are not inherited. */ slave->setCreateProcessArgumentsModifier([] (QProcess::CreateProcessArguments *args) { #ifndef QT_DEBUG args->inheritHandles = false; #endif }); #endif slave->start(engineExe, args); connect(slave, SIGNAL(readyReadStandardOutput()), this, SLOT(subProcessStandardOutput())); connect(slave, SIGNAL(readyReadStandardError()), this, SLOT(subProcessStandardError())); connect(slave, SIGNAL(error(QProcess::ProcessError)), this, SLOT(subProcessError(QProcess::ProcessError))); connect(slave, SIGNAL(finished(int,QProcess::ExitStatus)), this, SLOT(subprocessFinished(int,QProcess::ExitStatus))); connect(slave, SIGNAL(started()), this, SLOT(subProcessStarted())); return slave; }