Пример #1
0
bool Utils::Misc::isUrl(const QString &s)
{
    static const QRegularExpression reURLScheme(
                "http[s]?|ftp", QRegularExpression::CaseInsensitiveOption);

    return reURLScheme.match(QUrl(s).scheme()).hasMatch();
}
Пример #2
0
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;
}
Пример #3
0
  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;
  }
static FontKeys &fontKeys()
{
    static FontKeys result;
    if (result.isEmpty()) {
        const QSettings fontRegistry(QStringLiteral("HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Fonts"),
                                     QSettings::NativeFormat);
        const QStringList allKeys = fontRegistry.allKeys();
        const QString trueType = QStringLiteral("(TrueType)");
        const QRegularExpression sizeListMatch(QStringLiteral("\\s(\\d+,)+\\d+"));
        Q_ASSERT(sizeListMatch.isValid());
        const int size = allKeys.size();
        result.reserve(size);
        for (int i = 0; i < size; ++i) {
            FontKey fontKey;
            const QString &registryFontKey = allKeys.at(i);
            fontKey.fileName = fontRegistry.value(registryFontKey).toString();
            QString realKey = registryFontKey;
            realKey.remove(trueType);
            realKey.remove(sizeListMatch);
            const QStringList fontNames = realKey.trimmed().split(QLatin1Char('&'));
            fontKey.fontNames.reserve(fontNames.size());
            foreach (const QString &fontName, fontNames)
                fontKey.fontNames.append(fontName.trimmed());
            result.append(fontKey);
        }
    }
    return result;
}
static void createProposal(QFutureInterface<QStringList> &future, const QString &text,
                           const QString &wordUnderCursor)
{
    const QRegularExpression wordRE("([a-zA-Z_][a-zA-Z0-9_]{2,})");

    QSet<QString> words;
    QRegularExpressionMatchIterator it = wordRE.globalMatch(text);
    int wordUnderCursorFound = 0;
    while (it.hasNext()) {
        if (future.isCanceled())
            return;
        QRegularExpressionMatch match = it.next();
        const QString &word = match.captured();
        if (word == wordUnderCursor) {
            // Only add the word under cursor if it
            // already appears elsewhere in the text
            if (++wordUnderCursorFound < 2)
                continue;
        }

        if (!words.contains(word))
            words.insert(word);
    }

    future.reportResult(words.toList());
}
Пример #6
0
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();
	}
}
Пример #7
0
// 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;
}
Пример #8
0
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 );
}
Пример #9
0
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;
}
Пример #10
0
QRegularExpression SearchOptions::getRegularExpression() const
{
  QRegularExpression regexp = isWildCard() ? StringUtil::wildCardToRegExp(getFindValue()) : QRegularExpression(getFindValue());
  if (!isCaseSensitive()) {
    regexp.setPatternOptions(QRegularExpression::CaseInsensitiveOption);
  }
  return regexp;
}
Пример #11
0
/** 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);
	}
}
Пример #12
0
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));
    }
}
Пример #13
0
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);
}
Пример #14
0
/**
 * 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) : "";
}
Пример #15
0
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();
}
Пример #16
0
void MultipleFilterProxy::setRegExpFilter(qint32 col, const QRegularExpression& matcher, qint32 role, bool match)
{
    if (col < 0 || col >= m_dateRangeFilter.size())
        return;
    if (matcher.pattern().isEmpty() || !matcher.isValid())
        return removeFilterFromColumn(col, role);
    m_dateRangeFilter[col].remove(role);
    m_boolFilter[col].remove(role);
    m_regExpFilter[col][role] = std::make_pair(matcher, match);
    invalidateFilter();
}
Пример #17
0
// 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;
}
Пример #18
0
/**
 * 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;
}
Пример #19
0
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;
}
Пример #20
0
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());
}
Пример #21
0
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;
}
Пример #22
0
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
    }
}
bool QGCAudioWorker::_getMillisecondString(const QString& string, QString& match, int& number) {
    static QRegularExpression re("([0-9]+ms)");
    QRegularExpressionMatchIterator i = re.globalMatch(string);
    while (i.hasNext()) {
        QRegularExpressionMatch qmatch = i.next();
        if (qmatch.hasMatch()) {
            match = qmatch.captured(0);
            number = qmatch.captured(0).replace("ms", "").toInt();
            return true;
        }
    }
    return false;
}
Пример #24
0
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);
}
Пример #25
0
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;
}
Пример #26
0
/*!
    \fn int QStringList::indexOf(const QRegularExpression &re, int from) const
    \overload
    \since 5.0

    Returns the index position of the first match of \a re in
    the list, searching forward from index position \a from. Returns
    -1 if no item matched.

    \sa lastIndexOf()
*/
int QtPrivate::QStringList_indexOf(const QStringList *that, const QRegularExpression &re, int from)
{
    if (from < 0)
        from = qMax(from + that->size(), 0);

    QString exactPattern = QLatin1String("\\A(?:") + re.pattern() + QLatin1String(")\\z");
    QRegularExpression exactRe(exactPattern, re.patternOptions());

    for (int i = from; i < that->size(); ++i) {
        QRegularExpressionMatch m = exactRe.match(that->at(i));
        if (m.hasMatch())
            return i;
    }
    return -1;
}
Пример #27
0
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;
    }
}
Пример #28
0
    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;
    }
Пример #29
0
/**
 * 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;
}
Пример #30
0
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();
    });
}