DvcsJob::JobStatus GitRunner::remove(const KUrl::List &files) { if (files.empty()) return m_jobStatus = DvcsJob::JobCancelled; DvcsJob *job = new DvcsJob(); initJob(*job); *job << "rm"; QStringList stringFiles = files.toStringList(); while (!stringFiles.isEmpty()) { *job << m_lastRepoRoot->pathOrUrl() + '/' + stringFiles.takeAt(0); } startJob(*job); return m_jobStatus; }
bool QGenieWiFiProfileManagerController::moveDownProfile(int index) { bool bret = false; if((index >= 0) && (index < (m_profileList.count() - 1))) { QStringList tmpList = m_profileList; tmpList.insert(index,tmpList.takeAt(index + 1)); bret = diagnose_inf->SetWlanProfileList(m_curInterface,tmpList); if(bret) { m_profileList.insert(index,m_profileList.takeAt(index + 1)); } } return bret; }
void GitRunner::add(const KUrl::List &localLocations) { if (localLocations.empty()) { return; } QStringList command; command << "add"; // Adding files to the runner. QStringList stringFiles = localLocations.toStringList(); while (!stringFiles.isEmpty()) { command.append(m_lastRepoRoot->pathOrUrl() + '/' + stringFiles.takeAt(0)); } execSynchronously(command); }
DvcsJob::JobStatus GitRunner::add(const KUrl::List &localLocations) { if (localLocations.empty()) return m_jobStatus = DvcsJob::JobCancelled; DvcsJob *job = new DvcsJob(); initJob(*job); *job << "add"; // Adding files to the runner. QStringList stringFiles = localLocations.toStringList(); while (!stringFiles.isEmpty()) { *job << m_lastRepoRoot->pathOrUrl() + '/' + stringFiles.takeAt(0); } startJob(*job); return m_jobStatus; }
Node* LoadNodeFactory::getNode( const QString &tagContent, Parser *p ) const { QStringList expr = tagContent.split( QLatin1Char( ' ' ), QString::SkipEmptyParts ); if ( expr.size() <= 1 ) { throw Grantlee::Exception( TagSyntaxError, QString::fromLatin1( "%1 expects at least one argument" ).arg( expr.first() ) ); } expr.takeAt( 0 ); QListIterator<QString> i( expr ); while ( i.hasNext() ) { QString libName = i.next(); p->loadLib( libName ); } return new LoadNode( p ); }
void GitRunner::remove(const KUrl::List &files) { if (files.empty()) { return; } QStringList command; command << "rm "; QStringList stringFiles = files.toStringList(); while (!stringFiles.isEmpty()) { command.append(m_lastRepoRoot->pathOrUrl() + '/' + stringFiles.takeAt(0)); } KJob *job = initJob(command); connect(job, SIGNAL(result(KJob*)), this, SLOT(handleRemove(KJob*))); job->start(); }
void ExtCommandsHandler::run() { while (1) { QStringList args; if (!readRequest(&args)) { qWarning ("failed to read request from shell extension: %s", formatErrorMessage().c_str()); break; } QString cmd = args.takeAt(0); QString resp; if (cmd == "list-repos") { resp = handleListRepos(args); } else if (cmd == "get-share-link") { handleGenShareLink(args, false); } else if (cmd == "get-internal-link") { handleGenShareLink(args, true); } else if (cmd == "get-file-status") { resp = handleGetFileStatus(args); } else if (cmd == "lock-file") { handleLockFile(args, true); } else if (cmd == "unlock-file") { handleLockFile(args, false); } else if (cmd == "private-share-to-group") { handlePrivateShare(args, true); } else if (cmd == "private-share-to-user") { handlePrivateShare(args, false); } else { qWarning ("[ext] unknown request command: %s", cmd.toUtf8().data()); } if (!sendResponse(resp)) { qWarning ("failed to write response to shell extension: %s", formatErrorMessage().c_str()); break; } } qDebug ("An extension client is disconnected: GLE=%lu\n", GetLastError()); DisconnectNamedPipe(pipe_); CloseHandle(pipe_); }
Node* IfChangedNodeFactory::getNode( const QString &tagContent, Parser *p ) const { QStringList expr = tagContent.split( QLatin1Char( ' ' ), QString::SkipEmptyParts ); expr.takeAt( 0 ); IfChangedNode *n = new IfChangedNode( getFilterExpressionList( expr, p ), p ); NodeList trueList = p->parse( n, QStringList() << QLatin1String( "else" ) << QLatin1String( "endifchanged" ) ); n->setTrueList( trueList ); NodeList falseList; if ( p->takeNextToken().content.trimmed() == QLatin1String( "else" ) ) { falseList = p->parse( n, QLatin1String( "endifchanged" ) ); n->setFalseList( falseList ); p->removeNextToken(); } return n; }
Grantlee::Node* RangeNodeFactory::getNode( const QString& tagContent, Parser* p ) const { QStringList expr = smartSplit( tagContent ); expr.takeAt( 0 ); int numArgs = expr.size(); if ( numArgs != 1 ) { if ( numArgs <= 2 ) { throw Grantlee::Exception( TagSyntaxError, QStringLiteral( "'range' tag requires at least three arguments" ) ); } if ( expr.at( numArgs - 2 ) != QStringLiteral( "as" ) ) { throw Grantlee::Exception( TagSyntaxError, QStringLiteral( "Invalid arguments to 'range' tag" ) ); } } const QString name = ( numArgs > 2 ) ? expr.at( numArgs - 1 ) : QString(); if ( numArgs > 2 ) numArgs -= 2; RangeNode *n = 0; switch ( numArgs ) { case 1: n = new RangeNode( name, FilterExpression( QChar::fromLatin1( '0' ), p ), FilterExpression( expr.first(), p ), p ); break; case 2: n = new RangeNode( name, FilterExpression( expr.first(), p ), FilterExpression( expr.at( 1 ), p ), p ); break; case 3: n = new RangeNode( name, FilterExpression( expr.first(), p ), FilterExpression( expr.at( 1 ), p ), FilterExpression( expr.at( 2 ), p ), p ); break; default: return 0; } NodeList list = p->parse( n, QStringLiteral( "endrange" ) ); p->removeNextToken(); n->setNodeList( list ); return n; }
void MythUIImage::FindRandomImage(void) { QDir imageDir(m_imageDirectory); if (!imageDir.exists()) { QString themeDir = GetMythUI()->GetThemeDir() + '/'; imageDir = themeDir + m_imageDirectory; } QStringList imageTypes; QList< QByteArray > exts = QImageReader::supportedImageFormats(); QList< QByteArray >::Iterator it = exts.begin(); for (; it != exts.end(); ++it) { imageTypes.append(QString("*.").append(*it)); } imageDir.setNameFilters(imageTypes); QStringList imageList = imageDir.entryList(); QString randFile; if (imageList.size()) { // try to find a different image do { randFile = QString("%1%2").arg(m_imageDirectory) .arg(imageList.takeAt(random() % imageList.size())); } while (imageList.size() > 1 && randFile == m_OrigFilename); } m_OrigFilename = m_imageProperties.filename = randFile; }
void TermWidgetHolder::loadSession() { bool ok; QString name = QInputDialog::getItem(this, tr("Load Session"), tr("List of saved sessions:"), Properties::Instance()->sessions.keys(), 0, false, &ok); if (!ok || name.isEmpty()) return; #if 0 foreach (QWidget * w, findChildren<QWidget*>()) { if (w) { delete w; w = 0; } } qDebug() << "load" << name << QString(Properties::Instance()->sessions[name]); QStringList splitters = QString(Properties::Instance()->sessions[name]).split("|", QString::SkipEmptyParts); foreach (QString splitter, splitters) { QStringList components = splitter.split(","); qDebug() << "comp" << components; // orientation Qt::Orientation orientation; if (components.size() > 0) orientation = components.takeAt(0).toInt(); // sizes QList<int> sizes; QList<TermWidget*> widgets; foreach (QString s, components) { sizes << s.toInt(); widgets << newTerm(); }
void SourceEntryPrivate::parseData(const QString &data) { if (data.isEmpty()) return; QString tData = data.simplified(); // Check for nonvalid input if (tData.isEmpty() || tData == QChar('#')) { isValid = false; return; } QStringList types; types << QLatin1String("rpm") << QLatin1String("rpm-src") << QLatin1String("deb") << QLatin1String("deb-src"); // Check source enable state if (tData.at(0) == '#') { isEnabled = false; } // Handle multiple comment characters (hey, it happens!) while (tData.at(0) == '#') { // Remove starting '#' from tData tData = tData.remove(0, 1); tData = tData.trimmed(); } // Find any #'s past the start (these are comments) int idx = tData.indexOf('#'); if (idx > 0) { // Save the comment, then remove from tData comment = tData.right(tData.size() - idx - 1); tData.remove(idx, tData.size() - idx + 1); } QStringList pieces = tData.split(' '); if (pieces.size() < 3) { // Invalid source entry isValid = false; return; } // Parse type type = pieces.at(0); if (!types.contains(type)) { isValid = false; return; } // Parse architecture if (pieces.at(1).trimmed().at(0) == '[') { QStringList options = pieces.takeAt(1).remove('[').remove(']').split(';'); for (const QString &option : options) { QStringList parts = option.split('='); if (parts.size() != 2) { isValid = false; return; } QString key = parts.at(0); QString value = parts.at(1); if (key != QLatin1String("arch")) { isValid = false; return; } architectures = value.split(','); } } // Parse URI uri = pieces.at(1); if (uri.isEmpty()) { isValid = false; return; } // Parse distro and (optionally) components dist = pieces.at(2); if (pieces.size() > 3) { components = pieces.mid(3); } }
int main (int argc, char *argv[]) { QApplication app (argc, argv); QStringList args = app.arguments (); if (!args.isEmpty ()) args.pop_front (); // The command itself qputenv ("DESKTOP_STARTUP_ID", qgetenv ("STARTUP_ID_COPY")); // for startup notifications (set via rkward.desktop) qputenv ("STARTUP_ID_COPY", ""); // Parse arguments that need handling in the wrapper bool usage = false; QStringList debugger_args; QStringList file_args; bool reuse = false; bool warn_external = true; QString r_exe_arg; int debug_level = 2; for (int i=0; i < args.size (); ++i) { if (args[i] == "--debugger") { args.removeAt (i); while (i < args.size ()) { QString arg = args.takeAt (i); if (arg == "--") break; debugger_args.append (arg); } if (debugger_args.isEmpty ()) usage = true; } else if (args[i] == "--r-executable") { if ((i+1) < args.size ()) { r_exe_arg = args.takeAt (i + 1); } else usage = true; args.removeAt (i); --i; } else if (args[i] == "--debug-level") { if ((i+1) < args.size ()) { debug_level = args[i+1].toInt (); } } else if (args[i] == "--reuse") { reuse = true; } else if (args[i] == "--nowarn-external") { warn_external = false; } else if (args[i].startsWith ("--")) { // all RKWard and KDE options (other than --reuse) are of the for --option <value>. So skip over the <value> i++; } else { QUrl url (args[i]); if (url.isRelative ()) { file_args.append (QDir::current ().absoluteFilePath (url.toLocalFile ())); } else { file_args.append (args[i]); } } } if (reuse) { if (!QDBusConnection::sessionBus ().isConnected ()) { if (debug_level > 2) qDebug ("Could not connect to session dbus"); } else { QDBusInterface iface (RKDBUS_SERVICENAME, "/", "", QDBusConnection::sessionBus ()); if (iface.isValid ()) { QDBusReply<void> reply = iface.call ("openAnyUrl", file_args, warn_external); if (!reply.isValid ()) { if (debug_level > 2) qDebug ("Error while placing dbus call: %s", qPrintable (reply.error ().message ())); return 1; } return 0; } } } // MacOS may need some path adjustments, first #ifdef Q_WS_MAC QString oldpath = qgetenv ("PATH"); if (!oldpath.contains (INSTALL_PATH)) { //ensure that PATH is set to include what we deliver with the bundle qputenv ("PATH", QString ("%1/bin:%1/sbin:%2").arg (INSTALL_PATH).arg (oldpath).toLocal8Bit ()); if (debug_level > 3) qDebug ("Adjusting system path to %s", qPrintable (qgetenv ("PATH"))); } // ensure that RKWard finds its own packages qputenv ("R_LIBS", R_LIBS); QProcess::execute ("launchctl", QStringList () << "load" << "-w" << INSTALL_PATH "/Library/LaunchAgents/org.freedesktop.dbus-session.plist"); #endif // Locate KDE and RKWard installations QString kde4_config_exe = findExeAtPath ("kde4-config", QDir::currentPath ()); if (kde4_config_exe.isNull ()) kde4_config_exe = findExeAtPath ("kde4-config", app.applicationDirPath ()); if (kde4_config_exe.isNull ()) kde4_config_exe = findExeAtPath ("kde4-config", QDir (app.applicationDirPath ()).filePath ("KDE/bin")); if (kde4_config_exe.isNull ()) { #ifdef Q_WS_WIN QStringList syspath = QString (qgetenv ("PATH")).split (';'); #else QStringList syspath = QString (qgetenv ("PATH")).split (':'); #endif for (int i = 0; i < syspath.size (); ++i) { kde4_config_exe = findExeAtPath ("kde4-config", syspath[i]); if (!kde4_config_exe.isNull ()) break; } } if (kde4_config_exe.isNull ()) { QMessageBox::critical (0, "Could not find KDE installation", "The KDE installation could not be found (kde4-config). When moving / copying RKWard, make sure to copy the whole application folder, or create a shorcut / link, instead."); exit (1); } QDir kde_dir (QFileInfo (kde4_config_exe).absolutePath ()); kde_dir.makeAbsolute (); QString kde_dir_safe_path = quoteCommand (kde_dir.path ()); #ifdef Q_WS_WIN QString kdeinit4_exe = findExeAtPath ("kdeinit4", kde_dir.path ()); qputenv ("PATH", QString (kde_dir_safe_path + ';' + qgetenv ("PATH")).toLocal8Bit ()); if (debug_level > 3) qDebug ("Adding %s to the system path", qPrintable (kde_dir_safe_path)); #endif // important if RKWard is not in KDEPREFIX/bin but e.g. KDEPREFIX/lib/libexec qputenv ("RKWARD_ENSURE_PREFIX", kde_dir_safe_path.toLocal8Bit ()); if (debug_level > 3) qDebug ("Setting environment variable RKWARD_ENSURE_PREFIX=%s", qPrintable (kde_dir_safe_path)); QString rkward_frontend_exe = findRKWardAtPath (app.applicationDirPath ()); // this is for running directly from a build tree #ifdef Q_WS_MAC if (rkward_frontend_exe.isNull ()) rkward_frontend_exe = findRKWardAtPath (app.applicationDirPath () + "/rkward.frontend.app/Contents/MacOS"); // this is for running directly from a build tree #endif if (rkward_frontend_exe.isNull ()) rkward_frontend_exe = findRKWardAtPath (RKWARD_FRONTEND_LOCATION); if (rkward_frontend_exe.isNull ()) rkward_frontend_exe = findRKWardAtPath (kde_dir.absoluteFilePath ("bin")); if (rkward_frontend_exe.isNull ()) rkward_frontend_exe = findRKWardAtPath (kde_dir.absoluteFilePath ("../lib/libexec")); if (rkward_frontend_exe.isNull ()) { QMessageBox::critical (0, "RKWard frontend binary missing", "RKWard frontend binary could not be found. When moving / copying RKWard, make sure to copy the whole application folder, or create a shorcut / link, instead."); exit (1); } if (usage) { QProcess::execute (rkward_frontend_exe, QStringList ("--help")); exit (1); } #ifdef Q_WS_WIN // Explicit initialization of KDE, in case Windows 7 asks for admin privileges if (kdeinit4_exe.isNull ()) { kdeinit4_exe = findExeAtPath ("kdeinit4", QFileInfo (rkward_frontend_exe).absolutePath ()); } if (!kdeinit4_exe.isNull ()) QProcess::execute (kdeinit4_exe, QStringList ()); #endif // Look for R: //- command line parameter //- Specified in cfg file next to rkward executable //- compile-time default QString r_exe = r_exe_arg; if (!r_exe.isNull ()) { if (!QFileInfo (r_exe).isExecutable ()) { QMessageBox::critical (0, "Specified R executable does not exist", QString ("The R executable specified on the command line (%1) does not exist or is not executable.").arg (r_exe)); exit (1); } if (debug_level > 3) qDebug ("Using R specified on command line"); } else { QFileInfo frontend_info (rkward_frontend_exe); QDir frontend_path = frontend_info.absoluteDir (); QFileInfo rkward_ini_file (frontend_path.absoluteFilePath ("rkward.ini")); if (rkward_ini_file.isReadable ()) { QSettings rkward_ini (rkward_ini_file.absoluteFilePath (), QSettings::IniFormat); r_exe = rkward_ini.value ("R executable").toString (); if (!r_exe.isNull ()) { if (QDir::isRelativePath (r_exe)) { r_exe = frontend_path.absoluteFilePath (r_exe); } if (!QFileInfo (r_exe).isExecutable ()) { QMessageBox::critical (0, "Specified R executable does not exist", QString ("The R executable specified in the rkward.ini file (%1) does not exist or is not executable.").arg (rkward_ini_file.absoluteFilePath ())); exit (1); } } if (debug_level > 3) qDebug ("Using R as configured in config file %s", qPrintable (rkward_ini_file.absoluteFilePath ())); } if (r_exe.isNull ()) { r_exe = R_EXECUTABLE; if (!QFileInfo (r_exe).isExecutable ()) { QMessageBox::critical (0, "Specified R executable does not exist", QString ("The R executable specified at compile time (%1) does not exist or is not executable. Probably the installation of R has moved. You can use the command line parameter '--R', or supply an rkward.ini file to specify the new location.").arg (r_exe)); exit (1); } if (debug_level > 3) qDebug ("Using R as configured at compile time"); } } qputenv ("R_BINARY", r_exe.toLocal8Bit ()); QStringList call_args ("CMD"); call_args.append (debugger_args); call_args.append (quoteCommand (rkward_frontend_exe)); if (!args.isEmpty ()) { // NOTE: QProcess quotes its arguments, *but* properly passing all spaces and quotes through the R CMD wrapper, seems near(?) impossible on Windows. Instead, we use percent encoding, internally. for (int i = 0; i < args.size (); ++i) { call_args.append (QString::fromUtf8 (QUrl::toPercentEncoding (args[i], QByteArray (), " \""))); } } if (debug_level > 2) qDebug ("Starting frontend: %s %s", qPrintable (r_exe), qPrintable (call_args.join (" "))); InteractiveProcess proc; #ifdef Q_WS_WIN if (debugger_args.isEmpty ()) { // start _without_ opening an annoying console window QTemporaryFile *vbsf = new QTemporaryFile (QDir::tempPath () + "/rkwardlaunchXXXXXX.vbs"); vbsf->setAutoRemove (false); if (vbsf->open ()) { QTextStream vbs (vbsf); vbs << "Dim WinScriptHost\r\nSet WinScriptHost = CreateObject(\"WScript.Shell\")\r\nWinScriptHost.Run \"" << quoteCommand (r_exe); for (int i = 0; i < call_args.length (); ++i) { vbs << " " << call_args[i]; } vbs << "\", 0\r\nSet WomScriptHost = Nothing\r\n"; vbsf->close (); QString filename = vbsf->fileName (); delete (vbsf); // somehow, if creating vbsf on the stack, we cannot launch it, because "file is in use by another process", despite we have closed it. proc.start ("WScript.exe", QStringList (filename)); bool ok = proc.waitForFinished (-1); if (proc.exitCode () || !ok) { QMessageBox::critical (0, "Error starting RKWard", QString ("Starting RKWard failed with error \"%1\"").arg (proc.errorString ())); } QFile (filename).remove (); return (0); } } // if that did not work or not on windows: #endif proc.setProcessChannelMode (QProcess::ForwardedChannels); proc.start (quoteCommand (r_exe), call_args); bool ok = proc.waitForFinished (-1); if (proc.exitCode () || !ok) { QMessageBox::critical (0, "Error starting RKWard", QString ("Starting RKWard failed with error \"%1\"").arg (proc.errorString ())); } return (0); }
/*! Executes the command described in \a arguments, in the environment inherited from the parent process, with the \a additionalEnv settings applied. \a removeEnv removes the specified environment variables from the environment of the executed process. Returns the exit value of the process, or -1 if the command could not be executed. This function uses _(w)spawnvpe to spawn a process by searching through the PATH environment variable. */ int Environment::execute(QStringList arguments, const QStringList &additionalEnv, const QStringList &removeEnv) { #ifdef CONFIGURE_DEBUG_EXECUTE qDebug() << "About to Execute: " << arguments; qDebug() << " " << QDir::currentPath(); qDebug() << " " << additionalEnv; qDebug() << " " << removeEnv; #endif // Create the full environment from the current environment and // the additionalEnv strings, then remove all variables defined // in removeEnv QMap<QString, QString> fullEnvMap; LPWSTR envStrings = GetEnvironmentStrings(); if (envStrings) { int strLen = 0; for (LPWSTR envString = envStrings; *(envString); envString += strLen + 1) { strLen = wcslen(envString); QString str = QString((const QChar*)envString, strLen); if (!str.startsWith("=")) { // These are added by the system int sepIndex = str.indexOf('='); fullEnvMap.insert(str.left(sepIndex).toUpper(), str.mid(sepIndex +1)); } } } FreeEnvironmentStrings(envStrings); // Add additionalEnv variables for (int i = 0; i < additionalEnv.count(); ++i) { const QString &str = additionalEnv.at(i); int sepIndex = str.indexOf('='); fullEnvMap.insert(str.left(sepIndex).toUpper(), str.mid(sepIndex +1)); } // Remove removeEnv variables for (int j = 0; j < removeEnv.count(); ++j) fullEnvMap.remove(removeEnv.at(j).toUpper()); // Add all variables to a QStringList QStringList fullEnv; QMapIterator<QString, QString> it(fullEnvMap); while (it.hasNext()) { it.next(); fullEnv += QString(it.key() + "=" + it.value()); } // ---------------------------- QString program = arguments.takeAt(0); QString args = qt_create_commandline(program, arguments); QByteArray envlist = qt_create_environment(fullEnv); DWORD exitCode = -1; PROCESS_INFORMATION procInfo; memset(&procInfo, 0, sizeof(procInfo)); STARTUPINFO startInfo; memset(&startInfo, 0, sizeof(startInfo)); startInfo.cb = sizeof(startInfo); bool couldExecute = CreateProcess(0, (wchar_t*)args.utf16(), 0, 0, true, CREATE_UNICODE_ENVIRONMENT, envlist.isEmpty() ? 0 : envlist.data(), 0, &startInfo, &procInfo); if (couldExecute) { WaitForSingleObject(procInfo.hProcess, INFINITE); GetExitCodeProcess(procInfo.hProcess, &exitCode); CloseHandle(procInfo.hThread); CloseHandle(procInfo.hProcess); } if (exitCode == -1) { switch(GetLastError()) { case E2BIG: cerr << "execute: Argument list exceeds 1024 bytes" << endl; foreach(QString arg, arguments) cerr << " (" << arg.toLocal8Bit().constData() << ")" << endl; break; case ENOENT: cerr << "execute: File or path is not found (" << program.toLocal8Bit().constData() << ")" << endl; break; case ENOEXEC: cerr << "execute: Specified file is not executable or has invalid executable-file format (" << program.toLocal8Bit().constData() << ")" << endl; break; case ENOMEM: cerr << "execute: Not enough memory is available to execute new process." << endl; break; default: cerr << "execute: Unknown error" << endl; foreach(QString arg, arguments) cerr << " (" << arg.toLocal8Bit().constData() << ")" << endl; break; } } return exitCode; }
void PropertyEditorModel::setModelIndexes(const QModelIndex &logicalModelIndex , const QModelIndex &graphicalModelIndex) { beginResetModel(); mField.reset(new Field()); endResetModel(); mTargetLogicalObject = logicalModelIndex; mTargetGraphicalObject = graphicalModelIndex; if (!isValid()) { return; } const Id logicalId = mTargetLogicalObject.data(roles::idRole).value<Id>(); const QString dynamicProperties = dynamic_cast<models::details::LogicalModel *>(mTargetLogicalModel)-> logicalModelAssistApi().logicalRepoApi().stringProperty(logicalId, "dynamicProperties"); if (logicalModelIndex != QModelIndex()) { const QStringList logicalProperties = mEditorManagerInterface.propertyNames(logicalId.type()); int role = roles::customPropertiesBeginRole; QStringList cloneWithRoles; QStringList cloneWithPure; for (const QString &prop : logicalProperties) { if (prop.contains("!")) { cloneWithRoles.append(prop); } else { cloneWithPure.append(prop); } } int i = 0; role = roles::customPropertiesBeginRole; while (cloneWithRoles.size() > 0) { const QString roleName = cloneWithRoles.takeAt(0); const int first = roleName.indexOf("!"); const QString beginPartName = roleName.mid(0, first); mField->appendChild(new Field(beginPartName)); auto parent = mField->child(i); QString endPartName = roleName.mid(first + 1); mField->appendChild( new Field( endPartName , logicalAttribute , role , parent , mTargetLogicalObject , mTargetGraphicalObject) ); ++i; ++role; int j = 0; while (j < cloneWithRoles.size()) { if (cloneWithRoles.at(j).mid(0, first) == beginPartName) { QString roleName = cloneWithRoles.takeAt(j); roleName = roleName.mid(first + 1); mField->appendChild( new Field( roleName , logicalAttribute , role , parent , mTargetLogicalObject , mTargetGraphicalObject) ); ++i; ++role; j = 0; } else { ++j; } } ++i; } while (cloneWithPure.size() > 0) { QString roleName = cloneWithPure.takeAt(0); mField->appendChild( new Field( roleName , logicalAttribute , role , nullptr , mTargetLogicalObject , mTargetGraphicalObject) ); ++i; ++role; } if (!dynamicProperties.isEmpty()) { QDomDocument dynamProperties; dynamProperties.setContent(dynamicProperties); for (QDomElement element = dynamProperties.firstChildElement("properties").firstChildElement("property") ; !element.isNull() ; element = element.nextSiblingElement("property")) { mField->appendChild( new Field( element.attribute("displayedName") , logicalAttribute , role , nullptr , mTargetLogicalObject , mTargetGraphicalObject)); ++role; } } /* * Uncomment to display block Ids in a property editor * mField->appendChild( new Field( "logicalId" , logicalAttribute , roles::idRole , nullptr , mTargetLogicalObject , mTargetGraphicalObject ) ); mField->appendChild( new Field( "graphicalId" , graphicalAttribute , roles::idRole , nullptr , mTargetLogicalObject , mTargetGraphicalObject ) ); /**/ } beginResetModel(); endResetModel(); }
void ProtocolDataTransfer::sendDir() { emit sigListStart(); totalBytes = 0; QStringList fileList = DataAccess::GetFileList(m_dirName, &totalBytes); if (m_item) { emit sigListReady(fileList); m_lock.lock(); m_waitCondition.wait(&m_lock); m_lock.unlock(); } if (m_CtrlID != DoStart) { return; } QFileInfo finfo(m_dirName); QString const& headkey = fileList[0]; QStringList headkeys = ParseFileInfoString(headkey); if (headkeys.size() < 3) { m_CtrlID = DoError; sock_.close(); acceptor_.close(); emit sigError(tr("Error occurred while parsing file information: %1.").arg(headkey)); return; } headkeys[2] = finfo.fileName(); fileList[0] = headkeys.join("$"); QString const& fstr = fileList.join("/*/"); std::string bArray = fstr.toUtf8().data(); emit sigStart(); // list int tmp = 0; int siz = bArray.length() + 1; tmp = sock_.send_n(&siz, sizeof(siz)); if (tmp != sizeof(siz)) { sock_.close(); emit sigError(tr("Error occurred while sending file list size.")); return; } tmp = sock_.send_n(bArray.c_str(), siz); if (tmp != siz) { sock_.close(); emit sigError(tr("Error occurred while sending file list.")); return; } fileList.removeAt(0); // files char buf[PayloadSize]; while (m_CtrlID == DoStart) { if (fileList.isEmpty()) { m_CtrlID = DoError; sock_.close(); emit sigError(tr("File list became empty while sending.")); return; } QString const& key = fileList.takeAt(0); QStringList keys = ParseFileInfoString(key); if (keys.size() < 3) { m_CtrlID = DoError; sock_.close(); acceptor_.close(); emit sigError(tr("Error occurred while parsing file information: %1.").arg(key)); return; } if (keys[0] == "DIR") { if (updateDirFileItemInfo) { emit sigDirFileTransOK(0, keys[2]); } continue; } else if (keys[0] == "FILE") { quint64 bytesSentOfFile = 0; quint64 fsize = keys[1].toULongLong(); QString const& fname = m_dirName + keys[2]; QFile file(fname); if (!file.open(QIODevice::ReadOnly)) { m_CtrlID = DoError; sock_.close(); emit sigDirFileTransError(tr("Unable to read the file %1: %2") .arg(fname).arg(file.errorString()), keys[2]); return; } if (updateDirFileItemInfo) { emit sigDirFileTransStart(keys[2]); } m_currentFileName = keys[2]; m_currentFilePos = 0; tmp = file.read(buf, PayloadSize); tmp = sock_.send(buf, tmp); bytesSentOfFile += tmp; while (bytesSentOfFile < fsize && m_CtrlID == DoStart) { tmp = file.read(buf, PayloadSize); tmp = sock_.send(buf, tmp); bytesSentOfFile += tmp; m_currentFilePos = bytesSentOfFile; } file.close(); m_currentFilePos = bytesSentOfFile; bytesTransfered += bytesSentOfFile; if (bytesSentOfFile < fsize && m_CtrlID == DoCancel) { goto callend; } if (updateDirFileItemInfo) { emit sigDirFileTransOK(fsize, keys[2]); } if (bytesTransfered == totalBytes) { m_CtrlID = DoFinish; goto callend; } } } callend: sock_.close(); acceptor_.close(); if (m_CtrlID == DoFinish) { emit sigComplete(); } else if (m_CtrlID == DoCancel) { emit sigError(tr("Canceled")); } else { emit sigError(tr("Error")); } }
void ResourceManager::displayLanguages() { // Download details.json DownloadUtils js(this); js.setTarget(baseAddr() + "languages/details.json"); js.download(); QByteArray json = js.returnData(); qDebug() << json; // parse the json file QJsonParseError err; QJsonDocument result = QJsonDocument::fromJson(json, &err); if (err.error != QJsonParseError::NoError || !result.isObject()) { qDebug("An error occurred during parsing"); return; } int rowCount = result.object().keys().size(); rowCount -= 2; //version and type languagesTable->setRowCount(rowCount); int row = 0; int col = 0; #if (!defined (_MSCVER) && !defined (_MSC_VER)) QPushButton* updateButtons[rowCount]; #else // MSVC does not support VLA. Replace with std::vector. If profiling determines that the // heap allocation is slow, an optimization might be used. std::vector<QPushButton*> updateButtons(rowCount); #endif QPushButton* temp; languagesTable->verticalHeader()->show(); // move current language to first row QStringList langs = result.object().keys(); QString lang = mscore->getLocaleISOCode(); int index = langs.indexOf(lang); if (index < 0 && lang.size() > 2) { lang = lang.left(2); index = langs.indexOf(lang); } if (index >= 0) { QString l = langs.takeAt(index); langs.prepend(l); } for (QString key : langs) { if (!result.object().value(key).isObject()) continue; QJsonObject value = result.object().value(key).toObject(); col = 0; QString test = value.value("file_name").toString(); if(test.length() == 0) continue; QString filename = value.value("file_name").toString(); QString name = value.value("name").toString(); QString fileSize = value.value("file_size").toString(); QString hashValue = value.value("hash").toString(); languagesTable->setItem(row, col++, new QTableWidgetItem(name)); languagesTable->setItem(row, col++, new QTableWidgetItem(filename)); languagesTable->setItem(row, col++, new QTableWidgetItem(tr("%1 kB").arg(fileSize))); updateButtons[row] = new QPushButton(tr("Update")); temp = updateButtons[row]; languageButtonMap[temp] = "languages/" + filename; languageButtonHashMap[temp] = hashValue; languagesTable->setIndexWidget(languagesTable->model()->index(row, col++), temp); // get hash mscore and instruments QJsonObject mscoreObject = value.value("mscore").toObject(); QString hashMscore = mscoreObject.value("hash").toString(); QString filenameMscore = mscoreObject.value("file_name").toString(); bool verifyMScore = verifyLanguageFile(filenameMscore, hashMscore); QJsonObject instrumentsObject = value.value("instruments").toObject(); QString hashInstruments = instrumentsObject.value("hash").toString(); QString filenameInstruments = instrumentsObject.value("file_name").toString(); bool verifyInstruments = verifyLanguageFile(filenameInstruments, hashInstruments); QJsonObject toursObject = value.value("tours").toObject(); QString hashTours = toursObject.value("hash").toString(); QString filenameTours = toursObject.value("file_name").toString(); bool verifyTours = verifyLanguageFile(filenameTours, hashTours); if (verifyMScore && verifyInstruments && verifyTours) { // compare local file with distant hash temp->setText(tr("Updated")); temp->setDisabled(1); } else { connect(temp, SIGNAL(clicked()), this, SLOT(downloadLanguage())); } row++; } }
void ResourceManager::displayLanguages() { // Download details.json DownloadUtils *js = new DownloadUtils(this); js->setTarget(baseAddr + "languages/details.json"); js->download(); QByteArray json = js->returnData(); // parse the json file QJsonParseError err; QJsonDocument result = QJsonDocument::fromJson(json, &err); if (err.error != QJsonParseError::NoError || !result.isObject()) { qDebug("An error occured during parsing"); return; } int rowCount = result.object().keys().size(); rowCount -= 2; //version and type languagesTable->setRowCount(rowCount); int row = 0; int col = 0; QPushButton* updateButtons[rowCount]; QPushButton* temp; languagesTable->verticalHeader()->show(); // move current language to first row QStringList languages = result.object().keys(); QString lang = mscore->getLocaleISOCode(); int index = languages.indexOf(lang); if (index < 0 && lang.size() > 2) { lang = lang.left(2); index = languages.indexOf(lang); } if (index >= 0) { QString l = languages.takeAt(index); languages.prepend(l); } for (QString key : languages) { if (!result.object().value(key).isObject()) continue; QJsonObject value = result.object().value(key).toObject(); col = 0; QString test = value.value("file_name").toString(); if(test.length() == 0) continue; QString filename = value.value("file_name").toString(); QString name = value.value("name").toString(); QString fileSize = value.value("file_size").toString(); QString hashValue = value.value("hash").toString(); languagesTable->setItem(row, col++, new QTableWidgetItem(name)); languagesTable->setItem(row, col++, new QTableWidgetItem(filename)); languagesTable->setItem(row, col++, new QTableWidgetItem(tr("%1 KB").arg(fileSize))); updateButtons[row] = new QPushButton(tr("Update")); temp = updateButtons[row]; buttonMap[temp] = "languages/" + filename; buttonHashMap[temp] = hashValue; languagesTable->setIndexWidget(languagesTable->model()->index(row, col++), temp); // get hash mscore and instruments QJsonObject mscoreObject = value.value("mscore").toObject(); QString hashMscore = mscoreObject.value("hash").toString(); QString filenameMscore = mscoreObject.value("file_name").toString(); bool verifyMScore = verifyLanguageFile(filenameMscore, hashMscore); QJsonObject instrumentsObject = value.value("instruments").toObject(); QString hashInstruments = instrumentsObject.value("hash").toString(); QString filenameInstruments = instrumentsObject.value("file_name").toString(); bool verifyInstruments = verifyLanguageFile(filenameInstruments, hashInstruments); if (verifyMScore && verifyInstruments) { // compare local file with distant hash temp->setText(tr("No update")); temp->setDisabled(1); } else { connect(temp, SIGNAL(clicked()), this, SLOT(download())); } row++; } }
/** * \copydoc MythUIType::ParseElement() */ bool MythUIImage::ParseElement( const QString &filename, QDomElement &element, bool showWarnings) { QWriteLocker updateLocker(&d->m_UpdateLock); if (element.tagName() == "filename") { m_OrigFilename = m_Filename = getFirstText(element); if (m_Filename.endsWith('/')) { QDir imageDir(m_Filename); if (!imageDir.exists()) { QString themeDir = GetMythUI()->GetThemeDir() + '/'; imageDir = themeDir + m_Filename; } QStringList imageTypes; QList< QByteArray > exts = QImageReader::supportedImageFormats(); QList< QByteArray >::Iterator it = exts.begin(); for (;it != exts.end();++it) { imageTypes.append( QString("*.").append(*it) ); } imageDir.setNameFilters(imageTypes); QStringList imageList = imageDir.entryList(); srand(time(NULL)); QString randFile; if (imageList.size()) randFile = QString("%1%2").arg(m_Filename) .arg(imageList.takeAt(rand() % imageList.size())); m_OrigFilename = m_Filename = randFile; } } else if (element.tagName() == "filepattern") { m_OrigFilename = m_Filename = getFirstText(element); QString tmp = element.attribute("low"); if (!tmp.isEmpty()) m_LowNum = tmp.toInt(); tmp = element.attribute("high"); if (!tmp.isEmpty()) m_HighNum = tmp.toInt(); tmp = element.attribute("cycle", "start"); if (tmp == "reverse") m_animationCycle = kCycleReverse; } else if (element.tagName() == "area") { SetArea(parseRect(element)); m_ForceSize = m_Area.size(); } else if (element.tagName() == "preserveaspect") m_preserveAspect = parseBool(element); else if (element.tagName() == "crop") m_cropRect = parseRect(element); else if (element.tagName() == "delay") { QString value = getFirstText(element); if (value.contains(",")) { QVector<int> delays; QStringList tokens = value.split(","); QStringList::iterator it = tokens.begin(); for (; it != tokens.end(); ++it) { if ((*it).isEmpty()) { if (delays.size()) delays.append(delays[delays.size()-1]); else delays.append(0); // Default 0ms delay before first image } else { delays.append((*it).toInt()); } } if (delays.size()) { m_Delay = delays[0]; SetDelays(delays); } } else { m_Delay = value.toInt(); } } else if (element.tagName() == "reflection") { m_isReflected = true; QString tmp = element.attribute("axis"); if (!tmp.isEmpty()) { if (tmp.toLower() == "horizontal") m_reflectAxis = ReflectHorizontal; else m_reflectAxis = ReflectVertical; } tmp = element.attribute("shear"); if (!tmp.isEmpty()) m_reflectShear = tmp.toInt(); tmp = element.attribute("scale"); if (!tmp.isEmpty()) m_reflectScale = tmp.toInt(); tmp = element.attribute("length"); if (!tmp.isEmpty()) m_reflectLength = tmp.toInt(); tmp = element.attribute("spacing"); if (!tmp.isEmpty()) m_reflectSpacing = tmp.toInt(); } else if (element.tagName() == "mask") { QString maskfile = getFirstText(element); if (m_maskImage) { m_maskImage->DownRef(); m_maskImage = NULL; } m_maskImage = GetPainter()->GetFormatImage(); m_maskImage->UpRef(); if (m_maskImage->Load(maskfile)) m_isMasked = true; else { m_maskImage->DownRef(); m_maskImage = NULL; m_isMasked = false; } } else if (element.tagName() == "grayscale" || element.tagName() == "greyscale") { m_isGreyscale = parseBool(element); } else { return MythUIType::ParseElement(filename, element, showWarnings); } m_NeedLoad = true; if (m_Parent && m_Parent->IsDeferredLoading(true)) m_NeedLoad = false; return true; }
void ProtocolDataTransfer::recvDir() { char buf[PayloadSize]; int tmp = 0; int siz = 0; emit sigListStart(); // list tmp = sock_.recv_n(&siz, sizeof(int)); if (tmp != sizeof(int)) { sock_.close(); emit sigError(tr("Error occurred while receiving file list size.")); return; } char* listBuf = new char[siz]; tmp = sock_.recv_n(listBuf, siz); if (tmp != siz) { sock_.close(); delete listBuf; emit sigError(tr("Error occurred while receiving file list.")); return; } QString const& strBuf = QString::fromUtf8(listBuf, siz); QStringList fileList = strBuf.split("/*/"); if (m_item) { emit sigListReady(fileList); m_lock.lock(); m_waitCondition.wait(&m_lock); m_lock.unlock(); } if (m_CtrlID != DoStart) { delete listBuf; return; } emit sigStart(); QString const& headkey = fileList.takeAt(0); QStringList const& headkeys = ParseFileInfoString(headkey); totalBytes = headkeys[1].toULongLong(); // files while (m_CtrlID == DoStart) { if (fileList.isEmpty()) { m_CtrlID = DoError; sock_.close(); delete listBuf; emit sigError(tr("File list became empty while receiving.")); return; } QString const& key = fileList.takeAt(0); QStringList keys = ParseFileInfoString(key); if (keys.size() < 3) { m_CtrlID = DoError; sock_.close(); acceptor_.close(); delete listBuf; emit sigError(tr("Error occurred while parsing file information: %1.").arg(key)); return; } QString saveName = m_dirName + keys[2]; if (keys[0] == "DIR") { QDir dir; dir.mkpath(saveName); if (updateDirFileItemInfo) { emit sigDirFileTransOK(0, keys[2]); } } else if (keys[0] == "FILE") { quint64 bytesRecvedOfFile = 0; quint64 fsize = keys[1].toULongLong(); QFile file(saveName); if (!file.open(QIODevice::WriteOnly)) { m_CtrlID = DoError; sock_.close(); acceptor_.close(); emit sigDirFileTransError(tr("Unable to save the file %1: %2") .arg(saveName).arg(file.errorString()), keys[2]); delete listBuf; return; } if (updateDirFileItemInfo) { emit sigDirFileTransStart(keys[2]); } m_currentFileName = keys[2]; m_currentFilePos = 0; tmp = sock_.recv_n(buf, (fsize)>PayloadSize?PayloadSize:fsize); file.write(buf, tmp); bytesRecvedOfFile += tmp; while (bytesRecvedOfFile < fsize && m_CtrlID == DoStart) { siz = (fsize-bytesRecvedOfFile)>PayloadSize?PayloadSize:(fsize-bytesRecvedOfFile); tmp = sock_.recv_n(buf, siz); file.write(buf, tmp); bytesRecvedOfFile += tmp; m_currentFilePos = bytesRecvedOfFile; } file.close(); m_currentFilePos = bytesRecvedOfFile; bytesTransfered += bytesRecvedOfFile; if (bytesRecvedOfFile < fsize && m_CtrlID == DoCancel) { file.remove(); goto callend; } if (updateDirFileItemInfo) { emit sigDirFileTransOK(fsize, keys[2]); } if (bytesTransfered == totalBytes) { m_CtrlID = DoFinish; goto callend; } } } callend: sock_.close(); acceptor_.close(); if (m_CtrlID == DoFinish) { emit sigComplete(); } else if (m_CtrlID == DoCancel) { emit sigError(tr("Canceled")); } else { emit sigError(tr("Error")); } delete listBuf; }
int main ( int narg, char **argv ) { // parse command line ---------------------------------------------- po::options_description general_opt ( "Allowed options are: " ); general_opt.add_options() ( "help,h", "display this message." ) ( "initial,i", po::value< std::string >(), "Initial skeleton pgm filename." ) ( "reduced,r", po::value< std::string >(), "Reduced skeleton pgm filename." ) ( "label,l", po::value< std::string >(), "(part of the) Reduced skeleton being labeled pgm filename." ) ( "selection,s", po::value< std::string >()->multitoken(), "Catch branch touching the given components\' labels of the reduced skeleton.") ( "output,o", po::value< std::string >(), "Extended labeled skeleton pgm filename."); bool parseOK = true ; po::variables_map vm; try { po::store(po::parse_command_line(narg, argv, general_opt), vm); } catch ( const std::exception& ex ) { parseOK = false ; std::cerr<< "Error checking program options: "<< ex.what()<< endl; return -1 ; } po::notify ( vm ); if (!parseOK || vm.count ( "help" ) ||narg<=1 ) { errorAndHelp( general_opt ) ; return -1 ; } if ( ! vm.count("initial") ) missingParam( "initial" ) ; if ( ! vm.count("label") ) missingParam( "label" ) ; if ( ! vm.count("reduced") ) missingParam( "reduced" ) ; if ( ! vm.count("output") ) missingParam( "output" ) ; std::string initialSkelFile = vm["initial"].as<std::string>() ; std::string reducedSkelFile = vm["reduced"].as<std::string>() ; std::string reducedLabelSkelFile = vm["label"].as<std::string>() ; std::string outputSkelFile = vm["output"].as<std::string>() ; QList< tlabel > Labels ; if ( vm.count( "selection" ) ) { QStringList selectedLabels = QString( "%1").arg( vm["selection"].as< std::string >().c_str() ).split( " ", QString::SkipEmptyParts) ; while ( !selectedLabels.isEmpty() ) Labels.append( (tlabel)selectedLabels.takeAt(0).toInt() ) ; qSort( Labels.begin(), Labels.end(), qLess<tlabel>() ) ; std::cout<<"Selection : "; for ( QList< tlabel >::ConstIterator lbl = Labels.begin() ; lbl != Labels.end() ; lbl++ ) std::cout<<"["<<(int) *lbl<<"] " ; std::cout<<std::endl; } BillonTpl< tlabel > *labelReducedSkel ; BillonTpl< arma::u8 > *initialSkel, *reducedSkel ; { Pgm3dFactory< tlabel > factory ; labelReducedSkel = factory.read( QString(reducedLabelSkelFile.c_str()) ) ; } { Pgm3dFactory< arma::u8 > factory ; initialSkel = factory.read( QString(initialSkelFile.c_str()) ) ; if ( initialSkel->max() > 1 ) *initialSkel /= initialSkel->max() ; reducedSkel = factory.read( QString(reducedSkelFile.c_str()) ) ; if ( reducedSkel->max() > 1 ) *reducedSkel /= reducedSkel->max() ; } QList< uint * > touching ; make_branch( initialSkel, reducedSkel, labelReducedSkel, touching ) ; delete reducedSkel ; ConnexComponentExtractor< arma::u8, tlabelbranch > CCE ; BillonTpl< tlabelbranch > * labelBranch = CCE.run( *initialSkel ) ; IOPgm3d< tlabelbranch, qtlabelbranch, false >::write( *labelBranch, "/tmp/whois429.pgm3d" ) ; delete initialSkel ; QMap< tlabelbranch, tlabel > NewLabelBranch ; QMap< tlabel, QList<tlabel> > edges ; set_branch( touching, labelReducedSkel, labelBranch, NewLabelBranch, Labels,edges ) ; attach_branch( labelReducedSkel, labelBranch, NewLabelBranch, Labels ) ; IOPgm3d< tlabel, qtlabel, false >::write( *labelReducedSkel, QString(outputSkelFile.c_str() ) ) ; while ( !touching.isEmpty() ) { delete [] touching.takeFirst() ; } delete labelReducedSkel ; delete labelBranch ; return 0 ; }