bool CRegularExpressionRule::match(const QList<QString>& lQuery, const QString& sContent) const { Q_ASSERT( m_nType == RuleType::RegularExpression ); if ( m_sContent.isEmpty() ) return false; if ( m_bSpecialElements ) { // Build a regular expression filter from the search query words. // Returns an empty string if not applied or if the filter was invalid. // // Substitutes: // <_> - inserts all query keywords; // <0>..<9> - inserts query keyword number 0..9; // <> - inserts next query keyword. // // For example regular expression: // .*(<2><1>)|(<_>).* // for "music mp3" query will be converted to: // .*(mp3\s*music\s*)|(music\s*mp3\s*).* // // Note: \s* - matches any number of white-space symbols (including zero). QString sFilter, sBaseFilter = m_sContent; int pos = sBaseFilter.indexOf( '<' ); if ( pos != -1 ) { quint8 nArg = 0; // replace all relevant occurrences of <*something* while ( pos != -1 ); { sFilter += sBaseFilter.left( pos ); sBaseFilter.remove( 0, pos ); bool bSuccess = replace( sBaseFilter, lQuery, nArg ); pos = sBaseFilter.indexOf( '<', bSuccess ? 0 : 1 ); } // add whats left of the base filter string to the newly generated filter sFilter += sBaseFilter; QRegularExpression oRegExpFilter = QRegularExpression( sFilter ); return oRegExpFilter.match( sContent ).hasMatch(); } else { // This shouldn't happen, but it's covered anyway... Q_ASSERT( false ); QRegularExpression oRegExpFilter = QRegularExpression( m_sContent ); return oRegExpFilter.match( sContent ).hasMatch(); } } else { return m_regularExpressionContent.match( sContent ).hasMatch(); } }
int Walltime::toInt( QString const& string ) { int h,m; int s = -1; QRegularExpression re; QRegularExpressionMatch rem; // "h+:mm:ss" re.setPattern("^(\\d+):(\\d+):(\\d+)"); rem = re.match(string); if( rem.hasMatch() ) { try { h = rem.captured(1).toInt(); m = rem.captured(2).toInt(); s = rem.captured(3).toInt(); s+= h*3600 + m*60; } catch(...) { s = -1; } return s; } // "<integer>unit" where unit is d|h|m|s (case insensitive) re.setPattern("^\\s*(\\d+)\\s*([dhmsDHMS]?)\\s*$"); rem = re.match( string ); if( rem.hasMatch() ) { QString number = rem.captured(1); QString unit = rem.captured(2); try { s = number.toInt(); if( s<0 ) s = -1; else if( unit=="d" ) s*=24*3600; else if( unit=="h" ) s*=3600; else if( unit=="m" ) s*=60; else if( unit=="s" ) s*=1; else s = -1; } catch(...) { s = -1; } return s; } // "h+:mm" re.setPattern("^\\s*(\\d+):(\\d+)\\s*$"); rem = re.match( string ); if( rem.hasMatch() ) { try { h = rem.captured(1).toInt(); m = rem.captured(2).toInt(); s = h*3600 + m*60; } catch(...) { s = -1; } return s; } return -1; //keep the compiler happy }
QStringList CaViewerScanner::getImageSeries(QString sFullName, QString &sRetPath, QString &sRetBaseName) { // creates list components based on sFilename (eg. .../foo_t0001.tif) QStringList slImageSeries; // checks whether the filename matches the format or not const QString sFormatPrefix("^(?<path>.*/)(?<name>[^/]+)"); const QString sFormatNumber("_t(?<num>\\d{4})"); const QString sFormatSuffix("(?<dotext>\\..{1,3})$"); const QRegularExpression regexpSeries(sFormatPrefix + sFormatNumber + sFormatSuffix); const QRegularExpressionMatch matchSeries = regexpSeries.match(sFullName); if(matchSeries.hasMatch()) { // match found (i.e. there are related files in the same folder) sRetBaseName = matchSeries.captured("name"); sRetPath = matchSeries.captured("path"); const QString sExtension = matchSeries.captured("dotext"); const QDir dir(sRetPath); const QStringList slAllFiles = dir.entryList(QDir::Files, QDir::Name); QRegularExpression regexpFileName(QRegularExpression::escape(sRetBaseName) + sFormatNumber + QRegularExpression::escape(sExtension)); int nSequence = 0; for(int count = 0; count < slAllFiles.size(); ++count) { QRegularExpressionMatch match = regexpFileName.match(slAllFiles.at(count)); if(match.hasMatch()) { int fileNum = match.captured("num").toInt(); if(fileNum != nSequence) return slImageSeries; else { slImageSeries << slAllFiles.at(count); ++nSequence; } } } } else { // no match found const QRegularExpression regexpSingle(sFormatPrefix + sFormatSuffix); const QRegularExpressionMatch matchSingle = regexpSingle.match(sFullName); if(matchSingle.hasMatch()) { sRetBaseName = matchSingle.captured("name"); sRetPath = matchSingle.captured("path"); slImageSeries << sRetBaseName + matchSingle.captured("dotext"); } } return slImageSeries; }
bool CliPlugin::readExtractLine(const QString &line) { const QRegularExpression rxCRC(QStringLiteral("CRC failed")); if (rxCRC.match(line).hasMatch()) { emit error(i18n("One or more wrong checksums")); return false; } const QRegularExpression rxVolume(QStringLiteral("Cannot find volume ")); if (rxVolume.match(line).hasMatch()) { emit error(i18n("Failed to find all archive volumes.")); return false; } return true; }
QList<LocatorFilterEntry> OpenDocumentsFilter::matchesFor(QFutureInterface<LocatorFilterEntry> &future, const QString &entry) { QList<LocatorFilterEntry> goodEntries; QList<LocatorFilterEntry> betterEntries; const EditorManager::FilePathInfo fp = EditorManager::splitLineAndColumnNumber(entry); const QRegularExpression regexp = createRegExp(fp.filePath); if (!regexp.isValid()) return goodEntries; const QList<Entry> editorEntries = editors(); for (const Entry &editorEntry : editorEntries) { if (future.isCanceled()) break; QString fileName = editorEntry.fileName.toString(); if (fileName.isEmpty()) continue; QString displayName = editorEntry.displayName; const QRegularExpressionMatch match = regexp.match(displayName); if (match.hasMatch()) { LocatorFilterEntry filterEntry(this, displayName, QString(fileName + fp.postfix)); filterEntry.extraInfo = FileUtils::shortNativePath(FileName::fromString(fileName)); filterEntry.fileName = fileName; filterEntry.highlightInfo = highlightInfo(match); if (match.capturedStart() == 0) betterEntries.append(filterEntry); else goodEntries.append(filterEntry); } } betterEntries.append(goodEntries); return betterEntries; }
void PremiumizeMeDownloadHandler::generateLinkReplyFinished() { auto reply = static_cast< QNetworkReply *>(sender()); QString data(QString::fromLatin1(reply->readAll())); reply->deleteLater(); QRegularExpressionMatch match = LOCATION_REGEXP.match(data); if(!match.hasMatch()) { m_download->setMessage("No download url found: "+data); m_download->setEnabled(false); return; } QString downloadUrl = match.captured(1); downloadUrl.replace(QLatin1String("\\/"), QLatin1String("/")); m_download->setRedirectedUrl(QUrl(downloadUrl)); m_download->setMessage("Getting file information..."); Controller::downloadsDao()->update(m_download); m_downloader->setUrl(m_download->redirectedUrl()); m_downloader->getMetaData(); QObject::connect(m_downloader, &Downloader::metaDataChanged, [&]() { m_download->setRedirectedUrl(m_downloader->redirectedUrl()); m_download->setFileName(m_downloader->fileName()); m_download->setFileSize(m_downloader->fileSize()); m_download->setMessage(""); Controller::downloadsDao()->update(m_download); emit downloadInformationReady(); }); }
ImageOutputFormat parseImageFormat( const QString &format ) { if ( format.compare( QLatin1String( "png" ), Qt::CaseInsensitive ) == 0 || format.compare( QLatin1String( "image/png" ), Qt::CaseInsensitive ) == 0 ) { return PNG; } else if ( format.compare( QLatin1String( "jpg " ), Qt::CaseInsensitive ) == 0 || format.compare( QLatin1String( "image/jpeg" ), Qt::CaseInsensitive ) == 0 ) { return JPEG; } else { // lookup for png with mode QRegularExpression modeExpr = QRegularExpression( QStringLiteral( "image/png\\s*;\\s*mode=([^;]+)" ), QRegularExpression::CaseInsensitiveOption ); QRegularExpressionMatch match = modeExpr.match( format ); QString mode = match.captured(); if ( mode.compare( QLatin1String( "16bit" ), Qt::CaseInsensitive ) == 0 ) return PNG16; if ( mode.compare( QLatin1String( "8bit" ), Qt::CaseInsensitive ) == 0 ) return PNG8; if ( mode.compare( QLatin1String( "1bit" ), Qt::CaseInsensitive ) == 0 ) return PNG1; } return UNKN; }
// Delete all temporary directories for an application int PathUtils::removeTemporaryApplicationDirs(QString appName) { if (appName.isNull()) { appName = qApp->applicationName(); } auto dirName = TEMP_DIR_FORMAT.arg(appName).arg("*").arg("*"); QDir rootTempDir = QDir::tempPath(); auto dirs = rootTempDir.entryInfoList({ dirName }, QDir::Dirs); int removed = 0; for (auto& dir : dirs) { auto dirName = dir.fileName(); auto absoluteDirPath = QDir(dir.absoluteFilePath()); QRegularExpression re { "^" + QRegularExpression::escape(appName) + "\\-(?<pid>\\d+)\\-(?<timestamp>\\d+)$" }; auto match = re.match(dirName); if (match.hasMatch()) { auto pid = match.capturedRef("pid").toLongLong(); auto timestamp = match.capturedRef("timestamp"); if (!processIsRunning(pid)) { qDebug() << " Removing old temporary directory: " << dir.absoluteFilePath(); absoluteDirPath.removeRecursively(); removed++; } else { qDebug() << " Not removing (process is running): " << dir.absoluteFilePath(); } } } return removed; }
bool Utils::Misc::isUrl(const QString &s) { static const QRegularExpression reURLScheme( "http[s]?|ftp", QRegularExpression::CaseInsensitiveOption); return reURLScheme.match(QUrl(s).scheme()).hasMatch(); }
NimLexer::Token NimLexer::readIdentifierOrKeyword(SourceCodeStream* stream) { static QRegularExpression isLetter {"[a-zA-Z\x80-\xFF]"}; static QSet<QString> keywords {"template", "include", // 7 "method", "string", "import" // 6 "while", "cbool", "tuple", "defer", // 5 "cint", "case", "bool", "proc", "type", "else", "from", "enum", "when", // 4 "int", "var", "for", "ref", // 3 "in", "of", "if" }; // 2 stream->setAnchor(); stream->move(); while (!stream->isEnd()) { const QChar& c = stream->peek(); if (!(c == '_' || c.isDigit() || isLetter.match(c).hasMatch())) break; stream->move(); } QString value = stream->value(); bool isKeyword = keywords.contains(value); return Token (stream->anchor(), stream->length(), isKeyword ? TokenType::Keyword : TokenType::Identifier ); }
QByteArray ViewJson::render(Context *c) const { Q_D(const ViewJson); QByteArray ret; QJsonObject obj; const QVariantHash stash = c->stash(); switch (d->exposeMode) { case All: obj = QJsonObject::fromVariantHash(stash); break; case String: { auto it = stash.constFind(d->exposeKey); if (it != stash.constEnd()) { obj.insert(d->exposeKey, QJsonValue::fromVariant(it.value())); } break; } case StringList: { QVariantHash exposedStash; auto it = stash.constBegin(); while (it != stash.constEnd()) { const QString key = it.key(); if (d->exposeKeys.contains(key)) { exposedStash.insertMulti(it.key(), it.value()); } ++it; } obj = QJsonObject::fromVariantHash(exposedStash); break; } case RegularExpression: { QVariantHash exposedStash; QRegularExpression re = d->exposeRE; // thread safety auto it = stash.constBegin(); while (it != stash.constEnd()) { const QString key = it.key(); if (re.match(key).hasMatch()) { exposedStash.insertMulti(key, it.value()); } ++it; } obj = QJsonObject::fromVariantHash(exposedStash); break; } } c->response()->setContentType(QStringLiteral("application/json")); ret = QJsonDocument(obj).toJson(d->format); return ret; }
/** Redefined to disable search in the table and trigger jumpToWidget's action. */ void TableView::keyboardSearch(const QString &search) { // If one has assigned a simple key like 'N' to 'Skip Forward' we don't actually want to skip the track // IMHO, it's better to trigger the JumpTo widget to 'N' section static QRegularExpression az("[a-z]", QRegularExpression::CaseInsensitiveOption | QRegularExpression::OptimizeOnFirstUsageOption); if (az.match(search).hasMatch()) { this->jumpTo(search); } }
/** * Returns encrypted note text if it is encrypted */ QString Note::getEncryptedNoteText() { QString noteText = this->noteText; // get regular expression for the encrypted string QRegularExpression re = getEncryptedNoteTextRegularExpression(); // check if we have an encrypted note text and return it if so QRegularExpressionMatch match = re.match(noteText); return match.hasMatch() ? match.captured(1) : ""; }
void RevDesc::on_anchorClicked(const QUrl& link) { static QRegularExpression anchorRE("^#(.+)$"); qDebug() << "clicked on " << link.toDisplayString() << "\n"; QWebFrame* frame = this->page()->mainFrame(); QRegularExpressionMatch anchorMatch = anchorRE.match(link.toDisplayString()); if(anchorMatch.hasMatch()) { frame->scrollToAnchor(anchorMatch.captured(1)); } }
static void applyPermissionsFromName(FileInfo &info) { static QRegularExpression rx("_PERM_([^_]*)_[^/]*$"); auto m = rx.match(info.name); if (m.hasMatch()) { info.permissions = RemotePermissions::fromServerString(m.captured(1)); } for (FileInfo &sub : info.children) applyPermissionsFromName(sub); }
void LoginHandler::handleHostMessage(const QString &message) { Q_ASSERT(!_client->username().isEmpty()); if(_server->sessionCount() >= _server->sessionLimit()) { send("ERROR CLOSED"); _client->disconnectError("login error"); return; } const QRegularExpression re("\\AHOST (\\*|[a-zA-Z0-9:-]{1,64}) (\\d+) (\\d+)\\s*(?:;(.+))?\\z"); auto m = re.match(message); if(!m.hasMatch()) { send("ERROR SYNTAX"); _client->disconnectError("login error"); return; } QString sessionId = m.captured(1); int minorVersion = m.captured(2).toInt(); int userId = m.captured(3).toInt(); // Check if session ID is available if(sessionId == "*") { // Generated session ID sessionId = QUuid::createUuid().toString(); sessionId = sessionId.mid(1, sessionId.length()-2); // strip the { and } chars } if(!_server->getSessionDescriptionById(sessionId).id.isEmpty()) { send("ERROR SESSIONIDINUSE"); _client->disconnectError("login error"); return; } QString password = m.captured(4); if(password != _server->hostPassword() && !_hostPrivilege) { send("ERROR BADPASS"); _client->disconnectError("login error"); return; } _client->setId(userId); // Mark login phase as complete. No more login messages will be sent to this user send(QString("OK %1 %2").arg(sessionId).arg(userId)); _complete = true; // Create a new session SessionState *session = _server->createSession(sessionId, minorVersion, _client->username()); session->joinUser(_client, true); deleteLater(); }
QPair<QString, QString> UpdateItem::parseAnchor(const QString &input) { QPair<QString, QString> ret; QRegularExpressionMatch match = AnchorReg.match(input); if (match.hasMatch()) { ret.first = match.captured("href"); ret.second = match.captured("content"); } return ret; }
// Convert string to integer number bool Commands::function_AToI(CommandNode* c, Bundle& obj, ReturnValue& rv) { static QRegularExpression re("[\\d.\\-eE]+"); QRegularExpressionMatch match = re.match(c->argc(0)); if (match.hasMatch()) rv.set( match.captured(0).toInt() ); else { Messenger::warn("Couldn't convert '%s' to an integer number.\n", qPrintable(c->argc(0))); rv.reset(); } return true; }
/** * Load a palette from a GIMP palette file. * * The file format is: * * GIMP Palette * *HEADER FIELDS* * # one or more comment * r g b name * ... * * @param filename palette file name * @param writeprotected is the source file read only */ Palette *Palette::fromFile(const QFileInfo& file, bool readonly, QObject *parent) { QFile palfile(file.absoluteFilePath()); if (!palfile.open(QIODevice::ReadOnly | QIODevice::Text)) return nullptr; QTextStream in(&palfile); if(in.readLine() != "GIMP Palette") return nullptr; Palette *pal = new Palette(file.baseName(), file.absoluteFilePath(), !file.isWritable() | readonly, parent); const QRegularExpression colorRe("^(\\d+)\\s+(\\d+)\\s+(\\d+)\\s*(.+)?$"); do { QString line = in.readLine().trimmed(); if(line.isEmpty() || line.at(0) == '#') { // ignore comments and empty lines } else if(line.startsWith("Name:")) { pal->_name = line.mid(5).trimmed(); } else if(line.startsWith("Columns:")) { bool ok; int cols = line.mid(9).trimmed().toInt(&ok); if(ok && cols>0) pal->_columns = cols; } else { QRegularExpressionMatch m = colorRe.match(line); if(m.hasMatch()) { pal->_colors.append(PaletteColor( QColor( m.captured(1).toInt(), m.captured(2).toInt(), m.captured(3).toInt() ), m.captured(4) ) ); } else { qWarning() << "unhandled line" << line << "in" << file.fileName(); } } } while(!in.atEnd()); // Palettes loaded from file are write-protected by default pal->_writeprotect = true; return pal; }
void Template::translate(ITemplateTranslationProvider &provider) { //This regex captures expressions of the form //<?= tr("This is a test") ?> and <?= tr("optional %1 parameters %2","bla","blu") ?> //The first capture group is the key (untranslated string), the second the optional list of parameters const QRegularExpression regexp = QRegularExpression("<\\?=\\s*tr\\(\"([^\"\\\\]*(?:\\\\.[^\"\\\\]*)*)\"((?:,\"[^\"\\\\]*(?:\\\\.[^\"\\\\]*)*\")*)\\s*\\)\\?>"); //This one is used to extract the parameters using global matching const QRegularExpression paramExp = QRegularExpression(",\"([^\"\\\\]*(?:\\\\.[^\"\\\\]*)*)\""); int offset = 0; QRegularExpressionMatch match; do { match = regexp.match(*this,offset); if(match.hasMatch()) { int start = match.capturedStart(0); int len = match.capturedLength(0); QString key = match.captured(1); //replace escaped double and single quotes key.replace("\\\"","\""); key.replace("\\'", "'"); QString translation = provider.getTranslation(key); //find out if we have optional parameters if(match.capturedLength(2)>0) { QString params = match.captured(2); //extract each optional parameter QRegularExpressionMatchIterator it = paramExp.globalMatch(params); while(it.hasNext()) { QRegularExpressionMatch paramMatch = it.next(); QString param = paramMatch.captured(1); //replace escaped quotes param.replace("\\\"","\""); param.replace("\\'", "'"); //apply the param translation = translation.arg(param); } } this->replace(start,len,translation); offset = start+translation.length(); } }while(match.hasMatch()); }
//----------------------------------------------------------------------------- bool ClusterInfoReader::match_( QRegularExpression const& re, bool must_throw ) { this->m_ = re.match( this->remainder_ ); if( this->m_.hasMatch() ) { this->token_ = this->m_.captured(1); this->remainder_ = this->m_.captured(this->m_.lastCapturedIndex()); return true; } this->token_.clear(); if( must_throw ) this->throw_invalid_format_(); return false; }
static bool parseVersion(const QString &text, int &version) { // The version in Uncrustify is printed like "uncrustify 0.62" const QRegularExpression rx(QLatin1String("([0-9]{1})\\.([0-9]{2})")); const QRegularExpressionMatch match = rx.match(text); if (!match.hasMatch()) return false; const int major = match.captured(1).toInt() * 100; const int minor = match.captured(2).toInt(); version = major + minor; return true; }
void CellReference::init(const QString &cell_str) { // Try this "^'?([A-Za-z0-9._ ]*)'?:?\\$?([A-Z]{1,3})\\$?(\\d+)$" static QRegularExpression re(QStringLiteral("^\\$?([A-Z]{1,3})\\$?(\\d+)$")); QRegularExpressionMatch match = re.match(cell_str); if (match.hasMatch()) { const QString col_str = match.captured(1); const QString row_str = match.captured(2); _row = row_str.toInt(); _column = col_from_name(col_str); // TODO _sheet } }
const QRegularExpression FilePattern::regexFromPattern(const QString &pattern) { if (pattern.isEmpty()) return QRegularExpression(); static const QRegularExpression MATCH_PATTERN_DIRECTORY("^(.*/)$"); static const QRegularExpression MATCH_PATTERN_FILE("^(.*/)?([^.]*)?(?:[.]([^.]*))?$"); static const QRegularExpression MATCH_PATTERN_SEQUENCE("^(.*/)?(?:([^.]*))(?:[.](?:%0(\\d+)d))(?:[.]([^.]*))?$"); QString regExpStr = pattern; if (MATCH_PATTERN_DIRECTORY.match(pattern).hasMatch()) { regExpStr.replace(MATCH_PATTERN_FILE, "^(?<directory>\\1)$"); } else if (MATCH_PATTERN_FILE.match(pattern).hasMatch()) { regExpStr.replace(MATCH_PATTERN_FILE, "^(?<directory>\\1)(?<baseName>\\2)[.](?<extension>\\3)$"); } else if (MATCH_PATTERN_SEQUENCE.match(pattern).hasMatch()) { regExpStr.replace(MATCH_PATTERN_SEQUENCE, "^(?<directory>\\1)(?<baseName>\\2)[.]((?<frame>[0-9.]{\\3}?)|(?<frameSpec>%0\\d+d))[.](?<extension>\\4)$"); } else { qWarning() << "unable to generate regexp for pattern" << pattern; } return QRegularExpression(regExpStr); }
void AndroidDevice::filterAndAddToTextEdit(const QString& line) { static const QRegularExpression re( "(?<date>[\\d-]+) *(?<time>[\\d:\\.]+) *(?<pid>\\d+) *(?<tid>\\d+) *(?<verbosity>[A-Z]) *(?<tag>.+):", QRegularExpression::InvertedGreedinessOption | QRegularExpression::DotMatchesEverythingOption ); bool filtersMatch = true; const QRegularExpressionMatch match = re.match(line); if (match.hasMatch()) { const QStringRef date = match.capturedRef("date"); const QStringRef time = match.capturedRef("time"); const QStringRef pid = match.capturedRef("pid"); const QStringRef tid = match.capturedRef("tid"); const QStringRef verbosity = match.capturedRef("verbosity"); const QStringRef tag = match.capturedRef("tag").trimmed(); const QStringRef text = line.midRef(match.capturedEnd("tag") + 1); const auto verbosityLevel = static_cast<VerbosityEnum>(Utils::verbosityCharacterToInt(verbosity.at(0).toLatin1())); checkFilters(filtersMatch, m_filtersValid, verbosityLevel, pid, tid, tag, text); if (filtersMatch) { const auto verbosityColorType = static_cast<ColorTheme::ColorType>(verbosityLevel); m_deviceWidget->addText(verbosityColorType, verbosity); m_deviceWidget->addText(ColorTheme::DateTime, date); m_deviceWidget->addText(ColorTheme::DateTime, time); m_deviceWidget->addText(ColorTheme::Pid, pid); m_deviceWidget->addText(ColorTheme::Tid, tid); m_deviceWidget->addText(ColorTheme::Tag, tag); m_deviceWidget->addText(verbosityColorType, text); m_deviceWidget->flushText(); } } else { qDebug() << "failed to parse" << line; checkFilters(filtersMatch, m_filtersValid); if (filtersMatch) { m_deviceWidget->addText(ColorTheme::VerbosityVerbose, QStringRef(&line)); m_deviceWidget->flushText(); } } m_deviceWidget->highlightFilterLineEdit(!m_filtersValid); }
bool Hibernation::init() { // Ensure storage directory exists QDir dir(_path); if(!dir.exists()) { if(!dir.mkpath(".")) { logger::error() << "Couldn't create session storage directory" << _path; return false; } } // Scan for sessions const QRegularExpression re("^session-([a-zA-Z0-9:-]{1,64})\\.dphib$"); for(const QString &filename : dir.entryList(QStringList() << "session-*.dphib", QDir::Files | QDir::Readable)) { QRegularExpressionMatch m = re.match(filename); if(!m.hasMatch()) continue; recording::Reader reader(dir.filePath(filename)); recording::Compatibility comp = reader.open(); if(comp != recording::COMPATIBLE) { logger::warning() << "Incompatible hibernated session:" << filename; continue; } if(!reader.isHibernation()) { logger::warning() << "Valid recording, but not a hibernated session:" << filename; continue; } SessionDescription desc; desc.id = m.captured(1); desc.protoMinor = reader.hibernationHeader().minorVersion; desc.title = reader.hibernationHeader().title; desc.founder = reader.hibernationHeader().founder; desc.passwordHash = reader.hibernationHeader().password; desc.persistent = reader.hibernationHeader().flags & recording::HibernationHeader::PERSISTENT; desc.hibernating = true; _sessions.append(desc); logger::debug() << "Found hibernated session:" << filename; } logger::info() << "Found" << _sessions.size() << "hibernated session(s)"; return true; }
bool excludeHeaderPath(const QString &path) const override { if (path.contains(QLatin1String("lib/gcc/i686-apple-darwin"))) return true; // We already provide a custom clang include path matching the used libclang version, // so better ignore the clang include paths from the system as this might lead to an // unfavorable order with regard to include_next. static QRegularExpression clangIncludeDir( QLatin1String("\\A.*/lib/clang/\\d+\\.\\d+(\\.\\d+)?/include\\z")); if (clangIncludeDir.match(path).hasMatch()) return true; return false; }
void StaticSimple::beforePrepareAction(Context *c, bool *skipMethod) { Q_D(StaticSimple); if (*skipMethod) { return; } QString path = c->req()->path(); QRegularExpression re = d->re; // Thread-safe QRegularExpressionMatch match = re.match(path); if (match.hasMatch() && locateStaticFile(c, path)) { *skipMethod = true; } }
/** * Load a palette from a GIMP palette file. * * The file format is: * * GIMP Palette * *HEADER FIELDS* * # one or more comment * r g b name * ... * * @param filename palette file name */ Palette Palette::fromFile(const QFileInfo& file) { QFile palfile(file.absoluteFilePath()); if (!palfile.open(QIODevice::ReadOnly | QIODevice::Text)) return Palette(); QTextStream in(&palfile); if(in.readLine() != "GIMP Palette") return Palette(); Palette pal(file.baseName(), file.fileName()); const QRegularExpression colorRe("^(\\d+)\\s+(\\d+)\\s+(\\d+)\\s*(.+)?$"); do { QString line = in.readLine().trimmed(); if(line.isEmpty() || line.at(0) == '#') { // ignore comments and empty lines } else if(line.startsWith("Name:")) { pal._name = line.mid(5).trimmed(); } else if(line.startsWith("Columns:")) { bool ok; int cols = line.mid(9).trimmed().toInt(&ok); if(ok && cols>0) pal._columns = cols; } else { QRegularExpressionMatch m = colorRe.match(line); if(m.hasMatch()) { pal.appendColor( QColor( m.captured(1).toInt(), m.captured(2).toInt(), m.captured(3).toInt() ), m.captured(4) ); } else { qWarning() << "unhandled line" << line << "in" << file.fileName(); } } } while(!in.atEnd()); return pal; }
QString CellmlFileRuntime::cleanCode(const std::wstring &pCode) { // Remove all the comments from the given code and return the resulting // cleaned up code static const QRegularExpression CommentRegEx = QRegularExpression("^/\\*.*\\*/$"); QString res = QString(); foreach (const QString &code, QString::fromStdWString(pCode).split("\r\n")) { if (!CommentRegEx.match(code).hasMatch()) res += (res.isEmpty()?QString():"\n")+code; } return res; }