// Copy theme package into themes directory void SplashInstaller::addNewTheme(const KUrl &srcURL) { const QString dir = KGlobal::dirs()->saveLocation("ksplashthemes"); KUrl url; QStringList themeNames; QString filename = srcURL.fileName(); int i = filename.lastIndexOf('.'); // Convert extension to lower case. if (i >= 0) filename = filename.left(i)+filename.mid(i).toLower(); url.setPath(KStandardDirs::locateLocal("tmp",filename)); // Remove file from temporary directory if it aleady exists - usually the result of a failed install. if ( KIO::NetAccess::exists( url, KIO::NetAccess::SourceSide, 0 ) ) KIO::NetAccess::del( url, 0 ); if (srcURL.fileName().toLower() == "theme.rc" ) // uncompressed theme selected { QString themeName; // Get the name of the Theme from the theme.rc file KConfig _cnf(srcURL.path()); KConfigGroup cnf(&_cnf, QString("KSplash Theme: %1").arg(themeName) ); // copy directory of theme.rc to ThemesDir KIO::NetAccess::dircopy(KUrl(srcURL.directory()), KUrl(dir + themeName)); themeNames << themeName; } else { bool rc = KIO::NetAccess::file_copy(srcURL, url, 0); if (!rc) { kWarning() << "Failed to copy theme " << srcURL.fileName() << " into temporary directory " << url.path() << endl; return; } // Extract into theme directory: we may have multiple themes in one tarball! KTar tarFile(url.path()); if (!tarFile.open(QIODevice::ReadOnly)) { kWarning() << "Unable to open archive: " << url.path(); KIO::NetAccess::del( url, 0 ); return; } KArchiveDirectory const *ad = tarFile.directory(); // Find first directory entry. const QStringList entries = ad->entries(); foreach(const QString& s, entries) { if( ad->entry(s)->isDirectory() ) { // each directory may contain one theme themeNames << s; } } if (themeNames.count() < 1) { kWarning() << "No directory in archive: " << url.path(); tarFile.close(); KIO::NetAccess::del( url, 0 ); return; } // copy the theme into the "ksplashthemes" directory ad->copyTo(dir); tarFile.close(); KIO::NetAccess::del( url, 0 ); } readThemesList(); mThemesList->setCurrentRow(findTheme(themeNames.first())); if (mThemesList->currentItem()) { mThemesList->currentItem()->setSelected(true); } }
void CMakeRunPage::initializePage() { if (m_mode == Initial) { m_complete = m_cmakeWizard->existsUpToDateXmlFile(); m_buildDirectory = m_cmakeWizard->buildDirectory(); if (m_cmakeWizard->existsUpToDateXmlFile()) { m_descriptionLabel->setText( tr("The directory %1 already contains a cbp file, which is recent enough. " "You can pass special arguments or change the used toolchain here and rerun cmake. " "Or simply finish the wizard directly").arg(m_buildDirectory)); } else { m_descriptionLabel->setText( tr("The directory %1 does not contain a cbp file. Qt Creator needs to create this file by running cmake. " "Some projects require command line arguments to the initial cmake call.").arg(m_buildDirectory)); } } else if (m_mode == CMakeRunPage::Update) { m_descriptionLabel->setText(tr("The directory %1 contains an outdated .cbp file. Qt " "Creator needs to update this file by running cmake. " "If you want to add additional command line arguments, " "add them below. Note that cmake remembers command " "line arguments from the previous runs.").arg(m_buildDirectory)); } else if(m_mode == CMakeRunPage::Recreate) { m_descriptionLabel->setText(tr("The directory %1 specified in a build-configuration, " "does not contain a cbp file. Qt Creator needs to " "recreate this file, by running cmake. " "Some projects require command line arguments to " "the initial cmake call. Note that cmake remembers command " "line arguments from the previous runs.").arg(m_buildDirectory)); } else if(m_mode == CMakeRunPage::Change) { m_buildDirectory = m_cmakeWizard->buildDirectory(); m_descriptionLabel->setText(tr("Qt Creator needs to run cmake in the new build directory. " "Some projects require command line arguments to the " "initial cmake call.")); } if (m_cmakeWizard->cmakeManager()->hasCodeBlocksMsvcGenerator()) { m_generatorComboBox->setVisible(true); QString cachedGenerator; // Try to find out generator from CMakeCachhe file, if it exists QFile fi(m_buildDirectory + "/CMakeCache.txt"); if (fi.exists()) { // Cache exists, then read it... if (fi.open(QIODevice::ReadOnly | QIODevice::Text)) { while (!fi.atEnd()) { QString line = fi.readLine(); if (line.startsWith("CMAKE_GENERATOR:INTERNAL=")) { int splitpos = line.indexOf('='); if (splitpos != -1) { cachedGenerator = line.mid(splitpos + 1).trimmed(); } break; } } } } m_generatorComboBox->clear(); // Find out whether we have multiple msvc versions QStringList msvcVersions = ProjectExplorer::ToolChain::availableMSVCVersions(); if (msvcVersions.isEmpty()) { } else if (msvcVersions.count() == 1) { m_generatorComboBox->addItem(tr("NMake Generator"), msvcVersions.first()); } else { foreach (const QString &msvcVersion, msvcVersions) m_generatorComboBox->addItem(tr("NMake Generator (%1)").arg(msvcVersion), msvcVersion); } if (cachedGenerator == "NMake Makefiles" && !msvcVersions.isEmpty()) m_generatorComboBox->setCurrentIndex(0); m_generatorComboBox->addItem(tr("MinGW Generator"), "mingw"); if (cachedGenerator == "MinGW Makefiles") m_generatorComboBox->setCurrentIndex(m_generatorComboBox->count() - 1); } else {
/** * @brief GameView::applyGamerAction Réception des action des joueurs * @param s Chaine d'action * * Cette methode est utilisée par la GameView coté serveur afin d'executer * les actions des clients */ void GameView::applyGamerAction(QString s) { QStringList msgStr = s.split("."); if(msgStr.size() != 5) return; ACTIONS cmd = (ACTIONS)msgStr.first().toInt(); msgStr.pop_front(); int gamerId = msgStr.first().toInt(); //Identifiant du joueur msgStr.pop_front(); Node *nodeFrom = scene->getNode(msgStr.first().toInt()); //noeud source msgStr.pop_front(); Node *nodeTo = scene->getNode(msgStr.first().toInt()); //noeud cible msgStr.pop_front(); int param = msgStr.first().toInt(); //Parametre de l'action (nb ressource / pouvoir id) switch (cmd) { case GA_SEND: { qDebug()<<"GameView : in 'applyGamerAction' recive GA_SEND"; receive_GA_SEND(gamerId, nodeFrom, nodeTo, param); break; } case GA_USEPOWER_DESTROY: { qDebug()<<"GameView : in 'applyGamerAction' recive GA_USEPOWER_DESTROY"; receive_GA_USEPOWER_DESTROY(gamerId, nodeFrom, nodeTo, param); break; } case GA_USEPOWER_INVINCIBILITY: { qDebug()<<"GameView : in 'applyGamerAction' recive GA_USEPOWER_INVINCIBILITY"; receive_GA_USEPOWER_INVINCIBILITY(gamerId, nodeFrom, nodeTo, param); break; } case GA_USEPOWER_ARMORE: { qDebug()<<"GameView : in 'applyGamerAction' recive GA_USEPOWER_ARMORE"; receive_GA_USEPOWER_ARMORE(gamerId, nodeFrom, nodeTo, param); break; } case GA_USEPOWER_TELEPORTATION: { qDebug()<<"GameView : in 'applyGamerAction' recive GA_USEPOWER_TELEPORTATION"; receive_GA_USEPOWER_TELEPORTATION(gamerId, nodeFrom, nodeTo, param); break; } case GA_GAME_FINISHED: { qDebug()<<"GameView : in 'applyGamerAction' recive GA_GAME_FINISHED"; receive_GA_GAME_FINISHED(gamerId, nodeFrom, nodeTo, param); break; } case GA_MANA_BURN: { qDebug()<<"GameView : in 'applyGamerAction' recive GA_MANA_BURN"; receive_GA_MANA_BURN(gamerId, nodeFrom, nodeTo, param); break; } default: qCritical()<<"GameView : unexpected case in 'applyGamerAction'"; break; } }
void EjecutarInstruccion(char *instruccion) { QString slInstruccion = QString("%1").arg(instruccion); QString slInstruccionAEjecutar; // Pasar cualquier instruccion a mayuscula slInstruccion = slInstruccion.toLower(); // Retirar blancos de instruccion (espacios,tabuladores, etc.) slInstruccion = slInstruccion.simplified(); if(slInstruccion.contains(QRegExp(";"))) { // Ignorar instruccion return; } else if(slInstruccion.contains(QRegExp("mov"))) { emInstruccion = MOV; printf("MOV\n"); slInstruccionAEjecutar = slInstruccion.replace("mov", ""); printf("slInstruccionAEjecutar\n"); QStringList sllOperadorOperandos = slInstruccionAEjecutar.split(","); QString slDestino, slOrigen; if(!sllOperadorOperandos.isEmpty()) { if(sllOperadorOperandos.length() != 2) { printf("Error diferente de dos operandos.\n"); return; } else { slDestino = sllOperadorOperandos.first(); slOrigen = sllOperadorOperandos.last(); Verificar2Operandos(slDestino, slOrigen); } } else { printf("Error instruccion vacia."); } } else if(slInstruccion.contains(QRegExp("add"))) { emInstruccion = ADD; printf("ADD\n"); slInstruccionAEjecutar = slInstruccion.replace("add", ""); printf("slInstruccionAEjecutar\n"); QStringList sllOperadorOperandos = slInstruccionAEjecutar.split(","); QString slDestino, slOrigen; if(!sllOperadorOperandos.isEmpty()) { if(sllOperadorOperandos.length() != 2) { printf("Error diferente de dos operandos.\n"); return; } else { slDestino = sllOperadorOperandos.first(); slOrigen = sllOperadorOperandos.last(); Verificar2Operandos(slDestino, slOrigen); } } } else if(slInstruccion.contains(QRegExp("sub"))) { emInstruccion = SUB; printf("SUB\n"); slInstruccionAEjecutar = slInstruccion.replace("sub", ""); printf("slInstruccionAEjecutar\n"); QStringList sllOperadorOperandos = slInstruccionAEjecutar.split(","); QString slDestino, slOrigen; if(!sllOperadorOperandos.isEmpty()) { if(sllOperadorOperandos.length() != 2) { printf("Error diferente de dos operandos.\n"); return; } else { slDestino = sllOperadorOperandos.first(); slOrigen = sllOperadorOperandos.last(); Verificar2Operandos(slDestino, slOrigen); } } } else if(slInstruccion.contains(QRegExp("div"))) { emInstruccion = DIV; printf("DIV\n"); slInstruccionAEjecutar = slInstruccion.replace("div", ""); printf("slInstruccionAEjecutar\n"); QStringList sllOperadorOperandos = slInstruccionAEjecutar.split(","); QString slDestino, slOrigen; if(!sllOperadorOperandos.isEmpty()) { if(sllOperadorOperandos.length() != 2) { printf("Error diferente de dos operandos.\n"); return; } else { slDestino = sllOperadorOperandos.first(); slOrigen = sllOperadorOperandos.last(); Verificar2Operandos(slDestino, slOrigen); } } } else if(slInstruccion.contains(QRegExp("mul"))) { emInstruccion = MUL; printf("MUL\n"); slInstruccionAEjecutar = slInstruccion.replace("mul", ""); printf("slInstruccionAEjecutar\n"); QStringList sllOperadorOperandos = slInstruccionAEjecutar.split(","); QString slDestino, slOrigen; if(!sllOperadorOperandos.isEmpty()) { if(sllOperadorOperandos.length() != 2) { printf("Error diferente de dos operandos.\n"); return; } else { slDestino = sllOperadorOperandos.first(); slOrigen = sllOperadorOperandos.last(); Verificar2Operandos(slDestino, slOrigen); } } } else if(slInstruccion.contains(QRegExp("and"))) { emInstruccion = AND; printf("AND\n"); slInstruccionAEjecutar = slInstruccion.replace("and", ""); printf("slInstruccionAEjecutar\n"); QStringList sllOperadorOperandos = slInstruccionAEjecutar.split(","); QString slDestino, slOrigen; if(!sllOperadorOperandos.isEmpty()) { if(sllOperadorOperandos.length() != 2) { printf("Error diferente de dos operandos.\n"); return; } else { slDestino = sllOperadorOperandos.first(); slOrigen = sllOperadorOperandos.last(); Verificar2Operandos(slDestino, slOrigen); } } } else if(slInstruccion.contains(QRegExp("or"))) { emInstruccion = OR; printf("OR\n"); slInstruccionAEjecutar = slInstruccion.replace("or", ""); printf("slInstruccionAEjecutar\n"); QStringList sllOperadorOperandos = slInstruccionAEjecutar.split(","); QString slDestino, slOrigen; if(!sllOperadorOperandos.isEmpty()) { if(sllOperadorOperandos.length() != 2) { printf("Error diferente de dos operandos.\n"); return; } else { slDestino = sllOperadorOperandos.first(); slOrigen = sllOperadorOperandos.last(); Verificar2Operandos(slDestino, slOrigen); } } } else if(slInstruccion.contains(QRegExp("xor"))) { emInstruccion = XOR; printf("XOR\n"); slInstruccionAEjecutar = slInstruccion.replace("xor", ""); printf("slInstruccionAEjecutar\n"); QStringList sllOperadorOperandos = slInstruccionAEjecutar.split(","); QString slDestino, slOrigen; if(!sllOperadorOperandos.isEmpty()) { if(sllOperadorOperandos.length() != 2) { printf("Error diferente de dos operandos.\n"); return; } else { slDestino = sllOperadorOperandos.first(); slOrigen = sllOperadorOperandos.last(); Verificar2Operandos(slDestino, slOrigen); } } } else if(slInstruccion.contains(QRegExp("xnor"))) { emInstruccion = MUL; printf("XNOR\n"); slInstruccionAEjecutar = slInstruccion.replace("xnor", ""); printf("slInstruccionAEjecutar\n"); QStringList sllOperadorOperandos = slInstruccionAEjecutar.split(","); QString slDestino, slOrigen; if(!sllOperadorOperandos.isEmpty()) { if(sllOperadorOperandos.length() != 2) { printf("Error diferente de dos operandos.\n"); return; } else { slDestino = sllOperadorOperandos.first(); slOrigen = sllOperadorOperandos.last(); Verificar2Operandos(slDestino, slOrigen); } } } else if(slInstruccion.contains(QRegExp("inc"))) { QString slDestino; emInstruccion = INC; printf("INC\n"); slDestino = slInstruccion.replace("inc", ""); Verificar1Operandos(slDestino); } else if(slInstruccion.contains(QRegExp("dec"))) { QString slDestino; emInstruccion = DEC; printf("DEC\n"); slDestino = slInstruccion.replace("dec", ""); Verificar1Operandos(slDestino); } else if(slInstruccion.contains(QRegExp("push"))) { QString slDestino; emInstruccion = PUSH; printf("PUSH\n"); slDestino = slInstruccion.replace("push", ""); Verificar1Operandos(slDestino); } else if(slInstruccion.contains(QRegExp("pop"))) { QString slDestino; emInstruccion = POP; printf("POP\n"); slDestino = slInstruccion.replace("pop", ""); Verificar1Operandos(slDestino); } else if(slInstruccion.contains(QRegExp("test"))) { QString slDestino; emInstruccion = TEST; printf("TEST\n"); slDestino = slInstruccion.replace("test", ""); Verificar1Operandos(slDestino); } else if(slInstruccion.contains(QRegExp("not"))) { QString slDestino; emInstruccion = NOT; printf("NOT\n"); slDestino = slInstruccion.replace("not", ""); Verificar1Operandos(slDestino); } else if(slInstruccion.contains(QRegExp("lea"))) { QString slDestino; emInstruccion = LEA; printf("LEA\n"); slDestino = slInstruccion.replace("lea", ""); Verificar1Operandos(slDestino); } else if(slInstruccion.contains(QRegExp("lds"))) { QString slDestino; emInstruccion = LDS; printf("LDS\n"); slDestino = slInstruccion.replace("lds", ""); Verificar1Operandos(slDestino); } else if(slInstruccion.contains(QRegExp("les"))) { QString slDestino; emInstruccion = LES; printf("LES\n"); slDestino = slInstruccion.replace("les", ""); Verificar1Operandos(slDestino); } else if(slInstruccion.contains(QRegExp("shl"))) { emInstruccion = SHL; printf("SHL\n"); slInstruccionAEjecutar = slInstruccion.replace("shl", ""); printf("slInstruccionAEjecutar\n"); QStringList sllOperadorOperandos = slInstruccionAEjecutar.split(","); QString slDestino, slOrigen; if(!sllOperadorOperandos.isEmpty()) { if(sllOperadorOperandos.length() != 2) { printf("Error diferente de dos operandos.\n"); return; } else { slDestino = sllOperadorOperandos.first(); slOrigen = sllOperadorOperandos.last(); Verificar2Operandos(slDestino, slOrigen); } } } else if(slInstruccion.contains(QRegExp("shr"))) { emInstruccion = SHR; printf("SHR\n"); slInstruccionAEjecutar = slInstruccion.replace("shr", ""); printf("slInstruccionAEjecutar\n"); QStringList sllOperadorOperandos = slInstruccionAEjecutar.split(","); QString slDestino, slOrigen; if(!sllOperadorOperandos.isEmpty()) { if(sllOperadorOperandos.length() != 2) { printf("Error diferente de dos operandos.\n"); return; } else { slDestino = sllOperadorOperandos.first(); slOrigen = sllOperadorOperandos.last(); Verificar2Operandos(slDestino, slOrigen); } } } // EvaluarInstruccion(); for(int i=0; i < 8; i++) printf("reg[%d] = %d\n", i, registros[i]); printf("memoria source: address:%d content:%d\n", imValOrigen, memoria[imValOrigen].contenido); printf("memoria dest: address:%d content:%d\n", imValDestino, memoria[imValDestino].contenido); printf("Cima pila[%d] = %d\n", sp, pila[sp].contenido); }
static QString poEscapedString(const QString &prefix, const QString &keyword, bool noWrap, const QString &ba) { QStringList lines; int off = 0; QString res; while (off < ba.length()) { ushort c = ba[off++].unicode(); switch (c) { case '\n': res += QLatin1String("\\n"); lines.append(res); res.clear(); break; case '\r': res += QLatin1String("\\r"); break; case '\t': res += QLatin1String("\\t"); break; case '\v': res += QLatin1String("\\v"); break; case '\a': res += QLatin1String("\\a"); break; case '\b': res += QLatin1String("\\b"); break; case '\f': res += QLatin1String("\\f"); break; case '"': res += QLatin1String("\\\""); break; case '\\': res += QLatin1String("\\\\"); break; default: if (c < 32) { res += QLatin1String("\\x"); res += QString::number(c, 16); if (off < ba.length() && isxdigit(ba[off].unicode())) res += QLatin1String("\"\""); } else { res += QChar(c); } break; } } if (!res.isEmpty()) lines.append(res); if (!lines.isEmpty()) { if (!noWrap) { if (lines.count() != 1 || lines.first().length() > MAX_LEN - keyword.length() - prefix.length() - 3) { QStringList olines = lines; lines = QStringList(QString()); const int maxlen = MAX_LEN - prefix.length() - 2; foreach (const QString &line, olines) { int off = 0; while (off + maxlen < line.length()) { int idx = line.lastIndexOf(QLatin1Char(' '), off + maxlen - 1) + 1; if (idx == off) { #ifdef HARD_WRAP_LONG_WORDS // This doesn't seem too nice, but who knows ... idx = off + maxlen; #else idx = line.indexOf(QLatin1Char(' '), off + maxlen) + 1; if (!idx) break; #endif } lines.append(line.mid(off, idx - off)); off = idx; } lines.append(line.mid(off)); } } } else if (lines.count() > 1) {
/** return the property that matches the given key sequence, if any @param scope scope of key @param key keyname @param rootProperty is likely to be the top level QgsPropertyKey in QgsProject:e:Imp. @return null if not found, otherwise located Property */ static QgsProperty * findKey_( QString const & scope, QString const & key, QgsPropertyKey & rootProperty ) { QgsPropertyKey * currentProperty = &rootProperty; QgsProperty * nextProperty; // link to next property down hiearchy QStringList keySequence = makeKeyTokens_( scope, key ); while ( ! keySequence.isEmpty() ) { // if the current head of the sequence list matches the property name, // then traverse down the property hierarchy if ( keySequence.first() == currentProperty->name() ) { // remove front key since we're traversing down a level keySequence.pop_front(); // if we have only one key name left, then return the key found if ( 1 == keySequence.count() ) { return currentProperty->find( keySequence.front() ); } // if we're out of keys then the current property is the one we // want; i.e., we're in the rate case of being at the top-most // property node else if ( keySequence.isEmpty() ) { return currentProperty; } else if (( nextProperty = currentProperty->find( keySequence.first() ) ) ) { if ( nextProperty->isKey() ) { currentProperty = dynamic_cast<QgsPropertyKey*>( nextProperty ); } // it may be that this may be one of several property value // nodes keyed by QDict string; if this is the last remaining // key token and the next property is a value node, then // that's the situation, so return the currentProperty else if ( nextProperty->isValue() && ( 1 == keySequence.count() ) ) { return currentProperty; } else // QgsPropertyValue not Key, so return null { return 0x0; } } else // if the next key down isn't found { // then the overall key sequence doesn't exist return 0x0; } } else { return 0x0; } } return 0x0; } // findKey_
ListerDialog::ListerDialog(QWidget *parent, const QString &settingsGroup, const QString &appName, int flags) : QDialog(parent), m_settingsGroup(settingsGroup), m_appName(appName), m_flags(flags) { setWindowTitle(windowTitleWithAppName(tr("Lister"))); QVBoxLayout *vbox = new QVBoxLayout(this); QHBoxLayout *mainHorizontalLayout = new QHBoxLayout; vbox->addLayout(mainHorizontalLayout); QVBoxLayout *leftSideLayout = new QVBoxLayout; mainHorizontalLayout->addLayout(leftSideLayout); QVBoxLayout *rightSideLayout = new QVBoxLayout; mainHorizontalLayout->addLayout(rightSideLayout); mainHorizontalLayout->setStretchFactor(leftSideLayout, 3); // left side QHBoxLayout *queryLayout = new QHBoxLayout; leftSideLayout->addLayout(queryLayout); m_queryEdit = new QLineEdit; connect(m_queryEdit, SIGNAL(returnPressed()), this, SLOT(queryGo())); queryLayout->addWidget(m_queryEdit); m_queryButton = new QPushButton(tr("A-Z?* Query")); queryLayout->addWidget(m_queryButton); connect(m_queryButton, SIGNAL(clicked()), this, SLOT(queryGo())); QHBoxLayout *smallHLayout = new QHBoxLayout; leftSideLayout->addLayout(smallHLayout); m_numResultsLabel = new QLabel; smallHLayout->addWidget(m_numResultsLabel); smallHLayout->addStretch(); m_buildChecker = new QCheckBox(tr("Buil&d")); smallHLayout->addWidget(m_buildChecker); m_sowpodsChecker = new QCheckBox(tr("Remove &British")); connect(m_sowpodsChecker, SIGNAL(toggled(bool)), this, SLOT(setRemoveSowpods(bool))); if (!(m_flags & IgnoreBritishness)) smallHLayout->addWidget(m_sowpodsChecker); m_listBox = new QListWidget; leftSideLayout->addWidget(m_listBox); m_numResultsLabel->setBuddy(m_listBox); // right side QLabel *filtersLabel = new QLabel(tr("&Filters:")); rightSideLayout->addWidget(filtersLabel); m_filtersBox = new QListWidget; rightSideLayout->addWidget(m_filtersBox); connect(m_filtersBox, SIGNAL(itemClicked(QListWidgetItem *)), this, SLOT(showFilter(QListWidgetItem *))); filtersLabel->setBuddy(m_filtersBox); QStringList filters; if (m_flags & ProbabilityInsteadOfPlayability) filters << "Probability"; else filters << "Playability"; filters << "Regex"; filters << "Num. Anagrams"; if (!(m_flags & IgnoreBritishness)) filters << "Keep British"; m_filtersBox->addItems(filters); m_filtersLayout = new QVBoxLayout; rightSideLayout->addLayout(m_filtersLayout); m_currentFilter = 0; m_applyButton = new QPushButton(tr("&Apply")); rightSideLayout->addWidget(m_applyButton); // bottom QHBoxLayout *filenameLayout = new QHBoxLayout; vbox->addLayout(filenameLayout); QPushButton *filenameButton = new QPushButton(tr("Pic&k filename...")); filenameLayout->addWidget(filenameButton); connect(filenameButton, SIGNAL(clicked()), this, SLOT(chooseFilename())); m_filenameEdit = new QLineEdit; filenameLayout->addWidget(m_filenameEdit); QHBoxLayout *buttonBox = new QHBoxLayout; vbox->addLayout(buttonBox); QHBoxLayout *buttonBox2 = new QHBoxLayout; vbox->addLayout(buttonBox2); m_writeButton = new QPushButton(tr("&Write alphagram file")); m_writeNormalButton = new QPushButton(tr("&Write normal file")); m_studyThisButton = new QPushButton(tr("Write and &Study")); QPushButton *openButton = new QPushButton(tr("&Open File...")); QPushButton *clearButton = new QPushButton(tr("C&lear")); m_closeButton = new QPushButton(tr("&Close")); buttonBox->addWidget(m_writeButton); buttonBox->addWidget(m_writeNormalButton); if (!(m_flags & NothingToReturn)) buttonBox->addWidget(m_studyThisButton); buttonBox->addWidget(openButton); buttonBox2->addWidget(clearButton); buttonBox2->addStretch(); buttonBox2->addWidget(m_closeButton); filenameChanged(QString::null); // disable write button initially connect(m_filenameEdit, SIGNAL(textChanged(const QString &)), this, SLOT(filenameChanged(const QString &))); connect(m_writeButton, SIGNAL(clicked()), this, SLOT(writeButtonClicked())); connect(m_writeNormalButton, SIGNAL(clicked()), this, SLOT(writeNormalButtonClicked())); connect(m_studyThisButton, SIGNAL(clicked()), this, SLOT(studyButtonClicked())); connect(m_closeButton, SIGNAL(clicked()), this, SLOT(done())); connect(clearButton, SIGNAL(clicked()), this, SLOT(clear())); connect(openButton, SIGNAL(clicked()), this, SLOT(openFile())); showFilter(filters.first()); //m_filtersBox->setCurrentItem(0); clear(); }
int LupdateApplication::start() { QStringList argv = arguments(); int argc = argv.count(); QString defaultContext; // This was QLatin1String("@default") before. MetaTranslator fetchedTor; QByteArray codecForTr; QByteArray codecForSource; QStringList tsFileNames; QStringList proFiles; QStringList sourceFiles; bool verbose = true; // verbose is on by default starting with Qt 4.2 bool noObsolete = false; bool onlyPlural = false; int numFiles = 0; bool standardSyntax = true; bool metTsFlag = false; QString extensions = m_defaultExtensions; QStringList extensionsNameFilters; int i; for ( i = 1; i < argc; i++ ) { if ( argv.at(i) == QLatin1String("-ts") ) standardSyntax = false; } for ( i = 1; i < argc; i++ ) { QString arg = argv.at(i); if ( arg == QLatin1String("-help") || arg == QLatin1String("--help") || arg == QLatin1String("-h")) { printUsage(); return 0; } else if ( arg == QLatin1String("-pluralonly") ) { onlyPlural = true; continue; } else if ( arg == QLatin1String("-noobsolete") ) { noObsolete = true; continue; } else if ( arg == QLatin1String("-silent") ) { verbose = false; continue; } else if ( arg == QLatin1String("-verbose") ) { verbose = true; continue; } else if ( arg == QLatin1String("-version") ) { Console::out(tr("lupdate version %1\n").arg(QLatin1String(QT_VERSION_STR)) ); return 0; } else if ( arg == QLatin1String("-ts") ) { metTsFlag = true; continue; } else if ( arg == QLatin1String("-extensions") ) { ++i; if (i == argc) { qWarning("The -extensions option should be followed by an extension list."); return 1; } extensions = argv.at(i); continue; } numFiles++; QString fullText; if ( standardSyntax && !metTsFlag ) { QFile f( arg ); if ( !f.open(QIODevice::ReadOnly) ) { #if defined(_MSC_VER) && _MSC_VER >= 1400 char buf[100]; strerror_s(buf, sizeof(buf), errno); qWarning("lupdate error: Cannot open file '%s': %s\n", qPrintable(arg), buf ); #else qWarning("lupdate error: Cannot open file '%s': %s\n", qPrintable(arg), strerror(errno) ); #endif return 1; } f.close(); } codecForTr.clear(); codecForSource.clear(); if (metTsFlag) { if ( arg.endsWith(QLatin1String(".ts"), Qt::CaseInsensitive) || arg.endsWith(QLatin1String(".xlf"), Qt::CaseInsensitive)) { QFileInfo fi( arg ); if ( !fi.exists() || fi.isWritable() ) { tsFileNames.append( QFileInfo(arg).absoluteFilePath() ); } else { qWarning("lupdate warning: For some reason, I cannot save '%s'\n", qPrintable(arg) ); } } else { qWarning("lupdate error: File '%s' lacks .ts or .xlf extension\n", qPrintable(arg) ); } } else if (arg.endsWith(QLatin1String(".pro"), Qt::CaseInsensitive)) { proFiles << arg; } else { QFileInfo fi(arg); if (fi.isDir()) { if ( verbose ) Console::out(tr("Scanning directory '%1'...\n").arg(arg)); QDir dir = QDir(fi.filePath()); if (extensionsNameFilters.isEmpty()) { extensions = extensions.trimmed(); // Remove the potential dot in front of each extension if (extensions.startsWith(QLatin1Char('.'))) extensions.remove(0,1); extensions.replace(QLatin1String(",."), QLatin1String(",")); extensions.insert(0, QLatin1String("*.")); extensions.replace(QLatin1Char(','), QLatin1String(",*.")); extensionsNameFilters = extensions.split(QLatin1Char(',')); } QDir::Filters filters = QDir::Files | QDir::NoSymLinks; QFileInfoList fileinfolist; recursiveFileInfoList(dir, extensionsNameFilters, filters, true, &fileinfolist); QFileInfoList::iterator ii; QString fn; for (ii = fileinfolist.begin(); ii != fileinfolist.end(); ++ii) { // Make sure the path separator is stored with '/' in the ts file fn = ii->canonicalFilePath().replace(QLatin1Char('\\'),QLatin1Char('/')); #ifdef LINGUIST_DEBUG qDebug() << fn; #endif sourceFiles << fn; } }else{ sourceFiles << fi.canonicalFilePath().replace(QLatin1Char('\\'),QLatin1Char('/')); } } } //for if ( proFiles.count() > 0 ) { proFiles = getListOfProfiles(proFiles, verbose); } bool firstPass = true; for (int pi = 0; firstPass || pi < proFiles.count(); ++pi) { QStringList tsFiles = tsFileNames; if (proFiles.count() > 0) { QString pf = proFiles.at(pi); QMap<QByteArray, QStringList> variables; if(!evaluateProFile(pf, verbose, &variables)) return 2; sourceFiles = variables.value("SOURCES"); QStringList tmp = variables.value("CODECFORTR"); if (!tmp.isEmpty()) { codecForTr = tmp.first().toAscii(); fetchedTor.setCodecForTr(codecForTr.constData()); } tmp = variables.value("CODECFORSRC"); if (!tmp.isEmpty()) { codecForSource = tmp.first().toAscii(); } tsFiles += variables.value("TRANSLATIONS"); } for (QStringList::iterator it = sourceFiles.begin(); it != sourceFiles.end(); ++it) { #ifdef LINGUIST_DEBUG qDebug() << " " << (*it); #endif if ( (*it).endsWith(QLatin1String(".java"), Qt::CaseInsensitive) ) { fetchtr_java( *it, &fetchedTor, defaultContext, true, codecForSource ); } else if ( (*it).endsWith(QLatin1String(".ui"), Qt::CaseInsensitive) ) { #ifdef LINGUIST_DEBUG qDebug() << " " << (*it) + ".h"; #endif fetchtr_ui( *it, &fetchedTor, defaultContext, true ); fetchtr_cpp( *it + QLatin1String(".h"), &fetchedTor, defaultContext, false, codecForSource ); } else { fetchtr_cpp( *it, &fetchedTor, defaultContext, true, codecForSource ); } } removeDuplicates(&tsFiles, false); if ( tsFiles.count() > 0) { updateTsFiles( fetchedTor, tsFiles, QString::fromLatin1(codecForTr.constData()), noObsolete, onlyPlural, verbose ); } firstPass = false; } if ( numFiles == 0 ) { printUsage(); return 1; } return 0; }
int main(int argc, char **argv) { QCoreApplication app(argc, argv); app.setApplicationVersion("1.0"); #ifdef Q_OS_WIN const QLatin1Char pathsep(';'); #else const QLatin1Char pathsep(':'); #endif QCommandLineParser parser; parser.setApplicationDescription(QCoreApplication::translate("qtpaths", "Command line client to QStandardPaths")); parser.addPositionalArgument(QCoreApplication::translate("qtpaths", "[name]"), QCoreApplication::tr("Name of file or directory")); parser.addHelpOption(); parser.addVersionOption(); //setting up options QCommandLineOption types(QStringLiteral("types"), QCoreApplication::translate("qtpaths", "Available location types.")); parser.addOption(types); QCommandLineOption paths(QStringLiteral("paths"), QCoreApplication::translate("qtpaths", "Find paths for <type>."), QStringLiteral("type")); parser.addOption(paths); QCommandLineOption writablePath(QStringLiteral("writable-path"), QCoreApplication::translate("qtpaths", "Find writable path for <type>."), QStringLiteral("type")); parser.addOption(writablePath); QCommandLineOption locateDir(QStringList() << QStringLiteral("locate-dir") << QStringLiteral("locate-directory"), QCoreApplication::translate("qtpaths", "Locate directory [name] in <type>."), QStringLiteral("type")); parser.addOption(locateDir); QCommandLineOption locateDirs(QStringList() << QStringLiteral("locate-dirs") << QStringLiteral("locate-directories"), QCoreApplication::translate("qtpaths", "Locate directories [name] in all paths for <type>."), QStringLiteral("type")); parser.addOption(locateDirs); QCommandLineOption locateFile(QStringLiteral("locate-file"), QCoreApplication::translate("qtpaths", "Locate file [name] for <type>."), QStringLiteral("type")); parser.addOption(locateFile); QCommandLineOption locateFiles(QStringLiteral("locate-files"), QCoreApplication::translate("qtpaths", "Locate files [name] in all paths for <type>."), QStringLiteral("type")); parser.addOption(locateFiles); QCommandLineOption findExe(QStringList() << QStringLiteral("find-exe") << QStringLiteral("find-executable"), QCoreApplication::translate("qtpaths", "Find executable with [name].")); parser.addOption(findExe); QCommandLineOption display(QStringList() << QStringLiteral("display"), QCoreApplication::translate("qtpaths", "Prints user readable name for <type>."), QStringLiteral("type")); parser.addOption(display); QCommandLineOption testmode(QStringList() << QStringLiteral("testmode") << QStringLiteral("test-mode"), QCoreApplication::translate("qtpaths", "Use paths specific for unit testing.")); parser.addOption(testmode); QCommandLineOption qtversion(QStringLiteral("qt-version"), QCoreApplication::translate("qtpaths", "Qt version.")); parser.addOption(qtversion); QCommandLineOption installprefix(QStringLiteral("install-prefix"), QCoreApplication::translate("qtpaths", "Installation prefix for Qt.")); parser.addOption(installprefix); QCommandLineOption bindir(QStringList() << QStringLiteral("binaries-dir") << QStringLiteral("binaries-directory"), QCoreApplication::translate("qtpaths", "Location of Qt executables.")); parser.addOption(bindir); QCommandLineOption plugindir(QStringList() << QStringLiteral("plugin-dir") << QStringLiteral("plugin-directory"), QCoreApplication::translate("qtpaths", "Location of Qt plugins.")); parser.addOption(plugindir); parser.process(app); QStandardPaths::enableTestMode(parser.isSet(testmode)); QStringList results; if (parser.isSet(qtversion)) { QString qtversionstring = QString::fromLatin1(qVersion()); results << qtversionstring; } if (parser.isSet(installprefix)) { QString path = QLibraryInfo::location(QLibraryInfo::PrefixPath); results << path; } if (parser.isSet(bindir)) { QString path = QLibraryInfo::location(QLibraryInfo::BinariesPath); results << path; } if (parser.isSet(plugindir)) { QString path = QLibraryInfo::location(QLibraryInfo::PluginsPath); results << path; } if (parser.isSet(types)) { QStringList typesList = ::types(); results << typesList.join('\n'); } if (parser.isSet(display)) { QStandardPaths::StandardLocation location = parseLocationOrError(parser.value(display)); QString text = QStandardPaths::displayName(location); results << text; } if (parser.isSet(paths)) { QStandardPaths::StandardLocation location = parseLocationOrError(parser.value(paths)); QStringList paths = QStandardPaths::standardLocations(location); results << paths.join(pathsep); } if (parser.isSet(writablePath)) { QStandardPaths::StandardLocation location = parseLocationOrError(parser.value(writablePath)); QString path = QStandardPaths::writableLocation(location); results << path; } if (parser.isSet(findExe)) { QString searchitem = searchStringOrError(&parser); QString path = QStandardPaths::findExecutable(searchitem); results << path; } if (parser.isSet(locateDir)) { QStandardPaths::StandardLocation location = parseLocationOrError(parser.value(locateDir)); QString searchitem = searchStringOrError(&parser); QString path = QStandardPaths::locate(location, searchitem, QStandardPaths::LocateDirectory); results << path; } if (parser.isSet(locateFile)) { QStandardPaths::StandardLocation location = parseLocationOrError(parser.value(locateFile)); QString searchitem = searchStringOrError(&parser); QString path = QStandardPaths::locate(location, searchitem, QStandardPaths::LocateFile); results << path; } if (parser.isSet(locateDirs)) { QStandardPaths::StandardLocation location = parseLocationOrError(parser.value(locateDirs)); QString searchitem = searchStringOrError(&parser); QStringList paths = QStandardPaths::locateAll(location, searchitem, QStandardPaths::LocateDirectory); results << paths.join(pathsep); } if (parser.isSet(locateFiles)) { QStandardPaths::StandardLocation location = parseLocationOrError(parser.value(locateFiles)); QString searchitem = searchStringOrError(&parser); QStringList paths = QStandardPaths::locateAll(location, searchitem, QStandardPaths::LocateFile); results << paths.join(pathsep); } if (results.isEmpty()) { parser.showHelp(); } else if (results.size() == 1) { const QString &item = results.first(); message(item); if (item.isEmpty()) return EXIT_FAILURE; } else { QString errorMessage = QCoreApplication::translate("qtpaths", "Several options given, only one is supported at a time."); error(errorMessage); } return EXIT_SUCCESS; }
void WebWidget::showContextMenu(const QPoint &position) { m_contextMenuReason = QContextMenuEvent::Other; const bool hasSelection = (this->hasSelection() && !getSelectedText().trimmed().isEmpty()); if (m_ignoreContextMenu || (position.isNull() && (!hasSelection || m_clickPosition.isNull()))) { return; } const QPoint hitPosition = (position.isNull() ? m_clickPosition : position); if (isScrollBar(hitPosition) || (SettingsManager::getValue(QLatin1String("Browser/JavaScriptCanDisableContextMenu")).toBool() && !canShowContextMenu(hitPosition))) { return; } updateHitTestResult(hitPosition); updateEditActions(); QStringList flags; if (m_hitResult.flags.testFlag(IsFormTest)) { flags.append(QLatin1String("form")); } if (!m_hitResult.imageUrl.isValid() && m_hitResult.flags.testFlag(IsSelectedTest) && hasSelection) { flags.append(QLatin1String("selection")); } if (m_hitResult.linkUrl.isValid()) { if (m_hitResult.linkUrl.scheme() == QLatin1String("mailto")) { flags.append(QLatin1String("mail")); } else { flags.append(QLatin1String("link")); } } if (!m_hitResult.imageUrl.isEmpty()) { flags.append(QLatin1String("image")); } if (m_hitResult.mediaUrl.isValid()) { flags.append(QLatin1String("media")); } if (m_hitResult.flags.testFlag(IsContentEditableTest)) { flags.append(QLatin1String("edit")); } if (flags.isEmpty() || (flags.size() == 1 && flags.first() == QLatin1String("form"))) { flags.append(QLatin1String("standard")); if (m_hitResult.frameUrl.isValid()) { flags.append(QLatin1String("frame")); } } if (flags.isEmpty()) { return; } Menu menu(Menu::NoMenuRole, this); menu.load(QLatin1String("menu/webWidget.json"), flags); menu.exec(mapToGlobal(hitPosition)); }
void PackageStructureTest::mutateAfterCopy() { const bool mainscriptRequired = ps.isRequired("mainscript"); const QStringList imageMimeTypes = ps.mimeTypes("images"); const QStringList defaultMimeTypes = ps.mimeTypes("translations"); const QString packageRoot = ps.defaultPackageRoot(); const bool externalPaths = ps.allowExternalPaths(); const QStringList contentsPrefixPaths = ps.contentsPrefixPaths(); const QList<QByteArray> files = ps.files(); const QList<QByteArray> dirs = ps.directories(); KPackage::Package copy(ps); copy.setRequired("mainscript", !mainscriptRequired); QCOMPARE(ps.isRequired("mainscript"), mainscriptRequired); QCOMPARE(copy.isRequired("mainscript"), !mainscriptRequired); copy = ps; const QString copyPackageRoot = packageRoot + "more/"; copy.setDefaultPackageRoot(copyPackageRoot); QCOMPARE(ps.defaultPackageRoot(), packageRoot); QCOMPARE(copy.defaultPackageRoot(), copyPackageRoot); copy = ps; copy.setAllowExternalPaths(!externalPaths); QCOMPARE(ps.allowExternalPaths(), externalPaths); QCOMPARE(copy.allowExternalPaths(), !externalPaths); copy = ps; QStringList copyContentsPrefixPaths = contentsPrefixPaths; copyContentsPrefixPaths << QStringLiteral("more/"); copy.setContentsPrefixPaths(copyContentsPrefixPaths); QCOMPARE(ps.contentsPrefixPaths(), contentsPrefixPaths); QCOMPARE(copy.contentsPrefixPaths(), copyContentsPrefixPaths); copy = ps; copy.addFileDefinition("nonsense", QStringLiteral("foobar"), QString()); QCOMPARE(ps.files(), files); QVERIFY(ps.files() != copy.files()); copy = ps; copy.addDirectoryDefinition("nonsense", QStringLiteral("foobar"), QString()); QCOMPARE(ps.directories(), dirs); QVERIFY(ps.directories() != copy.directories()); copy = ps; copy.removeDefinition("mainscript"); QCOMPARE(ps.files(), files); QVERIFY(ps.files() != copy.files()); copy = ps; QVERIFY(!imageMimeTypes.isEmpty()); QStringList copyMimeTypes; copyMimeTypes << imageMimeTypes.first(); copy.setMimeTypes("images", copyMimeTypes); QCOMPARE(ps.mimeTypes("images"), imageMimeTypes); QCOMPARE(copy.mimeTypes("images"), copyMimeTypes); copy = ps; QStringList copyDefaultMimeTypes = defaultMimeTypes; copyDefaultMimeTypes << QStringLiteral("rubbish"); copy.setDefaultMimeTypes(copyDefaultMimeTypes); QCOMPARE(ps.mimeTypes("translations"), defaultMimeTypes); QCOMPARE(copy.mimeTypes("translations"), copyDefaultMimeTypes); }
void FakeJobResponse::parseEntityString( QList<FakeJobResponse *> &collectionResponseList, QHash<Collection::Id, FakeJobResponse *> &itemResponseMap, Collection::List &recentCollections, FakeServerData *fakeServerData, const QString& _entityString, int depth ) { QString entityString = _entityString; if ( entityString.startsWith( 'C' ) ) { Collection collection; entityString.remove( 0, 2 ); Q_ASSERT( entityString.startsWith( '(' ) ); entityString.remove( 0, 1 ); QStringList parts = entityString.split( ')' ); if ( !parts.first().isEmpty() ) { QString typesString = parts.takeFirst(); QStringList types = typesString.split(','); types.replaceInStrings(" ", ""); collection.setContentMimeTypes( types ); } else { parts.removeFirst(); } collection.setId( fakeServerData->nextCollectionId() ); collection.setName( QString("Collection %1").arg( collection.id() ) ); collection.setRemoteId( QString( "remoteId %1" ).arg( collection.id() ) ); if ( depth == 0 ) collection.setParentCollection( Collection::root() ); else collection.setParentCollection( recentCollections.at( depth ) ); if ( recentCollections.size() == ( depth + 1) ) recentCollections.append( collection ); else recentCollections[ depth + 1 ] = collection; int order = 0; if ( !parts.first().isEmpty() ) { QString displayName; QString optionalSection = parts.first().trimmed(); if ( optionalSection.startsWith( QLatin1Char( '\'' ) ) ) { optionalSection.remove( 0, 1 ); QStringList optionalParts = optionalSection.split( QLatin1Char( '\'' ) ); displayName = optionalParts.takeFirst(); EntityDisplayAttribute *eda = new EntityDisplayAttribute(); eda->setDisplayName( displayName ); collection.addAttribute( eda ); optionalSection = optionalParts.first(); } QString orderString = optionalSection.trimmed(); if ( !orderString.isEmpty() ) { bool ok; order = orderString.toInt(&ok); Q_ASSERT(ok); } } else { order = 1; } while ( collectionResponseList.size() < order ) { collectionResponseList.append( new FakeJobResponse( recentCollections[ depth ], FakeJobResponse::RespondToCollectionFetch, fakeServerData ) ); } collectionResponseList[ order - 1 ]->appendCollection( collection ); } if ( entityString.startsWith( 'I' ) ) { Item item; entityString.remove( 0, 2 ); entityString = entityString.trimmed(); QString type; int order = 0; int iFirstSpace = entityString.indexOf( QLatin1Char( ' ' ) ); type = entityString.left( iFirstSpace ); entityString = entityString.remove( 0, iFirstSpace + 1 ).trimmed(); if ( iFirstSpace > 0 && !entityString.isEmpty() ) { QString displayName; QString optionalSection = entityString; if ( optionalSection.startsWith( QLatin1Char( '\'' ) ) ) { optionalSection.remove( 0, 1 ); QStringList optionalParts = optionalSection.split( QLatin1Char( '\'' ) ); displayName = optionalParts.takeFirst(); EntityDisplayAttribute *eda = new EntityDisplayAttribute(); eda->setDisplayName( displayName ); item.addAttribute( eda ); optionalSection = optionalParts.first(); } QString orderString = optionalSection.trimmed(); if ( !orderString.isEmpty() ) { bool ok; order = orderString.toInt( &ok ); Q_ASSERT( ok ); } } else type = entityString; item.setMimeType( type ); item.setId( fakeServerData->nextItemId() ); item.setRemoteId( QString( "RId_%1 %2" ).arg( item.id() ).arg(type) ); item.setParentCollection( recentCollections.at( depth ) ); Collection::Id colId = recentCollections[ depth ].id(); if ( !itemResponseMap.contains( colId ) ) { FakeJobResponse *newResponse = new FakeJobResponse( recentCollections[ depth ], FakeJobResponse::RespondToItemFetch, fakeServerData ); itemResponseMap.insert( colId, newResponse ); collectionResponseList.append( newResponse ); } itemResponseMap[ colId ]->appendItem( item ); } }
void QgsGml::endElement( const XML_Char* el ) { QString elementName( QString::fromUtf8( el ) ); ParseMode theParseMode( mParseModeStack.isEmpty() ? none : mParseModeStack.top() ); QStringList splitName = elementName.split( NS_SEPARATOR ); QString localName = splitName.last(); QString ns = splitName.size() > 1 ? splitName.first() : ""; if ( theParseMode == coordinate && elementName == GML_NAMESPACE + NS_SEPARATOR + "coordinates" ) { mParseModeStack.pop(); } else if ( theParseMode == attribute && localName == mAttributeName ) //add a thematic attribute to the feature { mParseModeStack.pop(); //find index with attribute name QMap<QString, QPair<int, QgsField> >::const_iterator att_it = mThematicAttributes.find( mAttributeName ); if ( att_it != mThematicAttributes.constEnd() ) { QVariant var; switch ( att_it.value().second.type() ) { case QVariant::Double: var = QVariant( mStringCash.toDouble() ); break; case QVariant::Int: var = QVariant( mStringCash.toInt() ); break; case QVariant::LongLong: var = QVariant( mStringCash.toLongLong() ); break; default: //string type is default var = QVariant( mStringCash ); break; } Q_ASSERT( mCurrentFeature ); mCurrentFeature->setAttribute( att_it.value().first, QVariant( mStringCash ) ); } } else if ( theParseMode == geometry && localName == mGeometryAttribute ) { mParseModeStack.pop(); } else if ( theParseMode == boundingBox && elementName == GML_NAMESPACE + NS_SEPARATOR + "boundedBy" ) { //create bounding box from mStringCash if ( createBBoxFromCoordinateString( mCurrentExtent, mStringCash ) != 0 ) { QgsDebugMsg( "creation of bounding box failed" ); } mParseModeStack.pop(); } else if ( theParseMode == feature && localName == mTypeName ) { Q_ASSERT( mCurrentFeature ); if ( mCurrentWKBSize > 0 ) { mCurrentFeature->setGeometryAndOwnership( mCurrentWKB, mCurrentWKBSize ); } else if ( !mCurrentExtent.isEmpty() ) { mCurrentFeature->setGeometry( QgsGeometry::fromRect( mCurrentExtent ) ); } else { mCurrentFeature->setGeometry( 0 ); } mCurrentFeature->setValid( true ); mFeatures.insert( mCurrentFeature->id(), mCurrentFeature ); if ( !mCurrentFeatureId.isEmpty() ) { mIdMap.insert( mCurrentFeature->id(), mCurrentFeatureId ); } mCurrentFeature = 0; ++mFeatureCount; mParseModeStack.pop(); } else if ( elementName == GML_NAMESPACE + NS_SEPARATOR + "Point" ) { QList<QgsPoint> pointList; if ( pointsFromCoordinateString( pointList, mStringCash ) != 0 ) { //error } if ( theParseMode == QgsGml::geometry ) { //directly add WKB point to the feature if ( getPointWKB( &mCurrentWKB, &mCurrentWKBSize, *( pointList.begin() ) ) != 0 ) { //error } if ( *mWkbType != QGis::WKBMultiPoint ) //keep multitype in case of geometry type mix { *mWkbType = QGis::WKBPoint; } } else //multipoint, add WKB as fragment { unsigned char* wkb = 0; int wkbSize = 0; QList<unsigned char*> wkbList; QList<int> wkbSizeList; if ( getPointWKB( &wkb, &wkbSize, *( pointList.begin() ) ) != 0 ) { //error } if ( !mCurrentWKBFragments.isEmpty() ) { mCurrentWKBFragments.last().push_back( wkb ); mCurrentWKBFragmentSizes.last().push_back( wkbSize ); } else { QgsDebugMsg( "No wkb fragments" ); } } } else if ( elementName == GML_NAMESPACE + NS_SEPARATOR + "LineString" ) { //add WKB point to the feature QList<QgsPoint> pointList; if ( pointsFromCoordinateString( pointList, mStringCash ) != 0 ) { //error } if ( theParseMode == QgsGml::geometry ) { if ( getLineWKB( &mCurrentWKB, &mCurrentWKBSize, pointList ) != 0 ) { //error } if ( *mWkbType != QGis::WKBMultiLineString )//keep multitype in case of geometry type mix { *mWkbType = QGis::WKBLineString; } } else //multiline, add WKB as fragment { unsigned char* wkb = 0; int wkbSize = 0; QList<unsigned char*> wkbList; QList<int> wkbSizeList; if ( getLineWKB( &wkb, &wkbSize, pointList ) != 0 ) { //error } if ( !mCurrentWKBFragments.isEmpty() ) { mCurrentWKBFragments.last().push_back( wkb ); mCurrentWKBFragmentSizes.last().push_back( wkbSize ); } else { QgsDebugMsg( "no wkb fragments" ); } } } else if (( theParseMode == geometry || theParseMode == multiPolygon ) && elementName == GML_NAMESPACE + NS_SEPARATOR + "LinearRing" ) { QList<QgsPoint> pointList; if ( pointsFromCoordinateString( pointList, mStringCash ) != 0 ) { //error } unsigned char* wkb = 0; int wkbSize = 0; if ( getRingWKB( &wkb, &wkbSize, pointList ) != 0 ) { //error } if ( !mCurrentWKBFragments.isEmpty() ) { mCurrentWKBFragments.last().push_back( wkb ); mCurrentWKBFragmentSizes.last().push_back( wkbSize ); } else { QgsDebugMsg( "no wkb fragments" ); } } else if (( theParseMode == geometry || theParseMode == multiPolygon ) && elementName == GML_NAMESPACE + NS_SEPARATOR + "Polygon" ) { if ( *mWkbType != QGis::WKBMultiPolygon )//keep multitype in case of geometry type mix { *mWkbType = QGis::WKBPolygon; } if ( theParseMode == geometry ) { createPolygonFromFragments(); } } else if ( theParseMode == multiPoint && elementName == GML_NAMESPACE + NS_SEPARATOR + "MultiPoint" ) { *mWkbType = QGis::WKBMultiPoint; mParseModeStack.pop(); createMultiPointFromFragments(); } else if ( theParseMode == multiLine && elementName == GML_NAMESPACE + NS_SEPARATOR + "MultiLineString" ) { *mWkbType = QGis::WKBMultiLineString; mParseModeStack.pop(); createMultiLineFromFragments(); } else if ( theParseMode == multiPolygon && elementName == GML_NAMESPACE + NS_SEPARATOR + "MultiPolygon" ) { *mWkbType = QGis::WKBMultiPolygon; mParseModeStack.pop(); createMultiPolygonFromFragments(); } }
void QgsGml::startElement( const XML_Char* el, const XML_Char** attr ) { QString elementName( QString::fromUtf8( el ) ); ParseMode theParseMode( mParseModeStack.isEmpty() ? none : mParseModeStack.top() ); QStringList splitName = elementName.split( NS_SEPARATOR ); QString localName = splitName.last(); QString ns = splitName.size() > 1 ? splitName.first() : ""; if ( elementName == GML_NAMESPACE + NS_SEPARATOR + "coordinates" ) { mParseModeStack.push( QgsGml::coordinate ); mStringCash.clear(); mCoordinateSeparator = readAttribute( "cs", attr ); if ( mCoordinateSeparator.isEmpty() ) { mCoordinateSeparator = ","; } mTupleSeparator = readAttribute( "ts", attr ); if ( mTupleSeparator.isEmpty() ) { mTupleSeparator = " "; } } else if ( localName == mGeometryAttribute ) { mParseModeStack.push( QgsGml::geometry ); } //else if ( mParseModeStack.size() == 0 && elementName == GML_NAMESPACE + NS_SEPARATOR + "boundedBy" ) else if ( elementName == GML_NAMESPACE + NS_SEPARATOR + "boundedBy" ) { mParseModeStack.push( QgsGml::boundingBox ); } else if ( theParseMode == none && localName == mTypeName ) { Q_ASSERT( !mCurrentFeature ); mCurrentFeature = new QgsFeature( mFeatureCount ); QgsAttributes attributes( mThematicAttributes.size() ); //add empty attributes mCurrentFeature->setAttributes( attributes ); mParseModeStack.push( QgsGml::feature ); mCurrentFeatureId = readAttribute( "fid", attr ); } else if ( theParseMode == boundingBox && elementName == GML_NAMESPACE + NS_SEPARATOR + "Box" ) { //read attribute srsName="EPSG:26910" int epsgNr; if ( readEpsgFromAttribute( epsgNr, attr ) != 0 ) { QgsDebugMsg( "error, could not get epsg id" ); } } else if ( elementName == GML_NAMESPACE + NS_SEPARATOR + "Polygon" ) { mCurrentWKBFragments.push_back( QList<unsigned char*>() ); mCurrentWKBFragmentSizes.push_back( QList<int>() ); } else if ( elementName == GML_NAMESPACE + NS_SEPARATOR + "MultiPoint" ) { mParseModeStack.push( QgsGml::multiPoint ); //we need one nested list for intermediate WKB mCurrentWKBFragments.push_back( QList<unsigned char*>() ); mCurrentWKBFragmentSizes.push_back( QList<int>() ); } else if ( elementName == GML_NAMESPACE + NS_SEPARATOR + "MultiLineString" ) { mParseModeStack.push( QgsGml::multiLine ); //we need one nested list for intermediate WKB mCurrentWKBFragments.push_back( QList<unsigned char*>() ); mCurrentWKBFragmentSizes.push_back( QList<int>() ); } else if ( elementName == GML_NAMESPACE + NS_SEPARATOR + "MultiPolygon" ) { mParseModeStack.push( QgsGml::multiPolygon ); } else if ( theParseMode == feature && mThematicAttributes.contains( localName ) ) { mParseModeStack.push( QgsGml::attribute ); mAttributeName = localName; mStringCash.clear(); } }
void Amarok::coverContextMenu( QWidget *parent, QPoint point, const QString &artist, const QString &album, bool showCoverManager ) { KPopupMenu menu; enum { SHOW, FETCH, CUSTOM, DELETE, MANAGER }; menu.insertTitle( i18n( "Cover Image" ) ); menu.insertItem( SmallIconSet( Amarok::icon( "zoom" ) ), i18n( "&Show Fullsize" ), SHOW ); menu.insertItem( SmallIconSet( Amarok::icon( "download" ) ), i18n( "&Fetch From amazon.%1" ).arg( CoverManager::amazonTld() ), FETCH ); menu.insertItem( SmallIconSet( Amarok::icon( "files" ) ), i18n( "Set &Custom Cover" ), CUSTOM ); bool disable = !album.isEmpty(); // disable setting covers for unknown albums menu.setItemEnabled( FETCH, disable ); menu.setItemEnabled( CUSTOM, disable ); menu.insertSeparator(); menu.insertItem( SmallIconSet( Amarok::icon( "remove" ) ), i18n( "&Unset Cover" ), DELETE ); if ( showCoverManager ) { menu.insertSeparator(); menu.insertItem( SmallIconSet( Amarok::icon( "covermanager" ) ), i18n( "Cover &Manager" ), MANAGER ); } #ifndef AMAZON_SUPPORT menu.setItemEnabled( FETCH, false ); #endif disable = !CollectionDB::instance()->albumImage( artist, album, 0 ).contains( "nocover" ); menu.setItemEnabled( SHOW, disable ); menu.setItemEnabled( DELETE, disable ); switch( menu.exec( point ) ) { case SHOW: CoverManager::viewCover( artist, album, parent ); break; case DELETE: { const int button = KMessageBox::warningContinueCancel( parent, i18n( "Are you sure you want to remove this cover from the Collection?" ), QString::null, KStdGuiItem::del() ); if ( button == KMessageBox::Continue ) CollectionDB::instance()->removeAlbumImage( artist, album ); break; } case FETCH: #ifdef AMAZON_SUPPORT CollectionDB::instance()->fetchCover( parent, artist, album, false ); break; #endif case CUSTOM: { QString artist_id; artist_id.setNum( CollectionDB::instance()->artistID( artist ) ); QString album_id; album_id.setNum( CollectionDB::instance()->albumID( album ) ); QStringList values = CollectionDB::instance()->albumTracks( artist_id, album_id ); QString startPath = ":homedir"; if ( !values.isEmpty() ) { KURL url; url.setPath( values.first() ); startPath = url.directory(); } KURL file = KFileDialog::getImageOpenURL( startPath, parent, i18n("Select Cover Image File") ); if ( !file.isEmpty() ) CollectionDB::instance()->setAlbumImage( artist, album, file ); break; } case MANAGER: CoverManager::showOnce( album ); break; } }
bool StopSpam::processMuc(int account, const QDomElement& stanza) { if(stanza.tagName() == "presence") { QStringList jidList = stanza.attribute("from").split("/"); int i = mucUsers_.size(); if(findMuc(jidList.first(),jidList.last(), i)) { MucUser &mu = mucUsers_[i]; QDomNodeList nodeList = stanza.elementsByTagName("x"); for(int i = nodeList.size(); i> 0;) { QDomNode node = nodeList.at(--i).firstChild(); while(!node.isNull()) { QDomElement item = node.toElement(); if(item.tagName() == "item") { mu.affiliation = item.attribute("affiliation"); mu.role = item.attribute("role"); mu.jid = item.attribute("jid"); break; } node = node.nextSibling(); } } } else { MucUser mu; mu.mucJid = jidList.first(); mu.nick = jidList.last(); QDomNodeList nodeList = stanza.elementsByTagName("x"); for(int i = nodeList.size(); i> 0;) { QDomNode node = nodeList.at(--i).firstChild(); while(!node.isNull()) { QDomElement item = node.toElement(); if(item.tagName() == "item") { mu.affiliation = item.attribute("affiliation"); mu.role = item.attribute("role"); mu.jid = item.attribute("jid"); break; } node = node.nextSibling(); } } mucUsers_ << mu; } } else if(stanza.tagName() == "message" && stanza.attribute("type") == "chat") { QDomElement subj = stanza.firstChildElement("subject"); if (subj.text() == "StopSpam" || subj.text() == "StopSpam Question") return false; QString valF = stanza.attribute("from"); if (contactInfo->isConference(account, valF)) return false; MucUser mu; QStringList jidList = valF.split("/"); int i = mucUsers_.size(); if(findMuc(jidList.first(),jidList.last(), i)) { mu = mucUsers_[i]; } else { mu.affiliation = ""; mu.jid = ""; mu.mucJid = ""; mu.nick = ""; mu.role = ""; } bool find = false; if(mu.affiliation == "owner" && !Owner) find = true; else if( mu.affiliation == "admin" && !Admin) find = true; else if(mu.affiliation == "none" && !None) find = true; else if(mu.affiliation == "member" && !Member) find = true; if(find) return false; if(mu.role == "moderator" && !Moder) find = true; else if(mu.role == "participant" && !Participant) find = true; else if(mu.role == "visitor" && !Visitor) find = true; if(find) return false; QStringList UnblockedJids = Unblocked.split("\n"); if(UnblockedJids.contains(valF, Qt::CaseInsensitive)) return false; for(int i = 0; i < Jids.size(); i++) { QString jid_ = Jids.at(i); if(jid_.isEmpty()) continue; if(mu.jid.contains(jid_, Qt::CaseInsensitive) || mu.nick.contains(jid_, Qt::CaseInsensitive) || mu.mucJid.contains(jid_, Qt::CaseInsensitive)) { if(!selected[i].toBool()) return false; break; } } QDomElement Body = stanza.firstChildElement("body"); if(Body.isNull()) return false; if(BlockAll) { updateCounter(stanza, false); if(EnableBlockAllMes) stanzaHost->sendMessage(account, valF, BlockAllMes, "StopSpam", "chat"); return true; } QString BodyText = Body.text(); if(BodyText == Answer) { Unblocked += valF + "\n"; QVariant vUnblocked(Unblocked); psiOptions->setPluginOption(constUnblocked, vUnblocked); psiOptions->setPluginOption(constLastUnblock, QVariant(QDate::currentDate().toString("yyyyMMdd"))); stanzaHost->sendMessage(account, valF, Congratulation, "StopSpam", "chat"); updateCounter(stanza, true); return true; } else { int i = BlockedJids.size(); if(findAcc(account, valF, i)) { Blocked &B = BlockedJids[i]; if(B.count < Times) { stanzaHost->sendMessage(account, valF, Question, "StopSpam Question", "chat"); updateCounter(stanza, false); B.count++; B.LastMes = QDateTime::currentDateTime(); return true; } else { if(QDateTime::currentDateTime().secsTo(B.LastMes) >= -ResetTime*60) { updateCounter(stanza, false); return true; } else { B.count = 1; B.LastMes = QDateTime::currentDateTime(); stanzaHost->sendMessage(account, valF, Question, "StopSpam Question", "chat"); updateCounter(stanza, false); return true; } } } else { Blocked B = { account, valF, 1, QDateTime::currentDateTime() }; BlockedJids << B; stanzaHost->sendMessage(account, valF, Question, "StopSpam Question", "chat"); updateCounter(stanza, false); return true; } } } return false; }
/** add the given key and value @param scope scope of key @param key key name @param rootProperty is the property from which to start adding @param value the value associated with the key */ static QgsProperty * addKey_( QString const & scope, QString const & key, QgsPropertyKey * rootProperty, QVariant value ) { QStringList keySequence = makeKeyTokens_( scope, key ); // cursor through property key/value hierarchy QgsPropertyKey * currentProperty = rootProperty; QgsProperty * newProperty; // link to next property down hiearchy while ( ! keySequence.isEmpty() ) { // if the current head of the sequence list matches the property name, // then traverse down the property hierarchy if ( keySequence.first() == currentProperty->name() ) { // remove front key since we're traversing down a level keySequence.pop_front(); // if key sequence has one last element, then we use that as the // name to store the value if ( 1 == keySequence.count() ) { currentProperty->setValue( keySequence.front(), value ); return currentProperty; } // we're at the top element if popping the keySequence element // will leave it empty; in that case, just add the key else if ( keySequence.isEmpty() ) { currentProperty->setValue( value ); return currentProperty; } else if (( newProperty = currentProperty->find( keySequence.first() ) ) ) { currentProperty = dynamic_cast<QgsPropertyKey*>( newProperty ); if ( currentProperty ) { continue; } else // QgsPropertyValue not Key, so return null { return 0x0; } } else // the next subkey doesn't exist, so add it { newProperty = currentProperty->addKey( keySequence.first() ); if ( newProperty ) { currentProperty = dynamic_cast<QgsPropertyKey*>( newProperty ); } continue; } } else { return 0x0; } } return 0x0; } // addKey_
bool KexiFileWidget::checkSelectedFile() { //accept(); // KUrl url = currentURL(); // QString path = url.path().trimmed(); // QString path = selectedFile().trimmed(); kDebug() << "d->highlightedUrl: " << d->highlightedUrl; if (/*d->highlightedUrl.isEmpty() &&*/ !locationEdit()->lineEdit()->text().isEmpty()) { kDebug() << locationEdit()->lineEdit()->text(); //kDebug() << locationEdit()->urls(); kDebug() << baseUrl(); d->highlightedUrl = baseUrl(); const QString firstUrl(locationEdit()->lineEdit()->text()); // FIXME: find first... if (QDir::isAbsolutePath(firstUrl)) d->highlightedUrl = KUrl::fromPath(firstUrl); else d->highlightedUrl.addPath(firstUrl); } kDebug() << "d->highlightedUrl: " << d->highlightedUrl; // if (url.fileName().trimmed().isEmpty()) { if (d->highlightedUrl.isEmpty()) { KMessageBox::error(this, i18n("Enter a filename.")); return false; } if (!currentFilter().isEmpty()) { if (d->mode & SavingFileBasedDB) { const QStringList filters( currentFilter().split(" ") ); QString path = highlightedFile(); kDebug()<< "filter:" << filters << "path:" << path; QString ext( QFileInfo(path).suffix() ); bool hasExtension = false; foreach (const QString& filter, filters) { const QString f( filter.trimmed() ); hasExtension = !f.mid(2).isEmpty() && ext==f.mid(2); if (hasExtension) break; } if (!hasExtension) { //no extension: add one QString defaultExtension( d->defaultExtension ); if (defaultExtension.isEmpty()) { defaultExtension = filters.first().trimmed().mid(2); //first one } path += (QLatin1String(".")+defaultExtension); kDebug() << "appended extension" << path; setSelection( path ); d->highlightedUrl = KUrl(path); } } } kDebug() << "KexiFileWidget::checkURL() path: " << d->highlightedUrl; // kDebug() << "KexiFileWidget::checkURL() fname: " << url.fileName(); //todo if ( url.isLocalFile() ) { QFileInfo fi(d->highlightedUrl.toLocalFile()); if (mode() & KFile::ExistingOnly) { if (!fi.exists()) { KMessageBox::error(this, "<qt>" + i18n("The file \"%1\" does not exist.", QDir::convertSeparators(d->highlightedUrl.toLocalFile()))); return false; } else if (mode() & KFile::File) { if (!fi.isFile()) { KMessageBox::error(this, "<qt>" + i18n("Enter a filename.")); return false; } else if (!fi.isReadable()) { KMessageBox::error(this, "<qt>" + i18n("The file \"%1\" is not readable.", QDir::convertSeparators(d->highlightedUrl.path()))); return false; } } } else if (d->confirmOverwrites && !askForOverwriting(d->highlightedUrl.path(), this)) { return false; } // } return true; }
bool QgsProjectBadLayerGuiHandler::findMissingFile( QString const & fileFilters, QDomNode & layerNode ) { // Prepend that file name to the valid file format filter list since it // makes it easier for the user to not only find the original file, but to // perhaps find a similar file. QFileInfo originalDataSource( dataSource( layerNode ) ); QString memoryQualifier; // to differentiate between last raster and // vector directories switch ( dataType( layerNode ) ) { case IS_VECTOR: { memoryQualifier = "lastVectorFileFilter"; break; } case IS_RASTER: { memoryQualifier = "lastRasterFileFilter"; break; } default: QgsDebugMsg( "unable to determine data type" ); return false; } // Prepend the original data source base name to make it easier to pick it // out from a list of other files; however the appropriate filter strings // for the file type will also be added in case the file name itself has // changed, too. QString myFileFilters = originalDataSource.fileName() + ";;" + fileFilters; QStringList selectedFiles; QString enc; QString title = QObject::tr( "Where is '%1' (original location: %2)?" ) .arg( originalDataSource.fileName(), originalDataSource.absoluteFilePath() ); bool retVal = QgisGui::openFilesRememberingFilter( memoryQualifier, myFileFilters, selectedFiles, enc, title, true ); if ( selectedFiles.isEmpty() ) { return retVal; } else { setDataSource( layerNode, selectedFiles.first() ); if ( ! QgsProject::instance()->read( layerNode ) ) { QgsDebugMsg( "unable to re-read layer" ); } } return retVal; } // findMissingFile
bool parseAricoinURI(const QUrl &uri, SendCoinsRecipient *out) { // return if URI is not valid or is no aricoin: URI if(!uri.isValid() || uri.scheme() != QString("aricoin")) return false; SendCoinsRecipient rv; QStringList addressParts = uri.path().split("/", QString::SkipEmptyParts, Qt::CaseSensitive); rv.address = addressParts.isEmpty() ? "" : addressParts.first(); rv.amount = 0; #if QT_VERSION < 0x050000 QList<QPair<QString, QString> > items = uri.queryItems(); #else QUrlQuery uriQuery(uri); QList<QPair<QString, QString> > items = uriQuery.queryItems(); #endif for (QList<QPair<QString, QString> >::iterator i = items.begin(); i != items.end(); i++) { bool fShouldReturnFalse = false; if (i->first.startsWith("req-")) { i->first.remove(0, 4); fShouldReturnFalse = true; } if (i->first == "label") { rv.label = i->second; fShouldReturnFalse = false; } if (i->first == "message") { rv.message = i->second; fShouldReturnFalse = false; } else if (i->first == "amount") { if(!i->second.isEmpty()) { // Parse amount in C locale with no number separators QLocale locale(QLocale::c()); locale.setNumberOptions(QLocale::OmitGroupSeparator | QLocale::RejectGroupSeparator); if(!AricoinUnits::parse(AricoinUnits::ARI, i->second, &rv.amount, locale)) { return false; } } fShouldReturnFalse = false; } if (fShouldReturnFalse) return false; } if(out) { *out = rv; } return true; }
int PMInsertRuleSystem::canInsert( const PMObject* parentObject, const QStringList& list, const PMObject* after ) { if( list.size( ) == 1 ) { // more efficient if( canInsert( parentObject, list.first( ), after ) ) return 1; else return 0; } // find rules for target class QPtrList<PMRuleTargetClass> targetClassList; PMMetaObject* meta = parentObject->metaObject( ); for( ; meta; meta = meta->superClass( ) ) { PMRuleTargetClass* tc = m_rulesDict.find( meta->className( ) ); if( tc ) targetClassList.append( tc ); } if( targetClassList.isEmpty( ) ) return 0; // not rules found // count already inserted children QPtrListIterator<PMRuleTargetClass> tit( targetClassList ); for( ; tit.current( ); ++tit ) // ... for all target classes { QPtrListIterator<PMRule> rit = tit.current( )->rules( ); for( ; rit.current( ); ++rit ) // ... and all rules { rit.current( )->reset( ); bool afterInsertPoint = false; PMObject* o = parentObject->firstChild( ); if( !after ) afterInsertPoint = true; for( ; o; o = o->nextSibling( ) ) { rit.current( )->countChild( o->className( ), afterInsertPoint ); if( o == after ) afterInsertPoint = true; } } } int number = 0; QStringList::const_iterator oit; for( oit = list.begin( ); oit != list.end( ); ++oit ) { bool possible = false; for( tit.toFirst( ); tit.current( ) && !possible; ++tit ) { QPtrListIterator<PMRule> rit = tit.current( )->rules( ); for( ; rit.current( ) && !possible; ++rit ) { PMRule* rule = rit.current( ); if( rule->matches( *oit ) ) possible = rule->evaluate( parentObject ); } } if( possible ) { // object can be inserted, count it for( ; tit.current( ); ++tit ) { QPtrListIterator<PMRule> rit = tit.current( )->rules( ); for( ; rit.current( ); ++rit ) rit.current( )->countChild( *oit, false ); } number++; } } return number; }
void PowerDevilRunner::match(Sprinter::MatchData &matchData) { const QString term = matchData.queryContext().query(); PowerDevilWord word = NoWord; for (auto it = m_words.cbegin(); it != m_words.cend(); ++it) { if (term.startsWith(it.value(), Qt::CaseInsensitive)) { word = it.key(); break; } } // extracts the parameters from the given term auto getParameters = [&term](const QString &word) -> QStringList { QString adjustedTerm = term; adjustedTerm.remove(0, word.length()); return adjustedTerm.trimmed().split(' ', QString::SkipEmptyParts); }; switch (word) { case SuspendWord: { const QSet<Solid::PowerManagement::SleepState> states = Solid::PowerManagement::supportedSleepStates(); if (states.contains(Solid::PowerManagement::SuspendState)) { addMatch(SuspendAction, matchData); } if (states.contains(Solid::PowerManagement::HibernateState)) { addMatch(HibernateAction, matchData); } } break; case SleepWord: case ToRamWord: addMatch(SuspendAction, matchData); break; case HibernateWord: case ToDiskWord: addMatch(HibernateAction, matchData); break; case ScreenBrightnessWord: case DimScreenWord: { const QStringList parameters = getParameters(m_words.value(word)); int brightness; bool brightnessValid = false; if (!parameters.isEmpty()) { brightness = parameters.first().toInt(&brightnessValid); } if (brightnessValid) { addBrightnessMatch(brightness, matchData); } else { addMatch(DimTotalAction, matchData); addMatch(DimHalfAction, matchData); addMatch(DimNotAction, matchData); } } break; default: // No match found break; } }
void Image::postSaving(const QString &path, bool addMd5, bool startCommands, int count, bool basic) { if (addMd5) { m_profile->addMd5(md5(), path); } // Save info to a text file if (!basic) { auto logFiles = getExternalLogFiles(m_settings); for (auto it = logFiles.begin(); it != logFiles.end(); ++it) { auto logFile = it.value(); QString textfileFormat = logFile["content"].toString(); QStringList cont = this->path(textfileFormat, "", count, true, true, false, false, false); if (!cont.isEmpty()) { int locationType = logFile["locationType"].toInt(); QString contents = cont.first(); // File path QString fileTagsPath; if (locationType == 0) fileTagsPath = this->path(logFile["filename"].toString(), logFile["path"].toString(), 0, true, false, true, true, true).first(); else if (locationType == 1) fileTagsPath = logFile["uniquePath"].toString(); else if (locationType == 2) fileTagsPath = path + logFile["suffix"].toString(); // Replace some post-save tokens contents.replace("%path:nobackslash%", QDir::toNativeSeparators(path).replace("\\", "/")) .replace("%path%", QDir::toNativeSeparators(path)); // Append to file if necessary QFile fileTags(fileTagsPath); bool append = fileTags.exists(); if (fileTags.open(QFile::WriteOnly | QFile::Append | QFile::Text)) { if (append) fileTags.write("\n"); fileTags.write(contents.toUtf8()); fileTags.close(); } } } } // Keep original date if (m_settings->value("Save/keepDate", true).toBool()) setFileCreationDate(path, createdAt()); // Commands Commands &commands = m_profile->getCommands(); if (startCommands) { commands.before(); } for (const Tag &tag : qAsConst(m_tags)) { commands.tag(*this, tag, false); } commands.image(*this, path); for (const Tag &tag : qAsConst(m_tags)) { commands.tag(*this, tag, true); } if (startCommands) { commands.after(); } setSavePath(path); }
void VM_Viewer::resendExecMethod(const QStringList &method) { QStringList args; args.append(domain); TASK task; task.type = "domain"; task.srcConnPtr = ptr_ConnPtr; task.srcConName = connName; task.object = domain; if ( method.first()=="startVirtDomain" ) { task.method = method.first(); task.action = START_ENTITY; emit addNewTask(task); } else if ( method.first()=="pauseVirtDomain" ) { task.method = method.first(); task.action = PAUSE_ENTITY; task.args.state = VM_State ? 1 : 0; emit addNewTask(task); } else if ( method.first()=="destroyVirtDomain" ) { task.method = method.first(); task.action = DESTROY_ENTITY; emit addNewTask(task); } else if ( method.first()=="resetVirtDomain" ) { task.method = method.first(); task.action = RESET_ENTITY; emit addNewTask(task); } else if ( method.first()=="shutdownVirtDomain" ) { task.method = method.first(); task.action = SHUTDOWN_ENTITY; emit addNewTask(task); } else if ( method.first()=="saveVirtDomain" ) { QString to = QFileDialog::getSaveFileName(this, "Save to", "~"); if ( !to.isEmpty() ) { task.method = method.first(); task.action = SAVE_ENTITY; task.args.path = to; task.args.state = VM_State ? 1 : 0; emit addNewTask(task); }; } else if ( method.first()=="restoreVirtDomain" ) { QString from = QFileDialog::getOpenFileName(this, "Restore from", "~"); if ( !from.isEmpty() ) { task.method = method.first(); task.action = RESTORE_ENTITY; task.args.path = from; emit addNewTask(task); }; } else if ( method.first()=="createVirtDomainSnapshot" ) { //qDebug()<<"createVirtDomainSnapshot"; CreateSnapshotDialog *_dialog = new CreateSnapshotDialog( this, domain, true, ptr_ConnPtr); connect(_dialog, SIGNAL(errMsg(QString&)), this, SLOT(sendErrMsg(QString&))); int exitCode = _dialog->exec(); disconnect(_dialog, SIGNAL(errMsg(QString&)), this, SLOT(sendErrMsg(QString&))); _dialog->deleteLater(); if ( exitCode ) { task.action = CREATE_DOMAIN_SNAPSHOT; task.method = "createVirtDomainSnapshot"; task.args.object = _dialog->getSnapshotXMLDesc(); task.args.sign = _dialog->getSnapshotFlags(); emit addNewTask(task); }; } else if ( method.first()=="moreSnapshotActions" ) {
int AirspaceHelper::loadAirspaces( QList<Airspace>& list ) { // Set a global lock during execution to avoid calls in parallel. QMutexLocker locker( &m_mutex ); QTime t; t.start(); uint loadCounter = 0; // number of successfully loaded files m_airspaceDictionary.clear(); QString mapDir = MapContents::instance()->getMapRootDirectory() + "/airspaces"; QStringList preselect; // Setup a filter for the desired file extensions. QString filter = "*.txt *.TXT *.aip"; MapContents::addDir( preselect, mapDir, filter ); if( preselect.count() == 0 ) { qWarning( "ASH: No Airspace files found in the map directory!" ); return loadCounter; } // Check, which files shall be loaded. QStringList files = _settings.value( "/Airspace/FileList", QStringList(QString("All"))).toStringList(); if( files.isEmpty() ) { // No files shall be loaded qWarning() << "ASH: No Airspace files defined for loading!"; return loadCounter; } if( files.first() != "All" ) { // Check for desired files to be loaded. All other items are removed from // the files list. for( int i = preselect.size() - 1; i >= 0; i-- ) { QString file = QFileInfo(preselect.at(i)).fileName(); if( files.contains( file ) == false ) { preselect.removeAt(i); } } } OpenAirParser oap; OpenAip oaip; QString errorInfo; while( ! preselect.isEmpty() ) { QString srcName; if( preselect.first().endsWith(QString(".TXT")) || preselect.first().endsWith(QString(".txt")) ) { srcName = preselect.first(); if( oap.parse(srcName, list) ) { loadCounter++; } preselect.removeAt(0); continue; } if( preselect.first().endsWith(QString(".aip")) ) { // there can't be the same name aic after this aip // parse found aip file srcName = preselect.first(); if( oaip.readAirspaces(srcName, list, errorInfo ) ) { loadCounter++; } preselect.removeAt(0); continue; } } // End of While qDebug("ASH: %d Airspace file(s) loaded in %dms", loadCounter, t.elapsed()); // for(int i=0; i < list.size(); i++ ) // { // list.at(i)->debug(); // } return loadCounter; }
void Node::joinConns( int c0, int c1 ) { Pin* pin0 = m_pin[c0]; Pin* pin1 = m_pin[c1]; Connector* con0 = pin0->connector(); Connector* con1 = pin1->connector(); con0->remNullLines(); con1->remNullLines(); //eNode* enode = con0->enode(); Connector* con = new Connector( this, con0->itemtype(), con0->itemID(), pin0->conPin() ); //con->setEnode( enode ); /*eNode* newEnode = new eNode( enode->itemId() ); QList<ePin*> epins = enode->getEpins(); foreach( ePin* epin, epins ) epin->setEnode( newEnode ); Simulator::self()->remFromEnodeList( enode, true ); // Delete old eNode con->setEnode( newEnode );*/ QStringList list0 = con0->pointList(); QStringList list1 = con1->pointList(); QStringList plist; if( pin0 == con0->startPin() ) while( !list0.isEmpty() ) { QString p2 = list0.takeLast(); plist.append(list0.takeLast()); plist.append(p2); } else while( !list0.isEmpty() ) plist.append(list0.takeFirst()); if( pin1 == con1->endPin() ) while( !list1.isEmpty() ) { QString p2 = list1.takeLast(); plist.append(list1.takeLast()); plist.append(p2); } else while( !list1.isEmpty() ) plist.append(list1.takeFirst()); con->setPointList( plist ); con0->setStartPin(0l); con0->setEndPin(0l); //qDebug() << "Node::joinConns removing con0" << con0->objectName(); con0->remove(); con1->setStartPin(0l); con1->setEndPin(0l); //qDebug() << "Node::joinConns removing con1" << con1->objectName(); con1->remove(); int p1x = plist.first().toInt(); int p1y = plist.at(1).toInt(); int p2x = plist.at(plist.size()-2).toInt(); int p2y = plist.last().toInt(); int p0x = con->startPin()->scenePos().x(); int p0y = con->startPin()->scenePos().y(); con->addConLine( p0x,p0y, p1x, p1y, 0 ); int count = plist.size(); for (int i=2; i<count; i+=2) { p2x = plist.at(i).toInt(); p2y = plist.at(i+1).toInt(); con->addConLine( p1x, p1y, p2x, p2y, i/2 ); p1x = p2x; p1y = p2y; } con->closeCon( pin1->conPin() ); con->remNullLines(); Circuit::self()->addItem( con ); }
void UpdateChecker::resultReceiver(QString data) { QDomDocument xml; qDebug() << data; xml.setContent(data); QDomElement productxml = xml.firstChildElement("product"); if (productxml.isNull()) { QMessageBox::critical(NULL, tr("Error"), tr("Could not check for updates. Wrong server response.")); inProgress = false; return; } QDomElement urlxml = productxml.firstChildElement("url"); QString url = urlxml.text(); QDomNodeList versionsx = xml.elementsByTagName("version"); if (versionsx.length()==0) { QMessageBox::critical(NULL, tr("Error"), tr("Could not check for updates. No versions found.")); inProgress = false; return; } QString platform; #ifdef Q_OS_WIN platform = "WIN"; #endif #ifdef Q_OS_MAC platform = "MAC"; #endif if (platform.isEmpty()) platform = "UNIX"; QStringList versions; QMap<QString, QUrl> urls; for(unsigned int i=0; i<versionsx.length(); i++) { QDomNode version = versionsx.at(i); QDomNode platformx = version.attributes().namedItem("platform"); if (platformx.isNull()) continue; QString vpl = platformx.nodeValue(); if ((vpl != platform) && (vpl != "ALL")) continue; QString ver = version.attributes().namedItem("id").nodeValue(); versions.append(ver); QDomElement xurl = version.toElement().firstChildElement("url"); urls[ver] = QUrl(xurl.text()); } if (!versions.size()) { if (!workSilent) QMessageBox::information(NULL, tr("No updates available"), tr("You have the latest version of this application.")); inProgress = false; return; } qSort( versions.begin(), versions.end(), versionCompare); // I should write Version class with right compare QString version = versions.first(); // operator and use QMap's auto sorting. if (versionCompare(version, QApplication::applicationVersion())) { QMessageBox msg; msg.addButton(tr("Yes"), QMessageBox::YesRole); msg.addButton(tr("No"), QMessageBox::NoRole); msg.setText(tr("Lastest version is %1. Do you want to update?").arg(version)); msg.setWindowTitle(tr("Update available")); msg.exec(); if (msg.buttonRole(msg.clickedButton()) == QMessageBox::YesRole) { QDesktopServices().openUrl(urls[version]); } } else { if (!workSilent) { QMessageBox::information(NULL, tr("No updates available"), tr("You have the latest version of this application.")); } } inProgress = false; }
int main(int argc, char **argv) { QApplication::setOrganizationName("KDAB"); QApplication::setOrganizationDomain("kdab.com"); QApplication::setApplicationName("GammaRay"); QStringList args; for (int i = 1; i < argc; ++i) { args.push_back(QString::fromLocal8Bit(argv[i])); } QApplication app(argc, argv); QStringList builtInArgs = QStringList() << QLatin1String("-style") << QLatin1String("-stylesheet") << QLatin1String("-graphicssystem"); QString injectorType; int pid = -1; while (!args.isEmpty() && args.first().startsWith('-')) { const QString arg = args.takeFirst(); if ((arg == QLatin1String("-i") || arg == QLatin1String("--injector")) && !args.isEmpty()) { injectorType = args.takeFirst(); continue; } if ((arg == QLatin1String("-p") || arg == QLatin1String("--pid")) && !args.isEmpty()) { pid = args.takeFirst().toInt(); continue; } if (arg == QLatin1String("-h") || arg == QLatin1String("--help")) { usage(argv[0]); return 0; } if (arg == QLatin1String("-v") || arg == QLatin1String("--version")) { out << PROGRAM_NAME << " version " << GAMMARAY_VERSION_STRING << endl; out << "Copyright (C) 2010-2012 Klaralvdalens Datakonsult AB, " << "a KDAB Group company, [email protected]" << endl; return 0; } if (arg == QLatin1String("-filtertest")) { qputenv("GAMMARAY_TEST_FILTER", "1"); } if (arg == QLatin1String("-unittest")) { qputenv("GAMMARAY_UNITTEST", "1"); } if (arg == QLatin1String("-modeltest")) { qputenv("GAMMARAY_MODELTEST", "1"); } // built-in arguments of QApp, could be meant for us if we are showing the launcher window foreach (const QString &builtInArg, builtInArgs) { if (arg == builtInArg && !args.isEmpty()) { args.takeFirst(); } } } if (args.isEmpty() && pid <= 0) { LauncherWindow dialog; if (dialog.exec() == QDialog::Accepted) { args = dialog.launchArguments(); bool ok; pid = dialog.pid().toInt(&ok); if (!ok && args.isEmpty()) { return 0; } } else { return 0; } } const QString probeDll = ProbeFinder::findProbe(QLatin1String("gammaray_probe")); qputenv("GAMMARAY_PROBE_PATH", QFileInfo(probeDll).absolutePath().toLocal8Bit()); AbstractInjector::Ptr injector; if (injectorType.isEmpty()) { if (pid > 0) { injector = InjectorFactory::defaultInjectorForAttach(); } else { injector = InjectorFactory::defaultInjectorForLaunch(); } } else { injector = InjectorFactory::createInjector(injectorType); } if (injector) { if (pid > 0) { if (!injector->attach(pid, probeDll, QLatin1String("gammaray_probe_inject"))) { err << "Unable to attach injector " << injector->name() << endl; err << "Exit code: " << injector->exitCode() << endl; if (!injector->errorString().isEmpty()) { err << "Error: " << injector->errorString() << endl; } return 1; } else { return 0; } } else { if (!injector->launch(args, probeDll, QLatin1String("gammaray_probe_inject"))) { err << "Failed to launch injector " << injector->name() << endl; err << "Exit code: " << injector->exitCode() << endl; if (!injector->errorString().isEmpty()) { err << "Error: " << injector->errorString() << endl; } return 1; } return injector->exitCode(); } return 1; } if (injectorType.isEmpty()) { if (pid > 0) { #if defined(Q_OS_WIN) err << "Sorry, but at this time there is no attach injector on the Windows platform" << endl; err << "Only the launch injector windll is available on Windows" << endl; #else err << "Uh-oh, there is no default attach injector" << endl; #endif } else { err << "Uh-oh, there is no default launch injector" << endl; } } else { err << "Injector " << injectorType << " not found." << endl; } return 1; }
QString KeyListProxyModelPrivate::reorderEmailComponents(const QString &emailAddress) const { if (emailAddress.isEmpty()) return QString(); /// split email addresses at @ static const QChar charAt = QLatin1Char('@'); /// split domain at . static const QChar charDot = QLatin1Char('.'); /// convert result to lower case to make sorting case-insensitive QString result = emailAddress.toLower(); switch (m_emailSorting) { case KGpgSettings::EnumEmailSorting::TLDfirst: { /// get components of an email address /// [email protected] becomes [john.doe, mail.kde.org] const QStringList emailComponents = result.split(charAt); if (emailComponents.count() != 2) /// expect an email address to contain exactly one @ break; /// get components of a domain /// mail.kde.org becomes [mail, kde, org] const QString fqdn = emailComponents.last(); QStringList fqdnComponents = fqdn.split(charDot); if (fqdnComponents.count() < 2) /// if domain consists of less than two components ... return fqdn + charDot + emailComponents.first(); /// ... take shortcut /// prepend localpart, will be last after list is reversed fqdnComponents.insert(0, emailComponents.first()); /// reverse components of domain, result becomes e.g. org.kde.mail /// with localpart already in the list it becomes org.kde.mail.john.doe result = reverseListAndJoinWithChar(fqdnComponents, charDot); break; } case KGpgSettings::EnumEmailSorting::DomainFirst: { /// get components of an email address /// [email protected] becomes [john.doe, mail.kde.org] const QStringList emailComponents = result.split(charAt); if (emailComponents.count() != 2) /// expect an email address to contain exactly one @ break; /// get components of a domain /// mail.kde.org becomes [mail, kde, org] const QString fqdn = emailComponents.last(); QStringList fqdnComponents = fqdn.split(charDot); if (fqdnComponents.count() < 2) /// if domain consists of less than two components ... return fqdn + charDot + emailComponents.first(); /// ... take shortcut /// reverse last two components of domain, becomes e.g. kde.org /// TODO will fail for three-part domains like kde.org.uk result = charDot + fqdnComponents.takeLast(); result.prepend(fqdnComponents.takeLast()); /// append remaining components of domain, becomes e.g. kde.org.mail result.append(charDot).append(fqdnComponents.join(charDot)); /// append user name component of email address, becomes e.g. kde.org.mail.john.doe result.append(charDot).append(emailComponents.first()); break; } case KGpgSettings::EnumEmailSorting::FQDNFirst: { /// get components of an email address /// [email protected] becomes [john.doe, mail.kde.org] const QStringList emailComponents = result.split(charAt); /// assemble result by joining components in reverse order, /// separated by a dot, becomes e.g. mail.kde.org.john.doe result = reverseListAndJoinWithChar(emailComponents, charDot); break; } case KGpgSettings::EnumEmailSorting::Alphabetical: /// do not modify email address except for lower-case conversion break; } return result; }
void InitializeMythDirs(void) { installprefix = qgetenv( "MYTHTVDIR" ); confdir = qgetenv( "MYTHCONFDIR" ); if (confdir.length()) { LOG(VB_GENERAL, LOG_NOTICE, QString("Read conf dir = %1").arg(confdir)); confdir.replace("$HOME", QDir::homePath()); } #ifdef _WIN32 if (installprefix.length() == 0) installprefix = QDir( qApp->applicationDirPath() ) .absolutePath(); appbindir = installprefix + "/"; libdir = appbindir; sharedir = qgetenv( "ProgramData" ) + "\\mythtv\\"; if (confdir.length() == 0) confdir = qgetenv( "LOCALAPPDATA" ) + "\\mythtv"; #if 0 // The following code only works for Qt 5.0 and above, but it may // be a generic solution for both windows & linux. // Re-evalute use oce min Qt == 5.0 // QStringList sorted by least public to most. // Assume first is private user data and last is shared program data. qApp->setOrganizationName( "mythtv" ); QStringList lstPaths = QStandardPaths::standardLocations( QStandardPaths::DataLocation); // Remove AppName from end of path if (lstPaths.length() > 0) { QString sAppName = qApp->applicationName(); sharedir = lstPaths.last(); if (sharedir.endsWith( sAppName )) sharedir = sharedir.left( sharedir.length() - sAppName.length()); // Only use if user didn't override with env variable. if (confdir.length() == 0) { confdir = lstPaths.first(); if (confdir.endsWith( sAppName )) confdir = confdir.left( confdir.length() - sAppName.length()); } } #endif if (sharedir.length() == 0) sharedir = confdir; #elif defined(Q_OS_ANDROID) if (installprefix.isEmpty()) installprefix = QDir( qApp->applicationDirPath() ) .absolutePath(); QString extdir = QStandardPaths::writableLocation(QStandardPaths::GenericDataLocation) + "/Mythtv"; if (!QDir(extdir).exists()) QDir(extdir).mkdir("."); if (confdir.isEmpty()) confdir = QStandardPaths::writableLocation(QStandardPaths::AppDataLocation); #if 0 // TODO allow choice of base fs or the SD card for data QStringList appLocs = QStandardPaths::standardLocations(QStandardPaths::AppDataLocation); uint64_t maxFreeSpace = 0; for(auto s : appLocs) { struct statfs statFs; memset(&statFs, 0, sizeof(statFs)); int ret = statfs(s.toLocal8Bit().data(), &statFs); if (ret == 0 && statFs.f_bavail >= maxFreeSpace) { maxFreeSpace = statFs.f_bavail; confdir = s; } LOG(VB_GENERAL, LOG_NOTICE, QString(" appdatadir = %1 (%2, %3, %4)") .arg(s) .arg(statFs.f_bavail) .arg(statFs.f_bfree) .arg(statFs.f_bsize)); } QStringList cacheLocs = QStandardPaths::standardLocations(QStandardPaths::CacheLocation); maxFreeSpace = 0; for(auto s : cacheLocs) { struct statfs statFs; memset(&statFs, 0, sizeof(statFs)); int ret = statfs(s.toLocal8Bit().data(), &statFs); if (ret == 0 && statFs.f_bavail >= maxFreeSpace) { maxFreeSpace = statFs.f_bavail; //confdir = s; } LOG(VB_GENERAL, LOG_NOTICE, QString(" cachedir = %1 (%2, %3, %4)") .arg(s) .arg(statFs.f_bavail) .arg(statFs.f_bfree) .arg(statFs.f_bsize)); } #endif appbindir = installprefix + "/"; sharedir = "assets:/mythtv/"; libdir = installprefix + "/"; #else if (installprefix.length() == 0) installprefix = QString(RUNPREFIX); QDir prefixDir = qApp->applicationDirPath(); if (QDir(installprefix).isRelative()) { // If the PREFIX is relative, evaluate it relative to our // executable directory. This can be fragile on Unix, so // use relative PREFIX values with care. LOG(VB_GENERAL, LOG_DEBUG, QString("Relative PREFIX! (%1), appDir=%2") .arg(installprefix) .arg(prefixDir.canonicalPath())); if (!prefixDir.cd(installprefix)) { LOG(VB_GENERAL, LOG_ERR, QString("Relative PREFIX does not resolve, using %1") .arg(prefixDir.canonicalPath())); } installprefix = prefixDir.canonicalPath(); } appbindir = installprefix + "/bin/"; sharedir = installprefix + "/share/mythtv/"; libdir = installprefix + '/' + QString(LIBDIRNAME) + "/mythtv/"; #endif if (confdir.length() == 0) confdir = QDir::homePath() + "/.mythtv"; #if defined(Q_OS_ANDROID) themedir = sharedir + "themes/"; pluginsdir = libdir; translationsdir = sharedir + "i18n/"; filtersdir = libdir; #else themedir = sharedir + "themes/"; pluginsdir = libdir + "plugins/"; translationsdir = sharedir + "i18n/"; filtersdir = libdir + "filters/"; #endif LOG(VB_GENERAL, LOG_NOTICE, "Using runtime prefix = " + installprefix); LOG(VB_GENERAL, LOG_NOTICE, QString("Using configuration directory = %1") .arg(confdir)); LOG(VB_GENERAL, LOG_DEBUG, QString( "appbindir = "+ appbindir )); LOG(VB_GENERAL, LOG_DEBUG, QString( "sharedir = "+ sharedir )); LOG(VB_GENERAL, LOG_DEBUG, QString( "libdir = "+ libdir )); LOG(VB_GENERAL, LOG_DEBUG, QString( "themedir = "+ themedir )); LOG(VB_GENERAL, LOG_DEBUG, QString( "pluginsdir = "+ pluginsdir )); LOG(VB_GENERAL, LOG_DEBUG, QString( "translationsdir= "+ translationsdir)); LOG(VB_GENERAL, LOG_DEBUG, QString( "filtersdir = "+ filtersdir )); }