Пример #1
0
void Player::play(QString stationId) {

    stop();
    if( !playList.contains(stationId))
    {
        return;
    }

    HSTREAM stream = BASS_StreamCreateURL(playList.value(stationId).toStdString().c_str(),0,BASS_STREAM_BLOCK|BASS_STREAM_STATUS|BASS_STREAM_AUTOFREE,MyDownload,0);

    BASS_Start();

    if( stream)
    {
        bool buffering = true;
        while(buffering)
        {
            QWORD progress = BASS_StreamGetFilePosition(stream,BASS_FILEPOS_BUFFER)*100/BASS_StreamGetFilePosition(stream,BASS_FILEPOS_END);
            webView()->page()->mainFrame()->evaluateJavaScript(QString("PlayerHud.updateBufforStatus("+ QString::number(progress) +")"));
            if( progress>=100)
            {
                buffering = false;
                webView()->page()->mainFrame()->evaluateJavaScript("PlayerHud.clearBufforStatus()");
            }

        }
        const char *meta=BASS_ChannelGetTags(stream,BASS_TAG_META);
        if( !meta)
        {
            meta = BASS_ChannelGetTags(stream,BASS_TAG_OGG);
        }
        if( meta)
        {
            qDebug() << meta;
            QRegularExpression rx("StreamTitle='(.+)';StreamUrl");
            QRegularExpressionMatch match = rx.match(QString(meta));
            if (match.hasMatch()) {
                qDebug() << match.captured(1);
                webView()->page()->mainFrame()->evaluateJavaScript("setRadiostationTag('"+ match.captured(1) +"')");
            }
        }
        BASS_ChannelPlay(stream,FALSE);
        playStatus = true;

    }
    else
    {
        qDebug() << BASS_ErrorGetCode();
        return;
    }
    return;
}
Пример #2
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());
}
void AccountsWorker::refreshADDomain()
{
    QProcess *process = new QProcess(this);
    process->start("/opt/pbis/bin/enum-users");

    connect(process, &QProcess::readyReadStandardOutput, this, [=] {
        QRegularExpression re("Name:\\s+(\\w+)");
        QRegularExpressionMatch match = re.match(process->readAll());
        m_userModel->setIsJoinADDomain(match.hasMatch());
    });

    connect(process, static_cast<void (QProcess::*)(int)>(&QProcess::finished), process, &QProcess::deleteLater);
}
Пример #4
0
Provider *Provider::createForUrl(const QUrl &url, QObject *parent)
{
    QMapIterator<QString, QRegularExpression> it(endpointToUrlSchemes);
    while (it.hasNext()) {
        it.next();
        QRegularExpressionMatch match = it.value().match(url.toString());
        if (match.hasMatch()) {
            return new Provider(it.key(), parent);
        }
    }

    return 0;
}
Пример #5
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;
}
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;
}
Пример #8
0
QStringList CaViewerScanner::getImageSeries(QString sPath, QString sFileName, 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("^(?<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(sFileName);
    if(matchSeries.hasMatch())
    {   //  match found (i.e. there are related files in the same folder)
        sRetBaseName = matchSeries.captured("name");

        const QString sExtension = matchSeries.captured("dotext");

        const QDir dir(sPath);
        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(sFileName);
        if(matchSingle.hasMatch())
        {
            sRetBaseName = matchSingle.captured("name");
            slImageSeries << sFileName;
        }
    }

    return slImageSeries;
}
Пример #9
0
QString StringUtils::htmlEncode(
    QString text, bool urlAsLinks, bool newlineAsBr) {
  QString s;
  QHash<int,int> linksIndexes; // start of link index -> length of link
  if (urlAsLinks) {
    QRegularExpressionMatchIterator it = linkRe.globalMatch(text);
    while (it.hasNext()) {
      QRegularExpressionMatch match = it.next();
      linksIndexes.insert(match.capturedStart(0), match.capturedLength(0));
    }
  }
  for (int i = 0; i < text.length(); ) {
    if (urlAsLinks && linksIndexes.contains(i)) {
      int l = linksIndexes.value(i);
      QString html = htmlEncode(text.mid(i, l), false), href = html;
      href.replace("\"", "%22");
      s.append("<a href=\"").append(href).append("\">").append(html)
          .append("</a>");
      i += l;
    } else {
      const QChar c = text.at(i);
      switch(c.toLatin1()) {
      case '<':
        s.append("&lt;");
        break;
      case '>':
        s.append("&gt;");
        break;
      case '&':
        s.append("&amp;");
        break;
      case '"':
        s.append("&#34;");
        break;
      case '\'':
        s.append("&#39;");
        break;
      case '\n':
        if (newlineAsBr)
          s.append("<br/>\n");
        else
          s.append(c);
        break;
      default:
        s.append(c);
      }
      ++i;
    }
  }
  return s;
}
Пример #10
0
QUrl TheHatAndFat::extractStripImageUrl(QByteArray data)
{
    QString html(data);
    QRegularExpression reg("<img[^>]*src=\"(https://thehatandfat.files.wordpress.com/[^\"]*)\"");
    QRegularExpressionMatch match = reg.match(html);

    if (!match.hasMatch()) {
        return QUrl();
    }

    QString src = match.captured(1);

    return QUrl(src);
}
Пример #11
0
QUrl FoxTrot::extractStripImageUrl(QByteArray data)
{
    QString html(data);
    QRegularExpression reg("<img[^>]*class=\"strip\".*src=\"([^\"]*)\"");
    QRegularExpressionMatch match = reg.match(html);

    if (!match.hasMatch()) {
        return QUrl();
    }

    QString src = match.captured(1);

    return QUrl(src);
}
Пример #12
0
QUrl Sigmund::extractStripImageUrl(QByteArray data)
{
    QString html(data);
    QRegularExpression reg("<img[^>]*src=(strips/[^ ]*) ");
    QRegularExpressionMatch match = reg.match(html);

    if (!match.hasMatch()) {
        return QUrl();
    }

    QString src = match.captured(1);

    return QUrl("http://www.sigmund.nl/" + src);
}
Пример #13
0
bool RawHtmlPostprocessor::isblocklevel(const QString &html)
{
    QRegularExpressionMatch m = QRegularExpression("^\\<\\/?([^ >]+)").match(html);
    if ( m.hasMatch() ) {
        QChar ch = m.captured(1).at(0);
        // SPECIAL_CHARS: !, ?, @, %
        if ( SPECIAL_CHARS.contains(ch) ) {
            //! Comment, php etc...
            return true;
        }
        return util::isBlockLevel(m.captured(1));
    }
    return false;
}
Пример #14
0
    foreach (OnePartRule rule, onepartrules)
    {
        QRegularExpressionMatchIterator i = rule.pattern.globalMatch(text);

        while (i.hasNext())
        {
            QRegularExpressionMatch match = i.next();
            int length = match.capturedLength();
            if (length == 0)
                continue;
            int start = match.capturedStart();
            setFormat(start, length, rule.format);
        }
    }
Пример #15
0
QUrl ViiviJaWagner::extractStripImageUrl(QByteArray data)
{
    QString html(data);
    QRegularExpression reg("<img[^>]*src=\"(.*/webkuva/[^\"]*)\"");
    QRegularExpressionMatch match = reg.match(html);

    if (!match.hasMatch()) {
        return QUrl();
    }

    QString src = match.captured(1);

    return QUrl(src);
}
Пример #16
0
QUrl CheerUpEmoKid::extractStripImageUrl(QByteArray data)
{
    QString html(data);
    QRegularExpression reg("<img[^>]*src=\"([^\"]*/wp-content/uploads/[^\"]*)\"");
    QRegularExpressionMatch match = reg.match(html);

    if (!match.hasMatch()) {
        return QUrl();
    }

    QString src = match.captured(1);

    return QUrl(src);
}
Пример #17
0
QUrl DinosaurComics::extractStripImageUrl(QByteArray data)
{
    QString html(data);
    QRegularExpression reg("<img[^>]*src=\"([^\"]*/comics/[^\"]*)\"");
    QRegularExpressionMatch match = reg.match(html);

    if (!match.hasMatch()) {
        return QUrl();
    }

    QString src = match.captured(1);

    return QUrl(src);
}
Пример #18
0
/**
 * @brief Fetches the title of a webpage
 * @param url
 * @return
 */
QString LinkDialog::getTitleForUrl(QUrl url) {
    QNetworkAccessManager *manager = new QNetworkAccessManager(this);
    QEventLoop loop;
    QTimer timer;

    timer.setSingleShot(true);
    connect(&timer, SIGNAL(timeout()), &loop, SLOT(quit()));
    connect(manager, SIGNAL(finished(QNetworkReply *)), &loop, SLOT(quit()));

    // 5 sec timeout for the request
    timer.start(5000);

    QNetworkRequest networkRequest = QNetworkRequest(url);

#if (QT_VERSION >= QT_VERSION_CHECK(5, 6, 0))
    networkRequest.setAttribute(QNetworkRequest::FollowRedirectsAttribute,
                                true);
#endif

    QNetworkReply *reply = manager->get(networkRequest);
    loop.exec();

    // if we didn't get a timeout let's fetch the title of the webpage
    if (timer.isActive()) {
        // get the text from the network reply
        QString html = reply->readAll();

        // parse title from webpage
        QRegularExpression regex("<title>(.*)</title>");
        QRegularExpressionMatch match = regex.match(html);
        QString title = match.captured(1);

        // decode HTML entities
        HTMLEntities htmlEntities;
        title = htmlEntities.decodeHtmlEntities(title);

        // replace some other characters we don't want
        title.replace("[", "(")
                .replace("]", ")")
                .replace("<", "(")
                .replace(">", ")");

        // trim whitespaces and return title
        return title.simplified();
    }

    // timer elapsed, no reply from network request
    return "";
}
Пример #19
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;
}
Пример #20
0
bool LonLatParser::parse(const QString& string)
{
    const QString input = string.toLower().trimmed();

    // #1: Just two numbers, no directions, e.g. 74.2245 -32.2434 (assumes lat lon)
    {
        const QString numberCapExp = QStringLiteral("\\A(?:") +
            QStringLiteral("([-+]?\\d{1,3}%1?\\d*(?:[eE][+-]?\\d+)?)(?:,|;|\\s)\\s*").arg(m_decimalPointExp) +
            QStringLiteral("([-+]?\\d{1,3}%1?\\d*(?:[eE][+-]?\\d+)?)").arg(m_decimalPointExp) +
            QStringLiteral(")\\z");

        const QRegularExpression regex(numberCapExp);
        QRegularExpressionMatch match = regex.match(input);
        if (match.hasMatch()) {
            m_lon = parseDouble(match.captured(2));
            m_lat = parseDouble(match.captured(1));

            return true;
        }
    }

    initAll();

    if (tryMatchFromD(input, PostfixDir)) {
        return true;
    }

    if (tryMatchFromD(input, PrefixDir)) {
        return true;
    }

    if (tryMatchFromDms(input, PostfixDir)) {
        return true;
    }

    if (tryMatchFromDms(input, PrefixDir)) {
        return true;
    }

    if (tryMatchFromDm(input, PostfixDir)) {
        return true;
    }

    if (tryMatchFromDm(input, PrefixDir)) {
        return true;
    }

    return false;
}
Пример #21
0
// #3: Sexagesimal
bool LonLatParser::tryMatchFromDms(const QString& input, DirPosition dirPosition)
{
    // direction as postfix
    const QString postfixCapExp = QStringLiteral("\\A(?:") +
		QStringLiteral("([-+]?)(\\d{1,3})(?:%3|\\s)\\s*(\\d{1,2})(?:%4|\\s)\\s*") +
		QStringLiteral("(\\d{1,2}%1?\\d*)(?:%5)?\\s*%2[,;]?\\s*") +
		QStringLiteral("([-+]?)(\\d{1,3})(?:%3|\\s)\\s*(\\d{1,2})(?:%4|\\s)\\s*") +
		QStringLiteral("(\\d{1,2}%1?\\d*)(?:%5)?\\s*%2") +
		QStringLiteral(")\\z");

    // direction as prefix
    const QString prefixCapExp = QStringLiteral("\\A(?:") +
		QStringLiteral("%2\\s*([-+]?)(\\d{1,3})(?:%3|\\s)\\s*(\\d{1,2})(?:%4|\\s)\\s*") +
		QStringLiteral("(\\d{1,2}%1?\\d*)(?:%5)?\\s*(?:,|;|\\s)\\s*") +
		QStringLiteral("%2\\s*([-+]?)(\\d{1,3})(?:%3|\\s)\\s*(\\d{1,2})(?:%4|\\s)\\s*") +
		QStringLiteral("(\\d{1,2}%1?\\d*)(?:%5)?") +
		QStringLiteral(")\\z");

    const QString &expTemplate = (dirPosition == PostfixDir) ? postfixCapExp
                                                             : prefixCapExp;

    const QString numberCapExp = expTemplate.arg(m_decimalPointExp, m_dirCapExp,
                                                 m_degreeExp, m_minutesExp, m_secondsExp);

    const QRegularExpression regex(numberCapExp);
    QRegularExpressionMatch match = regex.match(input);
    if (!match.hasMatch()) {
        return false;
    }

    bool isDir1LonDir;
    bool isLonDirPosHemisphere;
    bool isLatDirPosHemisphere;
    const QString dir1 = match.captured(dirPosition == PostfixDir ? 5 : 1);
    const QString dir2 = match.captured(dirPosition == PostfixDir ? 10 : 6);
    if (!isCorrectDirections(dir1, dir2, isDir1LonDir,
                             isLonDirPosHemisphere, isLatDirPosHemisphere)) {
        return false;
    }

    const int valueStartIndex1 = (dirPosition == PostfixDir ? 1 : 2);
    const int valueStartIndex2 = (dirPosition == PostfixDir ? 6 : 7);
    m_lon = degreeValueFromDMS(match, isDir1LonDir ? valueStartIndex1 : valueStartIndex2,
                               isLonDirPosHemisphere);
    m_lat = degreeValueFromDMS(match, isDir1LonDir ? valueStartIndex2 : valueStartIndex1,
                               isLatDirPosHemisphere);

    return true;
}
Пример #22
0
void GnuMakeParser::stdOutput(const QString &line)
{
    const QString lne = rightTrimmed(line);

    QRegularExpressionMatch match = m_makeDir.match(lne);
    if (match.hasMatch()) {
        if (match.captured(6) == QLatin1String("Leaving"))
            removeDirectory(match.captured(7));
        else
            addDirectory(match.captured(7));
        return;
    }

    IOutputParser::stdOutput(line);
}
Пример #23
0
bool QuickFindPattern::isLineMatching( const QString& line, int column ) const
{
    if ( ! active_ )
        return false;

    QRegularExpressionMatch match = regexp_.match( line, column );
    if ( match.hasMatch() ) {
        lastMatchStart_ = match.capturedStart();
        lastMatchEnd_ = match.capturedEnd() - 1;
        return true;
    }
    else {
        return false;
    }
}
Пример #24
0
bool HRProcessor::test(const Element &, const QString &block)
{
    //! No atomic grouping in python so we simulate it here for performance.
    //! The regex only matches what would be in the atomic group - the HR.
    //! Then check if we are at end of block or if next char is a newline.
    QRegularExpressionMatch m = this->SEARCH_RE.match(block);
    if ( m.hasMatch()
         && ( m.capturedEnd() == block.size()
              || block.at(m.capturedStart()+m.capturedLength()) == '\n' ) ) {
        //! Save match object on class instance so we can use it later.
        this->match = m;
        return true;
    }
    return false;
}
Пример #25
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;
    }
}
Пример #26
0
int QzRegExp::indexIn(const QString &str, int offset) const
{
    QzRegExp* that = const_cast<QzRegExp*>(this);
    QRegularExpressionMatch m = match(str, offset);

    if (!m.hasMatch()) {
        that->m_matchedLength = -1;
        that->m_capturedTexts.clear();
        return -1;
    }

    that->m_matchedLength = m.capturedLength();
    that->m_capturedTexts = m.capturedTexts();
    return m.capturedStart();
}
Пример #27
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;
}
Пример #28
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;
}
bool SearchWorker::searchTxtLoop(QTextStream *intxt, QString searchtype, QString searchTerm, bool singleMatch, QString fullpath, QString displabel)
{
    int matchcount=0;
    QString matchline = "";
    QString firstmatchline = "";

    //prepare fo RegEx
    bool enableRegEx = m_profile.getBoolOption(Profile::EnableRegEx);
    const QRegularExpression searchExpr(searchTerm, QRegularExpression::UseUnicodePropertiesOption);
    if(!searchExpr.isValid()) enableRegEx=false;

    while (!intxt->atEnd()) {
        if (m_cancelled.loadAcquire() == Cancelled)
            return false;
        QString linetxt = intxt->readLine();
        int findpos=0;
        QRegularExpressionMatch matchR;
        //search for several occurences of search text in one line
        while ( (findpos = (enableRegEx ? (matchR = searchExpr.match(linetxt, findpos)).capturedStart()
                                        : linetxt.indexOf(searchTerm, findpos, Qt::CaseInsensitive))) != -1) {
            //prepate line for output
            if (findpos>10) matchline = "\u2026" + linetxt.mid(findpos-10,120);
            else matchline = linetxt.left(120);
            if(matchcount==0) firstmatchline=matchline;
            enableRegEx ? findpos=matchR.capturedEnd() : findpos+=searchTerm.size();
            matchcount++;

            if(!singleMatch) {
                //found result
                //APPS only on single match
                if(searchtype != "APPS") emit matchFound(fullpath, searchtype, displabel, matchline, 0);
            }
            if (m_cancelled.loadAcquire() == Cancelled)
                return false;
        }
    }
    if( singleMatch && (matchcount >0) ) {
        //found result
        if(searchtype == "APPS") {
            displabel = prepareForApps(intxt);
            matchcount = (-1)*matchcount;
            if(displabel.size()>0)
                emit matchFound(fullpath, searchtype, displabel, firstmatchline, matchcount);
        }
        else emit matchFound(fullpath, searchtype, displabel, firstmatchline, matchcount);
    }
    return true;
}
Пример #30
0
void PsUpdateDownloader::partMetaGot() {
	typedef QList<QNetworkReply::RawHeaderPair> Pairs;
	Pairs pairs = reply->rawHeaderPairs();
	for (Pairs::iterator i = pairs.begin(), e = pairs.end(); i != e; ++i) {
		if (QString::fromUtf8(i->first).toLower() == "content-range") {
			QRegularExpressionMatch m = QRegularExpression(qsl("/(\\d+)([^\\d]|$)")).match(QString::fromUtf8(i->second));
			if (m.hasMatch()) {
				{
					QMutexLocker lock(&mutex);
					full = m.captured(1).toInt();
				}
				emit App::app()->updateDownloading(already, full);
			}
		}
	}
}