void KeyCreator::accept() { // Validate data: if (editStorePass1->text().length() < 6) { emit warning(NULL, tr("Password must be at least 6 characters.")); editStorePass1->setFocus(); editStorePass1->selectAll(); return; } if (editStorePass1->text() != editStorePass2->text()) { emit warning(NULL, tr("Passwords do not match.")); editStorePass2->setFocus(); editStorePass2->selectAll(); return; } if (editAlias->text().isEmpty()) { emit warning(NULL, tr("Enter alias name.")); editAlias->setFocus(); editAlias->selectAll(); return; } if (editAliasPass1->text() != editAliasPass2->text()) { emit warning(NULL, tr("Passwords do not match.")); editAliasPass2->setFocus(); editAliasPass2->selectAll(); return; } if (editAliasPass1->text().length() < 6) { emit warning(NULL, tr("Password must be at least 6 characters.")); editAliasPass1->setFocus(); editAliasPass1->selectAll(); return; } // Create KeyStore and Alias: const QString FILENAME = QFileDialog::getSaveFileName(this, NULL, NULL, "KeyStore (*.keystore)"); if (FILENAME.isEmpty()) { return; } qDebug() << "Creating KeyStore..."; const QString ENV_PATH = qgetenv("PATH"); const QString JAVA_HOME = qgetenv("JAVA_HOME"); const QString KEYTOOL_CMD = QString("keytool -genkeypair -v -keystore \"%1\" -storepass \"%10\"" " -alias \"%2\" -keyalg RSA -keysize 2048" " -dname \"CN=%3, OU=%4, O=%5, L=%6, S=%7, C=%8\"" " -validity %9 -keypass \"%11\"") .arg(FILENAME) .arg(editAlias->text()) .arg(editName->text()) .arg(editUnit->text()) .arg(editOrgan->text()) .arg(editCity->text()) .arg(editState->text()) .arg(editCountry->text()) .arg(editYears->text().toInt() * 365); qputenv("PATH", ENV_PATH.toStdString().c_str()); qputenv("PATH", QString("%1;%2/bin").arg(ENV_PATH, JAVA_HOME).toStdString().c_str()); qDebug() << qPrintable(KEYTOOL_CMD.arg("*****", "*****")); QProcess p; p.start(KEYTOOL_CMD.arg(editStorePass1->text(), editAliasPass1->text())); qputenv("PATH", ENV_PATH.toStdString().c_str()); if (p.waitForStarted(-1)) { p.waitForFinished(10000); if (p.exitCode() != 0) { QString error_text = p.readAllStandardError().trimmed(); if (error_text.isEmpty()) error_text = p.readAllStandardOutput().trimmed(); qDebug() << qPrintable(QString("Keytool exit code: %1").arg(p.exitCode())); qDebug() << error_text; emit warning("Keytool", tr("%1: invalid parameters").arg("Keytool")); return; } } else { const QString ERROR_TEXT = tr("Error starting %1.\n" "Check your JDK installation and " "PATH environment variable.").arg("Keytool"); emit error("Keytool", ERROR_TEXT); return; } qDebug() << "Done.\n"; emit success("Keytool", tr("KeyStore successfully created/updated!")); emit created(FILENAME); clear(); QDialog::accept(); }
bool MountPointInfo::mount(const QString &host, const QString &mount_point, const QString &options, bool force) { is_mounted = true; #ifdef Q_OS_UNIX DEBUG() << "Mounting" << host << "to" << mount_point << is_mounted; if(is_mounted && !force) { WARN() << "Share" << this->s_host << "is already mounted to" << this->m_mount_point; return true; } this->s_host = host; this->m_mount_point = mount_point; QDir tmpdir(mount_point); if(!tmpdir.exists()) { if(!tmpdir.mkpath(tmpdir.path())) WARN() << "Cannot create directory" << tmpdir.path(); } QProcess cmd; QStringList params; params << "/usr/bin/env"; params << "mount"; params << "-t"; params << "cifs"; params << "-o"; //params << QString("username=%1,password=%2").arg("guest").arg(""); if(options.length() > 0) params << options; else params << "guest"; params << host; params << mount_point; cmd.start("sudo", params); if (!cmd.waitForStarted()) { ERROR() << "Cannot mount point" << s_host << "to" << mount_point; is_mounted = false; } if(!cmd.waitForFinished()) { ERROR() << "Not finished"; } //DEBUG() << params; DEBUG() << cmd.readAllStandardError() << cmd.readAllStandardOutput(); cmd.close(); cmd.kill(); #else ONLY_SUPPORTED_ON_UNIX; #endif //Q_OS_UNIX return is_mounted; }
foreach (const TestConfiguration *testConfiguration, selectedTests) { QScopedPointer<TestOutputReader> outputReader; switch (testConfiguration->testType()) { case TestTypeQt: outputReader.reset(new QtTestOutputReader(futureInterface, &testProcess, testConfiguration->buildDirectory())); break; case TestTypeGTest: outputReader.reset(new GTestOutputReader(futureInterface, &testProcess, testConfiguration->buildDirectory())); break; } if (futureInterface.isCanceled()) break; if (!testConfiguration->project()) continue; QProcessEnvironment environment = testConfiguration->environment().toProcessEnvironment(); QString commandFilePath = executableFilePath(testConfiguration->targetFile(), environment); if (commandFilePath.isEmpty()) { futureInterface.reportResult(new FaultyTestResult(Result::MessageFatal, QObject::tr("Could not find command \"%1\". (%2)") .arg(testConfiguration->targetFile()) .arg(testConfiguration->displayName()))); continue; } if (testConfiguration->testType() == TestTypeQt) { QStringList argumentList(QLatin1String("-xml")); if (!metricsOption.isEmpty()) argumentList << metricsOption; if (testConfiguration->testCases().count()) argumentList << testConfiguration->testCases(); testProcess.setArguments(argumentList); } else { // TestTypeGTest const QStringList &testSets = testConfiguration->testCases(); if (testSets.size()) { QStringList argumentList; argumentList << QLatin1String("--gtest_filter=") + testSets.join(QLatin1Char(':')); testProcess.setArguments(argumentList); } } testProcess.setWorkingDirectory(testConfiguration->workingDirectory()); if (Utils::HostOsInfo::isWindowsHost()) environment.insert(QLatin1String("QT_LOGGING_TO_CONSOLE"), QLatin1String("1")); testProcess.setProcessEnvironment(environment); testProcess.setProgram(commandFilePath); testProcess.start(); bool ok = testProcess.waitForStarted(); QTime executionTimer; executionTimer.start(); bool canceledByTimeout = false; if (ok) { while (testProcess.state() == QProcess::Running) { if (executionTimer.elapsed() >= timeout) { canceledByTimeout = true; break; } if (futureInterface.isCanceled()) { testProcess.kill(); testProcess.waitForFinished(); return; } eventLoop.processEvents(); } } if (canceledByTimeout) { if (testProcess.state() != QProcess::NotRunning) { testProcess.kill(); testProcess.waitForFinished(); } futureInterface.reportResult(new FaultyTestResult(Result::MessageFatal, QObject::tr( "Test case canceled due to timeout. \nMaybe raise the timeout?"))); } }
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 ); }
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"); #if QT_VERSION >= 0x040800 case QSysInfo::WV_WINDOWS8: return QString::fromLatin1("Windows 8"); #endif #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"); #if QT_VERSION >= 0x040700 case QSysInfo::MV_10_6: return QString::fromLatin1("Mac OS X 10.6"); #endif #if QT_VERSION >= 0x040800 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"); #endif 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 }
bool OBConvert::executeOBabel(const QStringList& args, const QByteArray& input, QByteArray& output) { QString program; // If the OBABEL_EXECUTABLE environment variable is set, then // use that to find obabel QByteArray obabelExec = qgetenv("OBABEL_EXECUTABLE"); if (!obabelExec.isEmpty()) { program = obabelExec; } else { // Otherwise, search in the current directory, and then ../bin #ifdef _WIN32 QString executable = "obabel.exe"; #else QString executable = "obabel"; #endif QString path = QCoreApplication::applicationDirPath(); if (QFile::exists(path + "/" + executable)) program = path + "/" + executable; else if (QFile::exists(path + "/../bin/" + executable)) program = path + "/../bin/" + executable; else { qDebug() << "Error: could not find obabel executable!"; return false; } } QProcess p; p.start(program, args); if (!p.waitForStarted()) { qDebug() << "Error: The obabel executable at" << program << "failed to start."; return false; } // Give it the input! p.write(input.data()); // Close the write channel p.closeWriteChannel(); if (!p.waitForFinished()) { qDebug() << "Error: " << program << "failed to finish."; output = p.readAll(); qDebug() << "Output is as follows:\n" << output; return false; } int exitStatus = p.exitStatus(); output = p.readAll(); if (exitStatus == QProcess::CrashExit) { qDebug() << "Error: obabel crashed!\n"; qDebug() << "Output is as follows:\n" << output; return false; } if (exitStatus != QProcess::NormalExit) { qDebug() << "Error: obabel finished abnormally with exit code " << exitStatus; qDebug() << "Output is as follows:\n" << output; return false; } // We did it! return true; }
void InitAacEncTask::initAacEncImpl(const char *const toolName, const char *const fileNames[], const quint32 &toolMinVersion, const quint32 &verDigits, const quint32 &verShift, const char *const verStr, QRegExp ®ExpVer, QRegExp ®ExpSig) { static const size_t MAX_FILES = 8; const QString appPath = QDir(QCoreApplication::applicationDirPath()).canonicalPath(); QFileInfoList fileInfo; for(size_t i = 0; fileNames[i] && (fileInfo.count() < MAX_FILES); i++) { fileInfo.append(QFileInfo(QString("%1/%2").arg(appPath, QString::fromLatin1(fileNames[i])))); } for(QFileInfoList::ConstIterator iter = fileInfo.constBegin(); iter != fileInfo.constEnd(); iter++) { if(!(iter->exists() && iter->isFile())) { qDebug("%s encoder binaries not found -> Encoding support will be disabled!\n", toolName); return; } if((iter->suffix().compare("exe", Qt::CaseInsensitive) == 0) && (!MUtils::OS::is_executable_file(iter->canonicalFilePath()))) { qDebug("%s executable is invalid -> %s support will be disabled!\n", MUTILS_UTF8(iter->fileName()), toolName); return; } } qDebug("Found %s encoder binary:\n%s\n", toolName, MUTILS_UTF8(fileInfo.first().canonicalFilePath())); //Lock the encoder binaries QScopedPointer<LockedFile> binaries[MAX_FILES]; try { size_t index = 0; for(QFileInfoList::ConstIterator iter = fileInfo.constBegin(); iter != fileInfo.constEnd(); iter++) { binaries[index++].reset(new LockedFile(iter->canonicalFilePath())); } } catch(...) { qWarning("Failed to get excluive lock to encoder binary -> %s support will be disabled!", toolName); return; } QProcess process; MUtils::init_process(process, fileInfo.first().absolutePath()); process.start(fileInfo.first().canonicalFilePath(), QStringList() << "-help"); if(!process.waitForStarted()) { qWarning("%s process failed to create!", toolName); qWarning("Error message: \"%s\"\n", process.errorString().toLatin1().constData()); process.kill(); process.waitForFinished(-1); return; } quint32 toolVersion = 0; bool sigFound = regExpSig.isEmpty() ? true : false; while(process.state() != QProcess::NotRunning) { if(!process.waitForReadyRead()) { if(process.state() == QProcess::Running) { qWarning("%s process time out -> killing!", toolName); process.kill(); process.waitForFinished(-1); return; } } while(process.canReadLine()) { QString line = QString::fromUtf8(process.readLine().constData()).simplified(); if((!sigFound) && regExpSig.lastIndexIn(line) >= 0) { sigFound = true; continue; } if(sigFound && (regExpVer.lastIndexIn(line) >= 0)) { quint32 tmp[8]; if(MUtils::regexp_parse_uint32(regExpVer, tmp, qMin(verDigits, 8U))) { toolVersion = 0; for(quint32 i = 0; i < verDigits; i++) { toolVersion = (toolVersion * verShift) + qBound(0U, tmp[i], (verShift - 1)); } } } } } if(toolVersion <= 0) { qWarning("%s version could not be determined -> Encoding support will be disabled!", toolName); return; } else if(toolVersion < toolMinVersion) { qWarning("%s version is too much outdated (%s) -> Encoding support will be disabled!", toolName, MUTILS_UTF8(lamexp_version2string(verStr, toolVersion, "N/A"))); qWarning("Minimum required %s version currently is: %s\n", toolName, MUTILS_UTF8(lamexp_version2string(verStr, toolMinVersion, "N/A"))); return; } qDebug("Enabled %s encoder %s.\n", toolName, MUTILS_UTF8(lamexp_version2string(verStr, toolVersion, "N/A"))); size_t index = 0; for(QFileInfoList::ConstIterator iter = fileInfo.constBegin(); iter != fileInfo.constEnd(); iter++) { lamexp_tools_register(iter->fileName(), binaries[index++].take(), toolVersion); } }
void ProcessLauncher::launchProcess() { QString commandLine; if (m_launchOptions.processType == WebProcess) { commandLine = QLatin1String("%1 \"%2\" %3"); QByteArray webProcessPrefix = qgetenv("QT_WEBKIT2_WP_CMD_PREFIX"); commandLine = commandLine.arg(QLatin1String(webProcessPrefix.constData())).arg(QString(executablePathOfWebProcess())); #if ENABLE(PLUGIN_PROCESS) } else if (m_launchOptions.processType == PluginProcess) { commandLine = QLatin1String("%1 \"%2\" %3 %4"); QByteArray pluginProcessPrefix = qgetenv("QT_WEBKIT2_PP_CMD_PREFIX"); commandLine = commandLine.arg(QLatin1String(pluginProcessPrefix.constData())).arg(QString(executablePathOfPluginProcess())); #endif } else ASSERT_NOT_REACHED(); #if OS(DARWIN) // Create the listening port. mach_port_t connector; mach_port_allocate(mach_task_self(), MACH_PORT_RIGHT_RECEIVE, &connector); // Insert a send right so we can send to it. mach_port_insert_right(mach_task_self(), connector, connector, MACH_MSG_TYPE_MAKE_SEND); // Register port with a service name to the system. QString serviceName = QStringLiteral("com.nokia.Qt.WebKit.QtWebProcess-%1-%2"); serviceName = serviceName.arg(QString().setNum(getpid()), QString().setNum((size_t)this)); kern_return_t kr = bootstrap_register2(bootstrap_port, const_cast<char*>(serviceName.toUtf8().data()), connector, 0); ASSERT_UNUSED(kr, kr == KERN_SUCCESS); commandLine = commandLine.arg(serviceName); #elif OS(WINDOWS) CoreIPC::Connection::Identifier connector, clientIdentifier; if (!CoreIPC::Connection::createServerAndClientIdentifiers(connector, clientIdentifier)) { // FIXME: What should we do here? ASSERT_NOT_REACHED(); } commandLine = commandLine.arg(qulonglong(clientIdentifier)); // Ensure that the child process inherits the client identifier. ::SetHandleInformation(clientIdentifier, HANDLE_FLAG_INHERIT, HANDLE_FLAG_INHERIT); #else int sockets[2]; if (socketpair(AF_UNIX, SOCKET_TYPE, 0, sockets) == -1) { qDebug() << "Creation of socket failed with errno:" << errno; ASSERT_NOT_REACHED(); return; } // Don't expose the ui socket to the web process while (fcntl(sockets[1], F_SETFD, FD_CLOEXEC) == -1) { if (errno != EINTR) { ASSERT_NOT_REACHED(); while (close(sockets[0]) == -1 && errno == EINTR) { } while (close(sockets[1]) == -1 && errno == EINTR) { } return; } } int connector = sockets[1]; commandLine = commandLine.arg(sockets[0]); #endif #if ENABLE(PLUGIN_PROCESS) if (m_launchOptions.processType == PluginProcess) commandLine = commandLine.arg(QString(m_launchOptions.extraInitializationData.get("plugin-path"))); #endif QProcess* webProcessOrSUIDHelper = new QtWebProcess(); webProcessOrSUIDHelper->setProcessChannelMode(QProcess::ForwardedChannels); #if ENABLE(SUID_SANDBOX_LINUX) if (m_launchOptions.processType == WebProcess) { QString sandboxCommandLine = QLatin1String("\"%1\" \"%2\" %3"); sandboxCommandLine = sandboxCommandLine.arg(QCoreApplication::applicationDirPath() + QLatin1String("/SUIDSandboxHelper")); sandboxCommandLine = sandboxCommandLine.arg(executablePathOfWebProcess()); sandboxCommandLine = sandboxCommandLine.arg(sockets[0]); webProcessOrSUIDHelper->start(sandboxCommandLine); } else webProcessOrSUIDHelper->start(commandLine); #else webProcessOrSUIDHelper->start(commandLine); #endif #if OS(UNIX) && !OS(DARWIN) // Don't expose the web socket to possible future web processes while (fcntl(sockets[0], F_SETFD, FD_CLOEXEC) == -1) { if (errno != EINTR) { ASSERT_NOT_REACHED(); delete webProcessOrSUIDHelper; return; } } #endif if (!webProcessOrSUIDHelper->waitForStarted()) { qDebug() << "Failed to start" << commandLine; ASSERT_NOT_REACHED(); #if OS(DARWIN) mach_port_deallocate(mach_task_self(), connector); mach_port_mod_refs(mach_task_self(), connector, MACH_PORT_RIGHT_RECEIVE, -1); #endif delete webProcessOrSUIDHelper; return; } #if OS(UNIX) setpriority(PRIO_PROCESS, webProcessOrSUIDHelper->pid(), 10); #endif RunLoop::main()->dispatch(bind(&WebKit::ProcessLauncher::didFinishLaunchingProcess, this, webProcessOrSUIDHelper, connector)); }
int main(int argc, char *argv[]) { QCoreApplication a(argc, argv); // Un message de courriel est arrivé à l'adresse prefixe+id_lot_et_cle_du_lot_destinataire@domaine. // exemple : [email protected] // sur le serveur MX du domaine, dans /etc/alias, l'administrateur aura placé cette ligne : // prefixe: |/usr/bin/relai_de_courriel // Les rêglages sont à faire dans un fichier de configuration sous /etc ou ~/.config QSettings settings("Les Développements Durables", "Laguntzaile"); // Vérifications préalables QString programme = settings.value("sendmail", "/usr/sbin/sendmail").toString(); if (!QFile::exists(programme)) { qCritical() << "Introuvable programme d'envoi du courrier " << programme; cout << "4.3.5 System incorrectly configured" << endl; return EX_CONFIG; } vector<const char*> env_requis; env_requis.push_back("EXTENSION"); env_requis.push_back("SENDER"); env_requis.push_back("USER"); env_requis.push_back("DOMAIN"); for (vector<const char*>::const_iterator i = env_requis.begin(); i != env_requis.end(); i++) { if (getenv(*i) == NULL) { qCritical() << "Erreur de lecture de la variable d'environnement" << *i << "- normalement le MTA renseigne cette variable."; cout << "4.3.5 System incorrectly configured" << endl; return EX_USAGE; } } // De EXTENSION, tirer l'id du lot de sa clé QString extension(getenv("EXTENSION")); bool aller = extension.contains(QRegExp("^\\d+_\\d+$")); bool retour = extension.contains(QRegExp("^\\d+_\\d+_\\d+$")); if (!aller && !retour) { qCritical() << "Cette adresse est invalide."; cout << "5.1.3 Bad destination mailbox address syntax" << endl; return EX_NOUSER; } // Le lot des destinataires est défini dans la base de données QSqlDatabase db = QSqlDatabase::addDatabase("QPSQL"); // Connexion à la base de données // FIXME : permettre un accès sans mot de passe db.setHostName (settings.value("database/hostName", "localhost" ).toString()); db.setPort (settings.value("database/port", 5432 ).toInt() ); db.setDatabaseName (settings.value("database/databaseName", "laguntzaile" ).toString()); db.setUserName (settings.value("database/userName", qgetenv("USER") ).toString()); db.setPassword (settings.value("database/password", qgetenv("USER") ).toString()); if(!db.open()) { qCritical() << "Erreur d'ouverture de la connexion à la base de données :" << db.lastError() << "Veuillez vérifier le fichier de configuration" << settings.fileName(); cout << "4.3.5 System incorrectly configured" << endl; return EX_CONFIG; } // Un retour en erreur ; débarrassons nous de ce cas spécial en premier if (retour) { // lire id_lot, id_personne et cle QStringList identifiant = extension.split('_'); int id_lot = identifiant.at(0).toInt(); int id_personne = identifiant.at(1).toInt(); int cle = identifiant.at(2).toInt(); // vérification standard : lot_personne avec la bonne cle, traité et reussi et sans erreur QSqlQuery query_lot_personne; if(!query_lot_personne.prepare( "select *" " from lot_personne" " where" " id_lot = :id_lot" " and id_personne = :id_personne" " and cle = :cle" " and traite" " and reussi" " and erreur is null")) { qCritical() << "Erreur de préparation de la requête d'identification de l'envoi :" << query_lot_personne.lastError(); cout << "4.3.5 System incorrectly configured" << endl; return EX_CONFIG; } query_lot_personne.bindValue(":id_lot", id_lot); query_lot_personne.bindValue(":id_personne", id_personne); query_lot_personne.bindValue(":cle", cle); if(!query_lot_personne.exec()) { qCritical() << "Erreur d'execution de la requête d'identification de l'envoi :" << query_lot_personne.lastError(); cout << "4.3.5 System incorrectly configured" << endl; return EX_CONFIG; } if (query_lot_personne.size() != 1) { qCritical() << "Cette adresse retour est invalide." << "query_lot_personne.size() = " << query_lot_personne.size() << "id_lot" << id_lot << "id_personne" << id_personne << "cle" << cle << query_lot_personne.executedQuery() << query_lot_personne.boundValues() << ".first()" << query_lot_personne.first(); cout << "5.1.1 Bad destination mailbox address" << endl; return EX_NOUSER; } // marquer cet envoi comme pas réussi et renseigner l'erreur QSqlQuery setLotPersonneEnErreur; if (!setLotPersonneEnErreur.prepare( "update lot_personne" " set reussi = false," " erreur = :erreur" " where id_lot = :id_lot" " and id_personne = :id_personne")) { qCritical() << "Erreur de préparation de la requête d'enregistrement de l'erreur d'envoi :" << setLotPersonneEnErreur.lastError(); cout << "4.3.5 System incorrectly configured" << endl; return EX_CONFIG; } QFile in; in.open(stdin, QIODevice::ReadOnly); setLotPersonneEnErreur.bindValue(":id_lot", id_lot); setLotPersonneEnErreur.bindValue(":id_personne", id_personne); setLotPersonneEnErreur.bindValue(":erreur", QString(in.readAll())); if(!setLotPersonneEnErreur.exec()) { qCritical() << "Erreur d'execution de la requête d''identification de l'enregistrement de l'erreur d'envoi :" << setLotPersonneEnErreur.lastError(); cout << "4.3.5 System incorrectly configured" << endl; return EX_CONFIG; } cout << "2.1.5 Destination address valid" << endl; return EX_OK; } // Pas un retour mais un envoi vers un lot de destinataires QStringList identifiant = extension.split('_'); int id_lot = identifiant.at(0).toInt(); int cle = identifiant.at(1).toInt(); // Lecture du lot QSqlQuery query_lot; if (!query_lot.prepare("select * from lot where id=? and cle=?")) { qCritical() << "Erreur de préparation de la requête de lecture du lot de destinataires :" << query_lot.lastError(); cout << "4.3.5 System incorrectly configured" << endl; return EX_CONFIG; } query_lot.addBindValue(id_lot); query_lot.addBindValue(cle); if (!query_lot.exec()) { qCritical() << "Erreur d'execution de la requête de lecture du lot de destinataires :" << query_lot.lastError(); cout << "4.3.5 System incorrectly configured" << endl; return EX_CONFIG; } if (!query_lot.first()) { qCritical() << "Cette adresse ne correspond pas à un lot de destinataires"; cout << "5.1.1 Bad destination mailbox address" << endl; return EX_NOUSER; } if (query_lot.value("traite").toBool()) { qCritical() << "Ce lot a déjà été traité une fois. Il n'est pas possible de réutiliser un même lot."; cout << "4.2.1 Mailbox disabled, not accepting messages" << endl; return EX_UNAVAILABLE; } #ifndef SKIP_DATE_TESTS if (query_lot.value("date_de_creation").toDateTime().secsTo(QDateTime::currentDateTime()) > 24*60*60) { qCritical() << "Ce lot est périmé. Un lot ne reste valide que pendant 24 heures." << "Date de création de ce lot : " << query_lot.value("date_de_creation"); cout << "4.2.1 Mailbox disabled, not accepting messages" << endl; return EX_UNAVAILABLE; } #endif // Lecture de l'évènement int id_evenement = query_lot.value("id_evenement").toInt(); QSqlQuery query_evenement; if (!query_evenement.prepare("select fin from evenement where id=?")) { qCritical() << "Erreur de préparation de la requête de lecture de l'évenement :" << query_evenement.lastError(); cout << "4.3.5 System incorrectly configured" << endl; return EX_CONFIG; } query_evenement.addBindValue(id_evenement); if (!query_evenement.exec()) { qCritical() << "Erreur d'execution de la requête de lecture de l'évènement :" << query_evenement.lastError(); cout << "4.3.5 System incorrectly configured" << endl; return EX_CONFIG; } if (!query_evenement.first()) { qCritical() << "Ce lot ne correspond à aucun évènement (base de donnée incohérente)"; cout << "5.1.1 Bad destination mailbox address" << endl; return EX_NOUSER; } #ifndef SKIP_DATE_TESTS if (query_evenement.value("fin").toDateTime() < QDateTime::currentDateTime()) { qCritical() << "Cet évènement est déjà terminé."; cout << "4.2.1 Mailbox disabled, not accepting messages" << endl; return EX_UNAVAILABLE; } #endif // Le message lui-même est à lire sur l'entrée standard istreambuf_iterator<char> bit(cin), eit; MimeEntity modele(bit, eit); // Adaptons le format du message et vérifions si on y trouve bien _URL_ bool marqueurTrouve = preparer(&modele); if (!marqueurTrouve) { qCritical() << "Marqueur _URL_ introuvable dans le corps du message."; cout << "4.2.4 Mailing list expansion problem" << endl; return EX_DATAERR; } // Virer les headers Return-Path, X-Original-To, Delivered-To, X-*, Received ... for (Header::iterator i = modele.header().begin(); i != modele.header().end(); i++) { if (i->name() == "Received" || i->name().substr(0,2) == "X-" || i->name() == "Return-Path" || i->name() == "Delivered-To" || i->name() == "Message-Id" ) { modele.header().erase(i); } } // Récupération de la liste des destinataires QSqlQuery query_destinataires; if (!query_destinataires.prepare( "select distinct concat_ws(' ', prenom, nom) as libelle, email, id_personne, disponibilite.id as id_disponibilite, lot_personne.cle" " from lot_personne join personne on id_personne = personne.id" " join lot on id_lot = lot.id" " left join disponibilite using(id_personne, id_evenement)" " where id_lot=?" " and email like '%@%'" )) { qCritical() << "Erreur de préparation de la requête de lecture des destinataires du lot :" << query_destinataires.lastError(); cout << "4.3.5 System incorrectly configured" << endl; return EX_CONFIG; } query_destinataires.addBindValue(id_lot); if (!query_destinataires.exec()) { qCritical() << "Erreur d'execution de la requête de lecture des destinataires du lot :" << query_destinataires.lastError(); cout << "4.3.5 System incorrectly configured" << endl; return EX_CONFIG; } // Préparation des autres requètes dont on va avoir besoin QSqlQuery query_affectations; if (!query_affectations.prepare( "select affectation.id, affectation.statut, affectation.commentaire, tour.debut, tour.fin, poste.nom, poste.description" " from affectation" " join tour on id_tour = tour.id" " join poste on id_poste = poste.id" " where id_disponibilite = ?" )) { qCritical() << "Erreur de préparation de la requête de lecture des affectations du destinataire :" << query_affectations.lastError(); cout << "4.3.5 System incorrectly configured" << endl; return EX_CONFIG; } QSqlQuery setLotPersonneTraite; if (!setLotPersonneTraite.prepare( "update lot_personne" " set" " traite = true," " reussi = :reussi," " erreur = :erreur" " where id_lot=:id_lot and id_personne=:id_personne" )) { qCritical() << "Erreur de préparation de la requête de marquage des envois traités :" << setLotPersonneTraite.lastError(); cout << "4.3.5 System incorrectly configured" << endl; return EX_CONFIG; } QSqlQuery setLotTraite; if (!setLotTraite.prepare( "update lot" " set" " traite = true," " modele = :modele," " expediteur = :expediteur" " where id=:id_lot" )) { qCritical() << "Erreur de préparation de la requête de marquage du lot traité :" << setLotTraite.lastError(); cout << "4.3.5 System incorrectly configured" << endl; return EX_CONFIG; } // Génération et envoi des messages personnalisés while (query_destinataires.next()) { QString libelle = query_destinataires.value("libelle").toString().trimmed(); QString email = query_destinataires.value("email").toString().trimmed(); int id_personne = query_destinataires.value("id_personne").toInt(); int cle = query_destinataires.value("cle").toInt(); stringstream b; b << modele; string s = b.str(); MimeEntity instance(s.begin(), s.end()); // Personnalisation du from, pour pouvoir identifier les personnes injoignables QString fromMailbox = QString("%1+%2_%3_%4").arg(getenv("USER")).arg(id_lot).arg(id_personne).arg(cle); QString fromDomaine = getenv("DOMAIN"); MailboxList& from = instance.header().from(); for (MailboxList::iterator i = from.begin(); i != from.end(); i++) { i->mailbox(fromMailbox.toStdString()); i->domain(fromDomaine.toStdString()); } // Génération du to Mailbox mailbox; mailbox.label(libelle.toStdString()); mailbox.mailbox(email.split('@').at(0).toStdString()); mailbox.domain(email.split('@').at(1).toStdString()); MailboxList to; to.push_back(mailbox); instance.header().to(to.str()); // substitution des marqueurs string url = settings.value("modele_url", "http://localhost/%1/%2").toString().arg(id_evenement).arg(id_personne).toStdString(); string affectations = ""; string affectations_html = ""; if (!query_destinataires.value("id_disponibilite").isNull()) { // le destinataire est inscrit à l'évènement et a peut-être des affectations int id_disponibilite = query_destinataires.value("id_disponibilite").toInt(); query_affectations.addBindValue(id_disponibilite); if (!query_affectations.exec()) { qCritical() << "Erreur d'execution de la requête de lecture des affectations du destinataire :" << query_affectations.lastError(); cout << "4.3.5 System incorrectly configured" << endl; return EX_CONFIG; } if (query_affectations.size() > 0) { // il a des affectations affectations_html = settings.value("modele_affectations_html_prefixe", "<table><tr><th>De</th><th>à </th><th>Poste</th></tr>").toString().toStdString(); while (query_affectations.next()) { QString debut = query_affectations.value("debut").toDateTime().toString(); // TODO : formater les dates et les heures QString fin = query_affectations.value("fin").toDateTime().toString(); QString nom = query_affectations.value("nom").toString(); affectations += settings.value("modele_affectations_texte", "%1 → %2 : %3\n").toString().arg(debut, fin, nom).toStdString(); affectations_html += settings.value("modele_affectations_html", "<tr><td>%1</td><td>%2</td><td>%3</td></tr>").toString().arg(debut, fin, nom).toStdString(); // TODO : htmlentities() } affectations_html += settings.value("modele_affectations_html_suffixe", "</table>").toString().toStdString(); } } substituer(&instance, url, affectations, affectations_html); // envoi du message et marquage des destinataires traités QProcess sendmail; QStringList arguments; arguments << "-f" << QString("%1@%2").arg(fromMailbox).arg(fromDomaine); arguments << email; stringstream ss; ss << instance; QString entree = QString::fromStdString(ss.str()); entree.replace(QString("\n.\n"), QString("\n..\n")); sendmail.start(programme, arguments); if (sendmail.waitForStarted()) { sendmail.write(entree.toUtf8()); sendmail.closeWriteChannel(); if (sendmail.waitForFinished() && sendmail.exitStatus() == QProcess::NormalExit && sendmail.exitCode() == EX_OK) { setLotPersonneTraite.bindValue(":reussi", true); setLotPersonneTraite.bindValue("erreur", QVariant()); } else { setLotPersonneTraite.bindValue(":reussi", false); setLotPersonneTraite.bindValue("erreur", strerror(sendmail.exitCode())); } } else { setLotPersonneTraite.bindValue(":reussi", false); setLotPersonneTraite.bindValue(":erreur", sendmail.readAllStandardError()); } setLotPersonneTraite.bindValue(":id_lot", id_lot); setLotPersonneTraite.bindValue(":id_personne", id_personne); if(!setLotPersonneTraite.exec()) { qCritical() << "Erreur d'execution de la requête de marquage des envois traités :" << setLotPersonneTraite.lastError(); cout << "4.3.5 System incorrectly configured" << endl; return EX_CONFIG; } } // Marquage du lot traité QString sender(getenv("SENDER")); setLotTraite.bindValue(":id_lot", id_lot); stringstream b; b << modele; string modele_lot = b.str(); setLotTraite.bindValue(":modele", modele_lot.c_str()); setLotTraite.bindValue(":expediteur", sender); if(!setLotTraite.exec()) { qCritical() << "Erreur d'execution de la requête de marquage des envois traités :" << setLotTraite.lastError(); cout << "2.1.5 Destination address valid mais le lot n'a pas été marqué 'traité'" << endl; return EX_OK; } // TODO : poster à SENDER la liste des adresses, nom, prenom, ville et identifiant des destinataires en erreur, le nombre d'envois faits (réussis et ratés), un rappel des sujet et date du message original cout << "2.1.5 Destination address valid" << endl; return EX_OK; }
int ctkDICOMApplicationTest1(int argc, char * argv []) { QApplication app(argc, argv); QTextStream out(stdout); if ( argc < 10 ) { out << "ERROR: invalid arguments. Should be:\n"; out << " ctkDICOMApplicationTest1 <dcmqrscp> <configfile> <dicomData1> <dcmData2> <storescu> <ctkDICOMQuery> <ctkDICOMRetrieve> <retrieveDirectory>\n"; return EXIT_FAILURE; } QString dcmqrscp_exe (argv[1]); QString dcmqrscp_cfg (argv[2]); QString dicomData1 (argv[3]); QString dicomData2 (argv[4]); QString storescu_exe (argv[5]); QString ctkDICOMQuery_exe (argv[6]); QString ctkDICOMQuery_db_file (argv[7]); QString ctkDICOMRetrieve_exe (argv[8]); QString ctkDICOMRetrieve_directory (argv[9]); // // first, start the server process // QProcess *dcmqrscp = new QProcess(0); QStringList dcmqrscp_args; dcmqrscp_args << "--config" << dcmqrscp_cfg; dcmqrscp_args << "--debug" << "--verbose"; dcmqrscp_args << "11112"; try { out << "starting server" << dcmqrscp_exe << "\n"; out << "with args " << dcmqrscp_args.join(" ") << "\n"; dcmqrscp->start(dcmqrscp_exe, dcmqrscp_args); dcmqrscp->waitForStarted(); } catch (std::exception e) { out << "ERROR: could not start server" << e.what(); return EXIT_FAILURE; } // // now push some dicom data in using storescp // QProcess *storescu = new QProcess(0); QStringList storescu_args; storescu_args << "-aec" << "CTK_AE"; storescu_args << "-aet" << "CTK_AE"; storescu_args << "localhost" << "11112"; storescu_args << dicomData1; storescu_args << dicomData2; try { out << "running client" << storescu_exe << "\n"; out << "with args" << storescu_args.join(" ") << "\n"; storescu->start(storescu_exe, storescu_args); storescu->waitForFinished(); out << "storescu Finished.\n"; out << "Standard Output:\n"; out << storescu->readAllStandardOutput(); out << "Standard Error:\n"; out << storescu->readAllStandardError(); } catch (std::exception e) { out << "ERROR: could not start client" << e.what(); return EXIT_FAILURE; } // // now query the server to see if the data arrived okay // - our database file will be updated with metadata from the query // QProcess *ctkDICOMQuery = new QProcess(0); QStringList ctkDICOMQuery_args; ctkDICOMQuery_args << ctkDICOMQuery_db_file; ctkDICOMQuery_args << "CTK_AE" << "CTK_AE"; ctkDICOMQuery_args << "localhost" << "11112"; try { out << "running client" << ctkDICOMQuery_exe << "\n"; out << "with args" << ctkDICOMQuery_args.join(" ") << "\n"; ctkDICOMQuery->start(ctkDICOMQuery_exe, ctkDICOMQuery_args); ctkDICOMQuery->waitForFinished(); out << "ctkDICOMQuery Finished.\n"; out << "Standard Output:\n"; out << ctkDICOMQuery->readAllStandardOutput(); out << "Standard Error:\n"; out << ctkDICOMQuery->readAllStandardError(); } catch (std::exception e) { out << "ERROR: could not start client" << e.what(); return EXIT_FAILURE; } // // now do a retrieve into our download directory // // this is the study id of the dicom files we load from CTKData QString studyUID("1.2.840.113619.2.135.3596.6358736.5118.1115807980.182"); QProcess *ctkDICOMRetrieve = new QProcess(0); QStringList ctkDICOMRetrieve_args; ctkDICOMRetrieve_args << studyUID; ctkDICOMRetrieve_args << ctkDICOMRetrieve_directory; ctkDICOMRetrieve_args << "CTK_AE" << "11113"; ctkDICOMRetrieve_args << "CTK_AE"; ctkDICOMRetrieve_args << "localhost" << "11112" << "CTK_CLIENT_AE"; try { out << "running client" << ctkDICOMRetrieve_exe << "\n"; out << "with args" << ctkDICOMRetrieve_args.join(" ") << "\n"; ctkDICOMRetrieve->start(ctkDICOMRetrieve_exe, ctkDICOMRetrieve_args); ctkDICOMRetrieve->waitForFinished(); out << "ctkDICOMRetrieve Finished.\n"; out << "Standard Output:\n"; out << ctkDICOMRetrieve->readAllStandardOutput(); out << "Standard Error:\n"; out << ctkDICOMRetrieve->readAllStandardError(); } catch (std::exception e) { out << "ERROR: could not start client" << e.what(); return EXIT_FAILURE; } // // clients are finished, not kill server and print output // try { dcmqrscp->kill(); dcmqrscp->waitForFinished(); out << "dcmqrscp Finished.\n"; out << "Standard Output:\n"; out << dcmqrscp->readAllStandardOutput(); out << "Standard Error:\n"; out << dcmqrscp->readAllStandardError(); } catch (std::exception e) { out << "ERROR: could not start client" << e.what(); return EXIT_FAILURE; } return EXIT_SUCCESS; }
/** Runs the specified command (should be ffmpeg), and lets * writeFrame pipe data into it 1 frame at a time. * * @param[in] strCmd A string containing the command to execute and * all of its arguments * @param[out] progress A function that takes one float argument * (the percentage of the ffmpeg operation complete) and * may display the output to the user in any way it * sees fit. * @param[in] writeFrame A function that takes two arguments, a * process (the ffmpeg process) and an integer * (frames processed or -1, see full description). * This function should write a single frame to the * process. The function returns true value if it * actually wrote a frame. * * This function operates generally as follows: * 1. Spawn process with the command from strCmd * 2. Check ffmpeg's output for a progress update. * 3. Add frames with writeFrame until it returns false. * 4. Repeat from step 2 until all frames have been written. * * The idea is that there are two forms of processing occuring * simultaneously, generating frames to send to ffmpeg, and ffmpeg * encoding those frames. Whether these this actually occur * concurrently or one after another appears to depend on the environment. * * The writeFrame function deserves a bit of extra details. It does * not only return false when there is an error in generating or * writing a frame, it also does it when it wants to "return control" * to the rest of the executeFFMpegPipe function for the purposes of * reading updates from ffmpeg's output. This should be done every * once in a while if possible, but with some formats (specifically gif), * all frames must be loaded before any processing can continue, so * there is no point returning false for it until all frames have * been written. writeFrame is also responsible for closing the writeChannel * of the process when it has finished writing all frames. This indicates * to executeFFMpegPipe that it no longer needs to call writeFrame. * * @return Returns Status::OK if everything went well, and Status::FAIL * and error is detected (usually a non-zero exit code for ffmpeg). */ Status MovieExporter::executeFFMpegPipe(QString strCmd, std::function<void(float)> progress, std::function<bool(QProcess&, int)> writeFrame) { qDebug() << strCmd; QProcess ffmpeg; ffmpeg.setReadChannel(QProcess::StandardOutput); // FFmpeg writes to stderr only for some reason, so we just read both channels together ffmpeg.setProcessChannelMode(QProcess::MergedChannels); ffmpeg.start(strCmd); if (ffmpeg.waitForStarted()) { int framesGenerated = 0; int lastFrameProcessed = 0; const int frameStart = mDesc.startFrame; const int frameEnd = mDesc.endFrame; while(ffmpeg.state() == QProcess::Running) { if (mCanceled) { ffmpeg.terminate(); return Status::CANCELED; } // Check FFmpeg progress int framesProcessed = -1; if(ffmpeg.waitForReadyRead(10)) { QString output(ffmpeg.readAll()); QStringList sList = output.split(QRegExp("[\r\n]"), QString::SkipEmptyParts); for (const QString& s : sList) { qDebug() << "[ffmpeg]" << s; } if(output.startsWith("frame=")) { lastFrameProcessed = framesProcessed = output.mid(6, output.indexOf(' ')).toInt(); } } if(!ffmpeg.isWritable()) { continue; } while(writeFrame(ffmpeg, framesProcessed)) { framesGenerated++; const float percentGenerated = framesGenerated / static_cast<float>(frameEnd - frameStart); const float percentConverted = lastFrameProcessed / static_cast<float>(frameEnd - frameStart); progress((percentGenerated + percentConverted) / 2); } const float percentGenerated = framesGenerated / static_cast<float>(frameEnd - frameStart); const float percentConverted = lastFrameProcessed / static_cast<float>(frameEnd - frameStart); progress((percentGenerated + percentConverted) / 2); } QString output(ffmpeg.readAll()); QStringList sList = output.split(QRegExp("[\r\n]"), QString::SkipEmptyParts); for (const QString& s : sList) { qDebug() << "[ffmpeg]" << s; } if(ffmpeg.exitStatus() != QProcess::NormalExit) { qDebug() << "ERROR: FFmpeg crashed"; return Status::FAIL; } } else { qDebug() << "ERROR: Could not start FFmpeg."; return Status::FAIL; } return Status::OK; }
/* Take the ENML note and transform it into HTML that WebKit will not complain about */ QByteArray NoteFormatter::rebuildNoteHTML() { QLOG_DEBUG() << "Rebuilding Note: " << QString::fromStdString(note.guid) << " : " << QString::fromStdString(note.title); formatError = false; readOnly = false; // First try to read the document. If it fails we need to clean it up content.append(QString::fromStdString(note.content)); QDomDocument doc; QString emsg; bool goodReturn = doc.setContent(content, &emsg); if (!goodReturn) { QLOG_DEBUG() << "Error with initial document: " << emsg << " running through tidy"; // Run it through "tidy". It is a program which will fix any invalid XML // and give us the results back through stdout. In a perfect world this // wouldn't be needed, but I've seen times where the ENML is bad for some reason. QProcess tidyProcess; tidyProcess.start("tidy -xml -raw -q -e", QIODevice::ReadWrite|QIODevice::Unbuffered); QLOG_DEBUG() << "Starting tidy " << tidyProcess.waitForStarted(); QByteArray b; b.append(QString::fromStdString(note.content)); tidyProcess.write(b); tidyProcess.closeWriteChannel(); QLOG_DEBUG() << "Stopping tidy " << tidyProcess.waitForFinished() << " Return Code: " << tidyProcess.state(); QLOG_DEBUG() << "Tidy Errors:" << tidyProcess.readAllStandardError(); content = tidyProcess.readAllStandardOutput(); // If the content is null, then we had a problem. Just risk going forward without tidy cleanup if (content.size() == 0) content = b; doc.setContent(content); } QLOG_DEBUG() << doc.toString(); // Remove all the temporary file names tempFiles.clear(); modifyTags(doc); // If we have search criteria, then do the highlighting if (enableHighlight) doc = addHighlight(doc); // Finish up and return the HTML to the user QDomElement docElem = doc.documentElement(); docElem.setTagName("body"); content = doc.toByteArray(3); qint32 index = content.indexOf("<body"); content.remove(0,index); content.prepend("<style type=\"text/css\">.en-crypt-temp { border-collapse:collapse; border-style:solid; border-color:blue; padding:0.0mm 0.0mm 0.0mm 0.0mm; }</style>"); content.prepend("<style type=\"text/css\">en-hilight { background-color: rgb(255,255,0) }</style>"); content.prepend("<style> img { height:auto; width:auto; max-height:auto; max-width:100%; }</style>"); content.prepend("<head><meta http-equiv=\"content-type\" content=\"text-html; charset=utf-8\"></head>"); content.prepend("<html>"); content.append("</html>"); if (!formatError && !readOnly) { NotebookTable ntable; qint32 notebookLid = ntable.getLid(note.notebookGuid); if (ntable.isReadOnly(notebookLid)) readOnly = true; } if (note.__isset.active && !note.active) readOnly = true; return content; }
OsproberEntryList runOsprober( PartitionCoreModule* core ) { QString osproberOutput; QProcess osprober; osprober.setProgram( "os-prober" ); osprober.setProcessChannelMode( QProcess::SeparateChannels ); osprober.start(); if ( !osprober.waitForStarted() ) { cDebug() << "ERROR: os-prober cannot start."; } else if ( !osprober.waitForFinished( 60000 ) ) { cDebug() << "ERROR: os-prober timed out."; } else { osproberOutput.append( QString::fromLocal8Bit( osprober.readAllStandardOutput() ).trimmed() ); } QString osProberReport( "Osprober lines, clean:\n" ); QStringList osproberCleanLines; OsproberEntryList osproberEntries; const auto lines = osproberOutput.split( '\n' ); for ( const QString& line : lines ) { if ( !line.simplified().isEmpty() ) { QStringList lineColumns = line.split( ':' ); QString prettyName; if ( !lineColumns.value( 1 ).simplified().isEmpty() ) prettyName = lineColumns.value( 1 ).simplified(); else if ( !lineColumns.value( 2 ).simplified().isEmpty() ) prettyName = lineColumns.value( 2 ).simplified(); QString path = lineColumns.value( 0 ).simplified(); if ( !path.startsWith( "/dev/" ) ) //basic sanity check continue; FstabEntryList fstabEntries = lookForFstabEntries( path ); QString homePath = findPartitionPathForMountPoint( fstabEntries, "/home" ); osproberEntries.append( { prettyName, path, QString(), canBeResized( core, path ), lineColumns, fstabEntries, homePath } ); osproberCleanLines.append( line ); } } osProberReport.append( osproberCleanLines.join( '\n' ) ); cDebug() << osProberReport; Calamares::JobQueue::instance()->globalStorage()->insert( "osproberLines", osproberCleanLines ); return osproberEntries; }
QString findPartitionPathForMountPoint( const FstabEntryList& fstab, const QString& mountPoint ) { if ( fstab.isEmpty() ) return QString(); for ( const FstabEntry& entry : fstab ) { if ( entry.mountPoint == mountPoint ) { QProcess readlink; QString partPath; if ( entry.partitionNode.startsWith( "/dev" ) ) // plain dev node { partPath = entry.partitionNode; } else if ( entry.partitionNode.startsWith( "LABEL=" ) ) { partPath = entry.partitionNode.mid( 6 ); partPath.remove( "\"" ); partPath.replace( "\\040", "\\ " ); partPath.prepend( "/dev/disk/by-label/" ); } else if ( entry.partitionNode.startsWith( "UUID=" ) ) { partPath = entry.partitionNode.mid( 5 ); partPath.remove( "\"" ); partPath = partPath.toLower(); partPath.prepend( "/dev/disk/by-uuid/" ); } else if ( entry.partitionNode.startsWith( "PARTLABEL=" ) ) { partPath = entry.partitionNode.mid( 10 ); partPath.remove( "\"" ); partPath.replace( "\\040", "\\ " ); partPath.prepend( "/dev/disk/by-partlabel/" ); } else if ( entry.partitionNode.startsWith( "PARTUUID=" ) ) { partPath = entry.partitionNode.mid( 9 ); partPath.remove( "\"" ); partPath = partPath.toLower(); partPath.prepend( "/dev/disk/by-partuuid/" ); } // At this point we either have /dev/sda1, or /dev/disk/by-something/... if ( partPath.startsWith( "/dev/disk/by-" ) ) // we got a fancy node { readlink.start( "readlink", { "-en", partPath }); if ( !readlink.waitForStarted( 1000 ) ) return QString(); if ( !readlink.waitForFinished( 1000 ) ) return QString(); if ( readlink.exitCode() != 0 || readlink.exitStatus() != QProcess::NormalExit ) return QString(); partPath = QString::fromLocal8Bit( readlink.readAllStandardOutput() ).trimmed(); } return partPath; } } return QString(); }
void GitCommand::run() { if (Git::Constants::debug) qDebug() << "GitCommand::run" << m_workingDirectory << m_jobs.size(); QProcess process; if (!m_workingDirectory.isEmpty()) process.setWorkingDirectory(m_workingDirectory); process.setEnvironment(m_environment); QByteArray stdOut; QByteArray stdErr; QString error; const int count = m_jobs.size(); int exitCode = -1; bool ok = true; for (int j = 0; j < count; j++) { if (Git::Constants::debug) qDebug() << "GitCommand::run" << j << '/' << count << m_jobs.at(j).arguments; process.start(m_binaryPath, m_basicArguments + m_jobs.at(j).arguments); if(!process.waitForStarted()) { ok = false; error += QString::fromLatin1("Error: \"%1\" could not be started: %2").arg(m_binaryPath, process.errorString()); break; } process.closeWriteChannel(); const int timeOutSeconds = m_jobs.at(j).timeout; if (!Utils::SynchronousProcess::readDataFromProcess(process, timeOutSeconds * 1000, &stdOut, &stdErr)) { Utils::SynchronousProcess::stopProcess(process); ok = false; error += msgTimeout(timeOutSeconds); break; } error += QString::fromLocal8Bit(stdErr); exitCode = process.exitCode(); switch (m_reportTerminationMode) { case NoReport: break; case ReportStdout: stdOut += msgTermination(exitCode, m_binaryPath, m_jobs.at(j).arguments).toUtf8(); break; case ReportStderr: error += msgTermination(exitCode, m_binaryPath, m_jobs.at(j).arguments); break; } } // Special hack: Always produce output for diff if (ok && stdOut.isEmpty() && m_jobs.front().arguments.at(0) == QLatin1String("diff")) { stdOut += "The file does not differ from HEAD"; } else { // @TODO: Remove, see below if (ok && m_jobs.front().arguments.at(0) == QLatin1String("status")) removeColorCodes(&stdOut); } if (ok && !stdOut.isEmpty()) emit outputData(stdOut); if (!error.isEmpty()) emit errorText(error); emit finished(ok, exitCode, m_cookie); if (ok) emit success(); // As it is used asynchronously, we need to delete ourselves this->deleteLater(); }
const AudioFileModel AnalyzeTask::analyzeFile(const QString &filePath, int *type) { *type = fileTypeNormal; AudioFileModel audioFile(filePath); QFile readTest(filePath); if(!readTest.open(QIODevice::ReadOnly)) { *type = fileTypeDenied; return audioFile; } if(checkFile_CDDA(readTest)) { *type = fileTypeCDDA; return audioFile; } readTest.close(); bool skipNext = false; unsigned int id_val[2] = {UINT_MAX, UINT_MAX}; cover_t coverType = coverNone; QByteArray coverData; QStringList params; params << QString("--Inform=file://%1").arg(QDir::toNativeSeparators(m_templateFile)); params << QDir::toNativeSeparators(filePath); QProcess process; lamexp_init_process(process, QFileInfo(m_mediaInfoBin).absolutePath()); process.start(m_mediaInfoBin, params); if(!process.waitForStarted()) { qWarning("MediaInfo process failed to create!"); qWarning("Error message: \"%s\"\n", process.errorString().toLatin1().constData()); process.kill(); process.waitForFinished(-1); return audioFile; } while(process.state() != QProcess::NotRunning) { if(*m_abortFlag) { process.kill(); qWarning("Process was aborted on user request!"); break; } if(!process.waitForReadyRead()) { if(process.state() == QProcess::Running) { qWarning("MediaInfo time out. Killing process and skipping file!"); process.kill(); process.waitForFinished(-1); return audioFile; } } QByteArray data; while(process.canReadLine()) { QString line = QString::fromUtf8(process.readLine().constData()).simplified(); if(!line.isEmpty()) { //qDebug("Line:%s", QUTF8(line)); int index = line.indexOf('='); if(index > 0) { QString key = line.left(index).trimmed(); QString val = line.mid(index+1).trimmed(); if(!key.isEmpty()) { updateInfo(audioFile, &skipNext, id_val, &coverType, &coverData, key, val); } } } } } if(audioFile.metaInfo().title().isEmpty()) { QString baseName = QFileInfo(filePath).fileName(); int index = baseName.lastIndexOf("."); if(index >= 0) { baseName = baseName.left(index); } baseName = baseName.replace("_", " ").simplified(); index = baseName.lastIndexOf(" - "); if(index >= 0) { baseName = baseName.mid(index + 3).trimmed(); } audioFile.metaInfo().setTitle(baseName); } process.waitForFinished(); if(process.state() != QProcess::NotRunning) { process.kill(); process.waitForFinished(-1); } if((coverType != coverNone) && (!coverData.isEmpty())) { retrieveCover(audioFile, coverType, coverData); } if((audioFile.techInfo().audioType().compare("PCM", Qt::CaseInsensitive) == 0) && (audioFile.techInfo().audioProfile().compare("Float", Qt::CaseInsensitive) == 0)) { if(audioFile.techInfo().audioBitdepth() == 32) audioFile.techInfo().setAudioBitdepth(AudioFileModel::BITDEPTH_IEEE_FLOAT32); } return audioFile; }
/** * 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; } if (m_singlethread) { arguments << QLatin1String("--singlethread"); } if (m_useCoreProfile) { arguments << QLatin1String("--core"); } if (m_captureState) { arguments << QLatin1String("-D"); arguments << QString::number(m_captureCall); } else if (m_captureThumbnails) { if (!m_thumbnailsToCapture.isEmpty()) { arguments << QLatin1String("-S"); arguments << thumbnailCallSet(); } arguments << QLatin1String("-s"); // emit snapshots arguments << QLatin1String("-"); // emit to stdout } else if (isProfiling()) { if (m_profileGpu) { arguments << QLatin1String("--pgpu"); } if (m_profileCpu) { arguments << QLatin1String("--pcpu"); } if (m_profilePixels) { arguments << QLatin1String("--ppd"); } } else { if (!m_doubleBuffered) { arguments << QLatin1String("--sb"); } if (m_benchmarking) { arguments << QLatin1String("-b"); } } arguments << 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) { process.waitForFinished(-1); QByteArray data = process.readAll(); QJsonParseError error; QJsonDocument jsonDoc = QJsonDocument::fromJson(data, &error); if (error.error != QJsonParseError::NoError) { //qDebug()<<"Error is "<<error.errorString(); msg = error.errorString(); } parsedJson = jsonDoc.toVariant().toMap(); } 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); }
bool AnalyzeTask::analyzeAvisynthFile(const QString &filePath, AudioFileModel &info) { QProcess process; lamexp_init_process(process, QFileInfo(m_avs2wavBin).absolutePath()); process.start(m_avs2wavBin, QStringList() << QDir::toNativeSeparators(filePath) << "?"); if(!process.waitForStarted()) { qWarning("AVS2WAV process failed to create!"); qWarning("Error message: \"%s\"\n", process.errorString().toLatin1().constData()); process.kill(); process.waitForFinished(-1); return false; } bool bInfoHeaderFound = false; while(process.state() != QProcess::NotRunning) { if(*m_abortFlag) { process.kill(); qWarning("Process was aborted on user request!"); break; } if(!process.waitForReadyRead()) { if(process.state() == QProcess::Running) { qWarning("AVS2WAV time out. Killing process and skipping file!"); process.kill(); process.waitForFinished(-1); return false; } } QByteArray data; while(process.canReadLine()) { QString line = QString::fromUtf8(process.readLine().constData()).simplified(); if(!line.isEmpty()) { int index = line.indexOf(':'); if(index > 0) { QString key = line.left(index).trimmed(); QString val = line.mid(index+1).trimmed(); if(bInfoHeaderFound && !key.isEmpty() && !val.isEmpty()) { if(key.compare("TotalSeconds", Qt::CaseInsensitive) == 0) { bool ok = false; unsigned int duration = val.toUInt(&ok); if(ok) info.techInfo().setDuration(duration); } if(key.compare("SamplesPerSec", Qt::CaseInsensitive) == 0) { bool ok = false; unsigned int samplerate = val.toUInt(&ok); if(ok) info.techInfo().setAudioSamplerate (samplerate); } if(key.compare("Channels", Qt::CaseInsensitive) == 0) { bool ok = false; unsigned int channels = val.toUInt(&ok); if(ok) info.techInfo().setAudioChannels(channels); } if(key.compare("BitsPerSample", Qt::CaseInsensitive) == 0) { bool ok = false; unsigned int bitdepth = val.toUInt(&ok); if(ok) info.techInfo().setAudioBitdepth(bitdepth); } } } else { if(line.contains("[Audio Info]", Qt::CaseInsensitive)) { info.techInfo().setAudioType("Avisynth"); info.techInfo().setContainerType("Avisynth"); bInfoHeaderFound = true; } } } } } process.waitForFinished(); if(process.state() != QProcess::NotRunning) { process.kill(); process.waitForFinished(-1); } //Check exit code switch(process.exitCode()) { case 0: qDebug("Avisynth script was analyzed successfully."); return true; break; case -5: qWarning("It appears that Avisynth is not installed on the system!"); return false; break; default: qWarning("Failed to open the Avisynth script, bad AVS file?"); return false; break; } }
void MainWindow::createGameWidget(){ // Creates a new process to be called QProcess *process = new QProcess; // Holds the path to the CreateTextFile.exe QString path = "./debug"; path.append("/CreateTextFile.exe"); // Displays the path to exe file //qDebug() << path; // Runs the CreateTextFile.exe process->start("CreateTextFile.exe"); // If the program fails to start, display an error message and exit the program if (process->waitForStarted() == false){ qDebug() << "Error starting CreateTextFile.exe"; qDebug() << process->errorString(); exit (-1); } // If the program runs, display a message saying it ran fine if (process->waitForStarted() == true){ qDebug() << "Running CreateTextFile.exe"; } // Close the .exe file after it has created the Instructions text file needed qDebug() << "Closing CreateTextFile.exe"; process->close(); // Creates a variable that will hold the path to the Instructions text file generated from process QFile text("C:/instructions.txt"); // Checks to see if file can be opened, if not, displays error if(!text.open(QIODevice::ReadOnly | QIODevice::Text)) QMessageBox::information(0, "Error", text.errorString()); // Creates the instructions label that will appear besides the game QLabel *instructions = new QLabel; // Outputs all lines in the text file instructions->setText(text.readAll()); instructions->setStyleSheet("QLabel{color: white}"); instructions->setFont(QFont("MS Shell Dlg 2", 12)); instructions->setFixedWidth(200); instructions->setWordWrap(true); // Closes the text file text.close(); // Creates a label that will display the user's score for each brick destroyed QLabel *scoreLabel = new QLabel(tr("Score: ")); scoreLabel->setStyleSheet("QLabel{color: white}"); scoreLabel->setFont(QFont("MS Shell Dlg 2", 12, QFont::Bold)); scoreLabel->setFixedHeight(20); scoreCount = new QLabel(tr("")); scoreCount->setStyleSheet("QLabel{color: white}"); scoreCount->setFrameShape(QFrame::Box); scoreCount->setFrameShadow(QFrame::Sunken); scoreCount->setFixedSize(200, 60); // Creates a temporary push button to act as a filler for the brick break game QPushButton *tempButton = new QPushButton(tr("Filler for Game Space")); tempButton->setFixedSize(330, 392); // Creates a reset button that resets the game if clicked resetGame = new QPushButton(tr("&Reset")); resetGame->setFixedSize(140,40); resetGame->setFont(QFont("MS Shell Dlg 2", 10, QFont::Bold)); resetGame->setStyleSheet("QPushButton{background-image:url(:/Resource/images/Exit.png); color: white; border-width: 3px; border-color: #181D1F; border-style: outset; border-radius: 7;}" "QPushButton:hover{background-image:url(:/Resource/images/Exit-Hover.png);}" "QPushButton:pressed{background-image:url(:/Resource/images/Exit-Clicked.png);}"); // Sets up the group box and layout for the Game widget scoreGroupBox = new QGroupBox(tr("")); scoreGroupBox->setStyleSheet("QGroupBox{color:white}"); QVBoxLayout *gameVLayout = new QVBoxLayout; gameVLayout->addSpacing(15); gameVLayout->addWidget(scoreLabel, 0, Qt::AlignHCenter); gameVLayout->addWidget(scoreCount, 0, Qt::AlignHCenter); gameVLayout->addWidget(instructions, 0, Qt::AlignHCenter); gameVLayout->addWidget(resetGame, 0, Qt::AlignHCenter); gameVLayout->addSpacing(15); scoreGroupBox->setLayout(gameVLayout); scoreGroupBox->setFixedWidth(240); QHBoxLayout *gameHLayout = new QHBoxLayout; gameHLayout->addWidget(tempButton, 0, Qt::AlignLeft); gameHLayout->addWidget(scoreGroupBox); gameWidget = new QWidget; gameWidget->setLayout(gameHLayout); }
// Index any files that are attached. void IndexRunner::indexAttachment(qint32 lid, Resource &r) { if (!officeFound) return; QLOG_DEBUG() << "indexing attachment to note " << lid; if (!keepRunning || pauseIndexing) { indexTimer->start(); return; } ResourceTable rtable(db); qint32 reslid = rtable.getLid(r.guid); if (lid <= 0) { indexTimer->start(); return; } QLOG_DEBUG() << "Resource " << reslid; QString extension = ""; ResourceAttributes attributes; if (r.attributes.isSet()) attributes = r.attributes; if (attributes.fileName.isSet()) { extension = attributes.fileName; int i = extension.indexOf("."); if (i != -1) extension = extension.mid(i); } if (extension != ".doc" && extension != ".xls" && extension != ".ppt" && extension != ".docx" && extension != ".xlsx" && extension != ".pptx" && extension != ".pps" && extension != ".pdf" && extension != ".odt" && extension != ".odf" && extension != ".ott" && extension != ".odm" && extension != ".html" && extension != ".txt" && extension != ".oth" && extension != ".ods" && extension != ".ots" && extension != ".odg" && extension != ".otg" && extension != ".odp" && extension != ".otp" && extension != ".odb" && extension != ".oxt" && extension != ".htm" && extension != ".docm") return; QString file = global.fileManager.getDbaDirPath() + QString::number(reslid) +extension; QFile dataFile(file); if (!dataFile.exists()) { QDir dir(global.fileManager.getDbaDirPath()); QStringList filterList; filterList.append(QString::number(lid)+".*"); QStringList list= dir.entryList(filterList, QDir::Files); if (list.size() > 0) { file = global.fileManager.getDbaDirPath()+list[0]; } } QString outDir = global.fileManager.getTmpDirPath(); QProcess sofficeProcess; QString cmd = "soffice --headless --convert-to txt:\"Text\" --outdir " +outDir + " " +file; sofficeProcess.start(cmd, QIODevice::ReadWrite|QIODevice::Unbuffered); QLOG_DEBUG() << "Starting soffice "; sofficeProcess.waitForStarted(); QLOG_DEBUG() << "Waiting for completion"; sofficeProcess.waitForFinished(); int rc = sofficeProcess.exitCode(); QLOG_DEBUG() << "soffice Errors:" << sofficeProcess.readAllStandardError(); QLOG_DEBUG() << "soffice Output:" << sofficeProcess.readAllStandardOutput(); QLOG_DEBUG() << "return code:" << rc; if (rc == 255) { QLOG_ERROR() << "soffice not found. Disabling attachment indexing."; this->officeFound = false; return; } QFile txtFile(outDir+QString::number(reslid) +".txt"); if (txtFile.open(QIODevice::ReadOnly)) { QString text; text = txtFile.readAll(); NSqlQuery sql(db); db->lockForWrite(); sql.prepare("Insert into SearchIndex (lid, weight, source, content) values (:lid, :weight, 'recognition', :content)"); sql.bindValue(":lid", lid); sql.bindValue(":weight", 100); sql.bindValue(":content", text); QLOG_DEBUG() << "Adding note resource to index DB"; sql.exec(); db->unlock(); txtFile.close(); } QDir dir; dir.remove(outDir+QString::number(reslid) +".txt"); }
void SyncContactsThread::run() { m_bStop = false; QMutex *mutex = &(g_pContactManager->m_LoadContactsMutex); if (mutex->tryLock(5000)==false) { // wait 5 seconds max. emit loadingContactsFinished(false, "Mutex lock failed."); return; } { // we remove connection at the end, so finish with QSqlDatabase object in this scope QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE", SQLITE_DB_CONNECTION_NAME); db.setDatabaseName(DBPath); db.open(); } QString resultErrorMessage; bool bContactsLoadedSuccessfully = true; if (global::IsOutlookInstalled()) { bContactsLoadedSuccessfully = false; QString db_path= g_pContactManager->getDBPath(); QString log_path = g_AppSettingsFolderPath + "/outcall.log"; //if outlook x64 if (true/*IsOutlook64bit()*/) // always use helper app to avoid potential crashing in outcall { bool b64 = global::IsOutlook64bit(); QString helper_path; if (b64) helper_path = g_AppDirPath + "/Outlook/x64/outlook_helper_x64.exe"; else helper_path = g_AppDirPath + "/Outlook/outlook_helper.exe"; QStringList arguments; QString exchange = "true"; arguments << QString("LoadContacts").toLatin1().data() << db_path.toLatin1().data() << log_path.toLatin1().data() << exchange; //HelperProcess outlookHelperProcess(helper_path, arguments); QProcess outlookHelperProcess; if (b64) outlookHelperProcess.setWorkingDirectory(g_AppDirPath + "/Outlook/x64"); else outlookHelperProcess.setWorkingDirectory(g_AppDirPath + "/Outlook"); outlookHelperProcess.start(helper_path, arguments); if (!outlookHelperProcess.waitForStarted(10000)) { if (b64) resultErrorMessage = "Outlook helper x64 could not be started."; else resultErrorMessage = "Outlook helper could not be started."; } else { while (!m_bStop) { if (outlookHelperProcess.waitForFinished(1000)) break; } if (m_bStop) { outlookHelperProcess.kill(); resultErrorMessage = "Cancelled"; } else { resultErrorMessage = QString(outlookHelperProcess.readAllStandardOutput()); if (resultErrorMessage=="_ok_") { bContactsLoadedSuccessfully = true; resultErrorMessage = ""; } else if (resultErrorMessage.isEmpty()) { resultErrorMessage = tr("Unknown error. Check log files for more information."); } /*if (resultErrorMessage.isEmpty()) bContactsLoadedSuccessfully = true;*/ } } } } QSqlDatabase::removeDatabase(SQLITE_DB_CONNECTION_NAME); // free resources mutex->unlock(); emit loadingContactsFinished(bContactsLoadedSuccessfully, resultErrorMessage); }
void StelLogger::init(const QString& logFilePath) { logFile.setFileName(logFilePath); if (logFile.open(QIODevice::WriteOnly | QIODevice::Truncate | QIODevice::Text | QIODevice::Unbuffered)) qInstallMessageHandler(StelLogger::debugLogHandler); // write timestamp writeLog(QString("%1").arg(QDateTime::currentDateTime().toString(Qt::ISODate))); // write info about operating system writeLog(StelUtils::getOperatingSystemInfo()); // write compiler version #if defined __GNUC__ && !defined __clang__ #ifdef __MINGW32__ #define COMPILER "MinGW GCC" #else #define COMPILER "GCC" #endif writeLog(QString("Compiled using %1 %2.%3.%4").arg(COMPILER).arg(__GNUC__).arg(__GNUC_MINOR__).arg(__GNUC_PATCHLEVEL__)); #elif defined __clang__ writeLog(QString("Compiled using %1 %2.%3.%4").arg("Clang").arg(__clang_major__).arg(__clang_minor__).arg(__clang_patchlevel__)); #elif defined _MSC_VER writeLog(QString("Compiled using %1").arg(getMsvcVersionString(_MSC_VER))); #else writeLog("Unknown compiler"); #endif // write Qt version writeLog(QString("Qt runtime version: %1").arg(qVersion())); writeLog(QString("Qt compilation version: %1").arg(QT_VERSION_STR)); // write addressing mode #if defined(__LP64__) || defined(_WIN64) writeLog("Addressing mode: 64-bit"); #else writeLog("Addressing mode: 32-bit"); #endif // write memory and CPU info #ifdef Q_OS_LINUX #ifndef BUILD_FOR_MAEMO QFile infoFile("/proc/meminfo"); if(!infoFile.open(QIODevice::ReadOnly | QIODevice::Text)) writeLog("Could not get memory info."); else { while(!infoFile.peek(1).isEmpty()) { QString line = infoFile.readLine(); line.chop(1); if (line.startsWith("Mem") || line.startsWith("SwapTotal")) writeLog(line); } infoFile.close(); } infoFile.setFileName("/proc/cpuinfo"); if (!infoFile.open(QIODevice::ReadOnly | QIODevice::Text)) writeLog("Could not get CPU info."); else { while(!infoFile.peek(1).isEmpty()) { QString line = infoFile.readLine(); line.chop(1); if(line.startsWith("model name") || line.startsWith("cpu MHz")) writeLog(line); } infoFile.close(); } QProcess lspci; lspci.start("lspci -v", QIODevice::ReadOnly); lspci.waitForFinished(300); const QString pciData(lspci.readAll()); QStringList pciLines = pciData.split('\n', QString::SkipEmptyParts); for (int i = 0; i<pciLines.size(); i++) { if(pciLines.at(i).contains("VGA compatible controller")) { writeLog(pciLines.at(i)); i++; while(i < pciLines.size() && pciLines.at(i).startsWith('\t')) { if(pciLines.at(i).contains("Kernel driver in use")) writeLog(pciLines.at(i).trimmed()); else if(pciLines.at(i).contains("Kernel modules")) writeLog(pciLines.at(i).trimmed()); i++; } } } #endif // Aargh Windows API #elif defined Q_OS_WIN // Hopefully doesn't throw a linker error on earlier systems. Not like // I'm gonna test it or anything. if (QSysInfo::WindowsVersion >= QSysInfo::WV_2000) { #ifdef __LP64__ MEMORYSTATUSEX statex; GlobalMemoryStatusEx(&statex); writeLog(QString("Total physical memory: %1 MB (unreliable)").arg(statex.ullTotalPhys/(1024<<10))); writeLog(QString("Total virtual memory: %1 MB (unreliable)").arg(statex.ullTotalVirtual/(1024<<10))); writeLog(QString("Physical memory in use: %1%").arg(statex.dwMemoryLoad)); #else MEMORYSTATUS statex; GlobalMemoryStatus(&statex); writeLog(QString("Total memory: %1 MB (unreliable)").arg(statex.dwTotalPhys/(1024<<10))); writeLog(QString("Total virtual memory: %1 MB (unreliable)").arg(statex.dwTotalVirtual/(1024<<10))); writeLog(QString("Physical memory in use: %1%").arg(statex.dwMemoryLoad)); #endif } else writeLog("Windows version too old to get memory info."); HKEY hKey = NULL; DWORD dwType = REG_DWORD; DWORD numVal = 0; DWORD dwSize = sizeof(numVal); // iterate over the processors listed in the registry QString procKey = "Hardware\\Description\\System\\CentralProcessor"; LONG lRet = ERROR_SUCCESS; int i; for(i = 0; lRet == ERROR_SUCCESS; i++) { lRet = RegOpenKeyExA(HKEY_LOCAL_MACHINE, qPrintable(QString("%1\\%2").arg(procKey).arg(i)), 0, KEY_QUERY_VALUE, &hKey); if(lRet == ERROR_SUCCESS) { if(RegQueryValueExA(hKey, "~MHz", NULL, &dwType, (LPBYTE)&numVal, &dwSize) == ERROR_SUCCESS) writeLog(QString("Processor speed: %1 MHz").arg(numVal)); else writeLog("Could not get processor speed."); } // can you believe this trash? dwType = REG_SZ; char nameStr[512]; DWORD nameSize = sizeof(nameStr); if (lRet == ERROR_SUCCESS) { if (RegQueryValueExA(hKey, "ProcessorNameString", NULL, &dwType, (LPBYTE)&nameStr, &nameSize) == ERROR_SUCCESS) writeLog(QString("Processor name: %1").arg(nameStr)); else writeLog("Could not get processor name."); } RegCloseKey(hKey); } if(i == 0) writeLog("Could not get processor info."); #elif defined Q_OS_MAC QProcess systemProfiler; systemProfiler.start("/usr/sbin/system_profiler -detailLevel mini SPHardwareDataType SPDisplaysDataType"); systemProfiler.waitForStarted(); systemProfiler.waitForFinished(); const QString systemData(systemProfiler.readAllStandardOutput()); QStringList systemLines = systemData.split('\n', QString::SkipEmptyParts); for (int i = 0; i<systemLines.size(); i++) { if(systemLines.at(i).contains("Model")) { writeLog(systemLines.at(i).trimmed()); } if(systemLines.at(i).contains("Processor")) { writeLog(systemLines.at(i).trimmed()); } if(systemLines.at(i).contains("Memory")) { writeLog(systemLines.at(i).trimmed()); } if(systemLines.at(i).contains("VRAM")) { writeLog(systemLines.at(i).trimmed()); } } #elif defined Q_OS_BSD4 QProcess dmesg; dmesg.start("/sbin/dmesg", QIODevice::ReadOnly); dmesg.waitForStarted(); dmesg.waitForFinished(); const QString dmesgData(dmesg.readAll()); QStringList dmesgLines = dmesgData.split('\n', QString::SkipEmptyParts); for (int i = 0; i<dmesgLines.size(); i++) { if (dmesgLines.at(i).contains("memory")) { writeLog(dmesgLines.at(i).trimmed()); } if (dmesgLines.at(i).contains("CPU")) { writeLog(dmesgLines.at(i).trimmed()); } if (dmesgLines.at(i).contains("VGA")) { writeLog(dmesgLines.at(i).trimmed()); } } #endif }
int main(int argc, char *argv[]) { try { QApplication app(argc, argv); QString commands; //Mac specific Terminal command commands = "system_profiler SPHardwareDataType"; //commands = "cat abc"; /* Wrong cat file -- testing */ //commands = " abc"; /* Wrong Terminal command -- testing */ /* For Linux and Ubuntu we use -- cat /proc/cpuinfo*/ QQmlApplicationEngine engine; engine.load(QUrl(QStringLiteral("qrc:/main.qml"))); QProcess *process = new QProcess(0); process->setProcessChannelMode(QProcess::MergedChannels); //process->start("system_profiler SPHardwareDataType"); process->start(commands); QByteArray arrSysInfo; process->write(arrSysInfo); process->closeWriteChannel(); if(!process->waitForStarted()){ qDebug() << "Could not wait to start..." << process->error() << process->errorString(); } if(!process->waitForFinished()) { qDebug() << "Could not wait to finish..." << process->error() << process->errorString(); } else{ mySysInfo output; /* interface */ output.setData( process->readAll()); QObject *rootObject = engine.rootObjects().first(); QObject* lstview = rootObject->findChild<QObject*>("lstview"); if (lstview) lstview->setProperty("placeholderText", output.getData());//quick fix } return app.exec(); } catch(std::exception e) {\ qDebug() << "Exception caught in main()" << e.what(); } }
void Editor::importMovie (QString filePath, int fps) { int i; QSettings settings("Pencil","Pencil"); qDebug() << "-------IMPORT VIDEO------" << filePath; // --------- Import all the temporary frames ---------- QDir::temp().mkdir("pencil"); QString tempPath = QDir::temp().absolutePath()+"/pencil/"; QProgressDialog progress("Importing movie...", "Abort", 0, 100, NULL); progress.setWindowModality(Qt::WindowModal); progress.show(); progress.setValue(10); QProcess ffmpeg; qDebug() << "ffmpeg -i \"" << filePath << "\" -r " << QString::number(fps) << " -f image2 \"" << tempPath << "tmp_import%4d.png\""; ffmpeg.start("ffmpeg -i \"" + filePath + "\" -r " + QString::number(fps) + " -f image2 \"" + tempPath + "tmp_import%4d.png\""); progress.setValue(20); if (ffmpeg.waitForStarted() == true) { if (ffmpeg.waitForFinished() == true) { QByteArray sErr = ffmpeg.readAllStandardError(); if (sErr == "") {qDebug() << "ERROR: Could not execute FFmpeg.";} else { qDebug() << "stderr: " + ffmpeg.readAllStandardOutput(); qDebug() << "stdout: " << sErr; } } else {qDebug() << "ERROR: FFmpeg did not finish executing.";} } else {qDebug() << "Please install FFMPEG: sudo apt-get install ffmpeg";} progress.setValue(50); QDir dir1(tempPath); int nFiles = dir1.entryList().count(); i=1; QString frameNumberString = QString::number(i); while( frameNumberString.length() < 4) frameNumberString.prepend("0"); while (QFile::exists(tempPath+"tmp_import"+frameNumberString+".png")) { progress.setValue(50+i*50/nFiles); if(i>1) scrubForward(); importImage(tempPath+"tmp_import"+frameNumberString+".png"); i++; frameNumberString = QString::number(i); while( frameNumberString.length() < 4) frameNumberString.prepend("0"); } progress.setValue(100); // --------- Clean up temp directory --------- QDir dir(tempPath); QStringList filtername("*.*"); QStringList entries = dir.entryList(filtername,QDir::Files,QDir::Type); for(int i=0; i<entries.size(); i++) dir.remove(entries[i]); }
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 }
// added parameter exportFps -> frame rate of exported video // added parameter exportFormat -> to set ffmpeg parameters bool Object::exportMovie( ExportMovieParameters parameters ) { int startFrame = parameters.startFrame; int endFrame = parameters.endFrame; QTransform view = parameters.view; Layer* currentLayer = parameters.currentLayer; QSize exportSize = parameters.exportSize; QString filePath = parameters.filePath; int fps = parameters.fps; int exportFps = parameters.exportFps; QString exportFormat = parameters.exportFormat; if(!filePath.endsWith(".avi", Qt::CaseInsensitive)) { filePath = filePath + ".avi"; } // additional parameters for ffmpeg QString ffmpegParameter = ""; if(filePath.endsWith(".avi", Qt::CaseInsensitive)) {ffmpegParameter = " -vcodec msmpeg4 ";} if(filePath.endsWith(".mov", Qt::CaseInsensitive)) {ffmpegParameter = "";} if(filePath.endsWith(".mp4", Qt::CaseInsensitive)) {ffmpegParameter = "";} qDebug() << "-------VIDEO------"; // --------- Export all the temporary frames ---------- QDir::temp().mkdir("pencil"); QString tempPath = QDir::temp().absolutePath()+"/pencil/"; QProgressDialog progress("Exporting movie...", "Abort", 0, 100, NULL); progress.setWindowModality(Qt::WindowModal); progress.show(); QDir dir2(filePath); if (QFile::exists(filePath) == true) { dir2.remove(filePath); } const char* format = "png"; ExportFrames1Parameters par; par.frameStart = startFrame; par.frameEnd = endFrame; par.view = view; par.currentLayer = currentLayer; par.exportSize = exportSize; par.filePath = tempPath + "tmp"; par.format = format; par.quality = 100; par.background = true; par.antialiasing = true; par.progress = &progress; par.progressMax = 50; par.fps = fps; par.exportFps = exportFps; exportFrames1( par ); // --------- Quicktime assemble call ---------- QDir sampledir; qDebug() << "testmic:" << sampledir.filePath(filePath); QProcess ffmpeg; qDebug() << "Trying to export VIDEO"; quint32 audioDataSize = 44100*2*2*(endFrame-1)/fps; qint16* audioData =(qint16*) malloc(audioDataSize); for (uint i = 0; i < audioDataSize/2; i++ ) audioData[i] = 0; quint16 header1[22]; bool audioDataValid = false; for(int i = 0; i < this->getLayerCount() ; i++) { Layer* layer = this->getLayer(i); if(layer->type() == Layer::SOUND) { auto pSoundLayer = static_cast< LayerSound* >( layer ); pSoundLayer->foreachKeyFrame( [&] ( KeyFrame* key ) { int l = 0; // FIXME: export sound // convert audio file: 44100Hz sampling rate, stereo, signed 16 bit little endian // supported audio file types: wav, mp3, ogg... ( all file types supported by ffmpeg ) qDebug() << "ffmpeg -i \"" + ((LayerSound*)layer)->getSoundFilepathAt(l) + "\" -ar 44100 -acodec pcm_s16le -ac 2 -y \"" + tempPath + "tmpaudio0.wav\""; ffmpeg.start("ffmpeg -i \"" + ((LayerSound*)layer)->getSoundFilepathAt(l) + "\" -ar 44100 -acodec pcm_s16le -ac 2 -y \"" + tempPath + "tmpaudio0.wav\""); if (ffmpeg.waitForStarted() == true) { if (ffmpeg.waitForFinished() == true) { QByteArray sErr = ffmpeg.readAllStandardError(); if (sErr == "") { qDebug() << "ERROR: Could not execute FFmpeg."; } else { qDebug() << "stdout: " << ffmpeg.readAllStandardOutput(); qDebug() << "stderr: " << sErr; qDebug() << "AUDIO conversion done. ( file: " << ((LayerSound*)layer)->getSoundFilepathAt(l) << ")"; } } else { qDebug() << "ERROR: FFmpeg did not finish executing."; } } else { qDebug() << "ERROR: Could not execute FFmpeg."; } int frame = key->pos() - 1; float fframe = (float)frame/(float)fps; QFile file(tempPath+"tmpaudio0.wav"); qDebug() << "audio file " + tempPath+"tmpaudio0.wav"; file.open(QIODevice::ReadOnly); file.read((char*)header1,sizeof(header1)); quint32 audioSize = header1[21]; audioSize = audioSize * 65536 + header1[20]; qDebug() << "audio len " << audioSize; // before calling malloc should check: audioSize < max credible value qint16* data = (qint16*) malloc(audioSize); file.read((char*)data,audioSize); audioDataValid = true; int delta = fframe*44100*2; qDebug() << "audio delta " << delta; int indexMax = MIN(audioSize/2,audioDataSize/2-delta); // audio files 'mixing': 'higher' sound layers overwrite 'lower' sound layers for (int index = 0; index < indexMax; index++) { audioData[index+delta] = safeSum(audioData[index+delta],data[index]); } free(data); file.close(); } ); } } if ( audioDataValid ) { // save mixed audio file ( will be used as audio stream ) QFile file(tempPath+"tmpaudio.wav"); file.open(QIODevice::WriteOnly); header1[20] = audioDataSize % 65536; header1[21] = audioDataSize / 65536; file.write((char*)header1,sizeof(header1)); file.write((char*)audioData,audioDataSize); file.close(); } // video input: frame sequence ( -i tmp%03d.png ) // frame rate ( -r fps ) // audio input: ( -i tmpaudio.wav ) // movie output: ( filePath ) // frame rate ( -r 25 ) if ( audioDataValid ) { qDebug() << "ffmpeg -r " + QString::number(exportFps) + " -i " + tempPath + "tmp%4d.png -i " + tempPath + "tmpaudio.wav -r " + QString::number(exportFps) + " -y " + ffmpegParameter + "\"" + filePath + "\""; ffmpeg.start("ffmpeg -r " + QString::number(exportFps) + " -i " + tempPath + "tmp%4d.png -i " + tempPath + "tmpaudio.wav -r " + QString::number(exportFps) + " -y " + ffmpegParameter + "\"" + filePath + "\""); } else { qDebug() << "ffmpeg -r " + QString::number(exportFps) + " -i " + tempPath + "tmp%4d.png -r " + QString::number(exportFps) + " -y " + ffmpegParameter + "\"" + filePath + "\""; ffmpeg.start("ffmpeg -r " + QString::number(exportFps) + " -i " + tempPath + "tmp%4d.png -r " + QString::number(exportFps) + " -y " + ffmpegParameter + "\"" + filePath + "\""); } if (ffmpeg.waitForStarted() == true) { if (ffmpeg.waitForFinished() == true) { QByteArray sErr = ffmpeg.readAllStandardError(); if (sErr == "") { qDebug() << "ERROR: Could not execute FFmpeg."; } else { qDebug() << "stdout: " << ffmpeg.readAllStandardOutput(); qDebug() << "stderr: " << sErr; qDebug() << "dbg:" << QDir::current().currentPath() +"/plugins/"; qDebug() << ":" << tempPath + "tmp%03d.png"; qDebug() << ":\"" + filePath + "\""; qDebug() << "VIDEO export done."; } } else { qDebug() << "ERROR: FFmpeg did not finish executing."; } } else { qDebug() << "Please install FFMPEG: sudo apt-get install ffmpeg"; } progress.setValue(100); free(audioData); // --------- Clean up temp directory --------- QDir dir(tempPath); QStringList filtername("*.*"); QStringList entries = dir.entryList(filtername,QDir::Files,QDir::Type); for(int i=0; i<entries.size(); i++) dir.remove(entries[i]); qDebug() << "-----"; return true; }
void qtDLGAssembler::InsertNewInstructions() { if(lineEdit->text().length() <= 0) { close(); return; } QMap<quint64,DisAsDataRow>::const_iterator i = m_pCurrentDisassembler->SectionDisAs.constFind(m_instructionOffset); if(i == m_pCurrentDisassembler->SectionDisAs.constEnd()) { close(); return; } QString oldOpcodes = i.value().OpCodes; DWORD oldOpcodeLen = oldOpcodes.replace(" ", "").length() / 2, newOpcodeLen = NULL; QFile tempOutput("nanomite.asm"); tempOutput.open(QIODevice::WriteOnly | QIODevice::Text); QTextStream out(&tempOutput); if(m_is64Bit) out << "BITS 64\n"; else out << "BITS 32\n"; out << "org 0x" << hex << i.value().Offset << "\r\n"; out << lineEdit->text(); tempOutput.close(); QProcess nasm; nasm.setReadChannel(QProcess::StandardOutput); nasm.setProcessChannelMode(QProcess::MergedChannels); nasm.start("nasm.exe -o nanomite.bin nanomite.asm"); if (!nasm.waitForStarted()) { QMessageBox::critical(this, "Nanomite", "Unable to launch assembler!", QMessageBox::Ok, QMessageBox::Ok); close(); return; } while(nasm.state() != QProcess::NotRunning) { nasm.waitForReadyRead(); QString errorMessage = nasm.readAll(); if(errorMessage.contains("nanomite.asm:3:")) { errorMessage.replace("nanomite.asm:3:",""); QMessageBox::critical(this, "Nanomite", errorMessage, QMessageBox::Ok, QMessageBox::Ok); lineEdit->clear(); return; } } DeleteFile(L"nanomite.asm"); HANDLE hFile = CreateFileW(L"nanomite.bin",GENERIC_READ,FILE_SHARE_READ,NULL,OPEN_EXISTING,NULL,NULL); if(hFile == INVALID_HANDLE_VALUE) { lineEdit->clear(); return; } int iLen = GetFileSize(hFile,NULL); LPVOID pFileBuffer = clsMemManager::CAlloc(iLen); DWORD BytesRead = NULL; if(!ReadFile(hFile,pFileBuffer,iLen,&BytesRead,NULL)) { CloseHandle(hFile); DeleteFile(L"nanomite.bin"); clsMemManager::CFree(pFileBuffer); QMessageBox::critical(this,"Nanomite","no valid opcodes found!",QMessageBox::Ok,QMessageBox::Ok); lineEdit->clear(); return; } CloseHandle(hFile); DeleteFile(L"nanomite.bin"); if(BytesRead <= 0) { clsMemManager::CFree(pFileBuffer); QMessageBox::critical(this,"Nanomite","no valid opcodes found!",QMessageBox::Ok,QMessageBox::Ok); lineEdit->clear(); return; } if(oldOpcodeLen >= BytesRead) newOpcodeLen = oldOpcodeLen; else if(oldOpcodeLen < BytesRead) { newOpcodeLen = oldOpcodeLen; while(newOpcodeLen < BytesRead) { ++i; if(i == m_pCurrentDisassembler->SectionDisAs.constEnd()) return; oldOpcodes = i.value().OpCodes; newOpcodeLen += oldOpcodes.replace(" ", "").length() / 2; } } LPVOID pBuffer = clsMemManager::CAlloc(newOpcodeLen); memset(pBuffer,0x90,newOpcodeLen); memcpy(pBuffer,pFileBuffer,BytesRead); qtDLGPatchManager::AddNewPatch(GetProcessId(m_processHandle), m_processHandle, m_instructionOffset, newOpcodeLen, pBuffer); clsMemManager::CFree(pBuffer); clsMemManager::CFree(pFileBuffer); lineEdit->clear(); close(); }
void AndroidCreateKeystoreCertificate::on_buttonBox_accepted() { switch (checkKeystorePassword()) { case Invalid: ui->keystorePassLineEdit->setFocus(); return; case NoMatch: ui->keystoreRetypePassLineEdit->setFocus(); return; default: break; } switch (checkCertificatePassword()) { case Invalid: ui->certificatePassLineEdit->setFocus(); return; case NoMatch: ui->certificateRetypePassLineEdit->setFocus(); return; default: break; } if (!ui->aliasNameLineEdit->text().length()) ui->aliasNameLineEdit->setFocus(); if (!ui->commonNameLineEdit->text().length()) ui->commonNameLineEdit->setFocus(); if (!ui->organizationNameLineEdit->text().length()) ui->organizationNameLineEdit->setFocus(); if (!ui->localityNameLineEdit->text().length()) ui->localityNameLineEdit->setFocus(); if (!ui->countryLineEdit->text().length()) ui->countryLineEdit->setFocus(); m_keystoreFilePath = QFileDialog::getSaveFileName(this, tr("Keystore file name"), QDir::homePath() + QLatin1String("/android_release.keystore"), tr("Keystore files (*.keystore *.jks)")); if (!m_keystoreFilePath.length()) return; QString distinguishedNames(QString::fromLatin1("CN=%1, O=%2, L=%3, C=%4") .arg(ui->commonNameLineEdit->text().replace(QLatin1Char(','), QLatin1String("\\,"))) .arg(ui->organizationNameLineEdit->text().replace(QLatin1Char(','), QLatin1String("\\,"))) .arg(ui->localityNameLineEdit->text().replace(QLatin1Char(','), QLatin1String("\\,"))) .arg(ui->countryLineEdit->text().replace(QLatin1Char(','), QLatin1String("\\,")))); if (ui->organizationUnitLineEdit->text().length()) distinguishedNames += QLatin1String(", OU=") + ui->organizationUnitLineEdit->text().replace(QLatin1Char(','), QLatin1String("\\,")); if (ui->stateNameLineEdit->text().length()) distinguishedNames += QLatin1String(", S=") + ui->stateNameLineEdit->text().replace(QLatin1Char(','), QLatin1String("\\,")); QStringList params; params << QLatin1String("-genkey") << QLatin1String("-keyalg") << QLatin1String("RSA") << QLatin1String("-keystore") << m_keystoreFilePath << QLatin1String("-storepass") << ui->keystorePassLineEdit->text() << QLatin1String("-alias") << ui->aliasNameLineEdit->text() << QLatin1String("-keysize") << ui->keySizeSpinBox->text() << QLatin1String("-validity") << ui->validitySpinBox->text() << QLatin1String("-keypass") << ui->certificatePassLineEdit->text() << QLatin1String("-dname") << distinguishedNames; QProcess genKeyCertProc; genKeyCertProc.start(AndroidConfigurations::instance().keytoolPath(), params ); if (!genKeyCertProc.waitForStarted() || !genKeyCertProc.waitForFinished()) return; if (genKeyCertProc.exitCode()) { QMessageBox::critical(this, tr("Error") , QString::fromLatin1(genKeyCertProc.readAllStandardOutput()) + QString::fromLatin1(genKeyCertProc.readAllStandardError())); return; } accept(); }
bool processXmlFile(const QString &xmlFile) { QFile file(xmlFile); if (!file.open(QIODevice::ReadOnly)) return false; const QLatin1String tag_app("app"); const QLatin1String attrib_mainQmlFile("mainqmlfile"); const QLatin1String attrib_projectPath("projectpath"); const QLatin1String attrib_projectName("projectname"); const QLatin1String attrib_screenOrientation("screenorientation"); const QLatin1String value_screenOrientationLockLandscape("LockLandscape"); const QLatin1String value_screenOrientationLockPortrait("LockPortrait"); const QLatin1String attrib_networkAccess("networkaccess"); static const QString qtDir = QLibraryInfo::location(QLibraryInfo::PrefixPath) + QLatin1Char('/'); QXmlStreamReader reader(&file); while (!reader.atEnd()) { const QXmlStreamReader::TokenType token = reader.readNext(); switch (token) { case QXmlStreamReader::StartElement: if (reader.name() == tag_app) { QtQuickApp app; QFileInfo projectPath; if (!reader.attributes().hasAttribute(attrib_projectPath)) { qDebug() << "Project without path found"; continue; } projectPath = qtDir + reader.attributes().value(attrib_projectPath).toString(); app.setProjectPath(projectPath.absoluteFilePath()); if (reader.attributes().hasAttribute(attrib_mainQmlFile)) { const QFileInfo qmlFileOrigin( qtDir + reader.attributes().value(attrib_mainQmlFile).toString()); if (!qmlFileOrigin.exists()) { qDebug() << "Cannot find" << QDir::toNativeSeparators(qmlFileOrigin.absoluteFilePath()); continue; } const QFileInfo qmlTargetPath(QString(projectPath.absoluteFilePath() + QLatin1Char('/') + qmlFileOrigin.baseName() + QLatin1String("/qml"))); #ifdef Q_OS_WIN const QString sourcePath = QDir::toNativeSeparators(qmlFileOrigin.canonicalPath() + QLatin1String("/*")); const QString targetPath = QDir::toNativeSeparators(qmlTargetPath.absoluteFilePath() + QLatin1Char('/')); QProcess xcopy; QStringList parameters; parameters << QLatin1String("/E") << sourcePath << targetPath; xcopy.start(QLatin1String("xcopy.exe"), parameters); if (!xcopy.waitForStarted() || !xcopy.waitForFinished()) { qDebug() << "Could not copy" << QDir::toNativeSeparators(sourcePath); continue; } #else // Q_OS_WIN // Implement me! #endif // Q_OS_WIN app.setMainQmlFile(qmlTargetPath.absoluteFilePath() + QLatin1Char('/') + qmlFileOrigin.fileName()); } app.setProjectName(reader.attributes().hasAttribute(attrib_projectName) ? reader.attributes().value(attrib_projectName).toString() : QFileInfo(app.mainQmlFile()).baseName()); if (reader.attributes().hasAttribute(attrib_screenOrientation)) { const QStringRef orientation = reader.attributes().value(attrib_screenOrientation); app.setOrientation(orientation == value_screenOrientationLockLandscape ? AbstractMobileApp::ScreenOrientationLockLandscape : orientation == value_screenOrientationLockPortrait ? AbstractMobileApp::ScreenOrientationLockPortrait : AbstractMobileApp::ScreenOrientationAuto); } if (reader.attributes().hasAttribute(attrib_networkAccess)) app.setNetworkEnabled( reader.attributes().value(attrib_networkAccess).toString() == QLatin1String("true")); if (!app.generateFiles(0)) qDebug() << "Unable to generate the files for" << app.projectName(); } break; default: break; } } return true; }
//-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- void RicNewScriptFeature::onActionTriggered(bool isChecked) { std::vector<RimCalcScript*> calcScripts = RicScriptFeatureImpl::selectedScripts(); std::vector<RimScriptCollection*> calcScriptCollections = RicScriptFeatureImpl::selectedScriptCollections(); RimCalcScript* calcScript = calcScripts.size() > 0 ? calcScripts[0] : NULL; RimScriptCollection* scriptColl = calcScriptCollections.size() > 0 ? calcScriptCollections[0] : NULL; QString fullPathNewScript; if (calcScript) { QFileInfo existingScriptFileInfo(calcScript->absolutePath()); fullPathNewScript = existingScriptFileInfo.absolutePath(); } else if (scriptColl) { fullPathNewScript = scriptColl->directory(); } else { return; } QString fullPathFilenameNewScript; fullPathFilenameNewScript = fullPathNewScript + "/untitled.m"; int num= 1; while (caf::Utils::fileExists(fullPathFilenameNewScript)) { fullPathFilenameNewScript = fullPathNewScript + "/untitled" + QString::number(num) + ".m"; num++; } bool ok; fullPathFilenameNewScript = QInputDialog::getText(nullptr, "Specify new script file", "File name", QLineEdit::Normal, fullPathFilenameNewScript, &ok, RiuTools::defaultDialogFlags()); if (ok && !fullPathFilenameNewScript.isEmpty()) { QFile file(fullPathFilenameNewScript); if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) { QMessageBox::warning(Riu3DMainWindowTools::mainWindowWidget(), "Script editor", "Failed to create file\n" + fullPathFilenameNewScript); return; } RicRefreshScriptsFeature::refreshScriptFolders(); if (calcScript) { Riu3DMainWindowTools::selectAsCurrentItem(calcScript); } RiaApplication* app = RiaApplication::instance(); QString scriptEditor = app->scriptEditorPath(); if (!scriptEditor.isEmpty()) { QStringList arguments; arguments << fullPathFilenameNewScript; QProcess* myProcess = new QProcess(this); myProcess->start(scriptEditor, arguments); if (!myProcess->waitForStarted(1000)) { QMessageBox::warning(Riu3DMainWindowTools::mainWindowWidget(), "Script editor", "Failed to start script editor executable\n" + scriptEditor); } } } }