Esempio n. 1
14
void MainWindow::saveAllSheetsToImages(const QString &fileName)
{
    int indexOfExtension = fileName.indexOf(QRegularExpression("\\.\\w+$"), 0);
    QString currentFileName;
    currentSheetNumber = -1;
    ui->toolBar->actions()[ToolButton::Next]->setEnabled(true);
    ui->svgView->hideBorders(true);

    while (ui->toolBar->actions()[ToolButton::Next]->isEnabled()) //while "Next Sheet" tool button is enabled,
    {                                                             //i.e. while rendering all sheets
        renderNextSheet();
        currentFileName = fileName;

        if (currentSheetNumber > 0 || ui->toolBar->actions()[ToolButton::Next]->isEnabled())
            //i.e. there is more than one sheet
            currentFileName.insert(indexOfExtension, QString("_%1").arg(currentSheetNumber));

        saveSheet(currentFileName);
    }

    ui->svgView->hideBorders(false);

    //we used renderNextSheet() for the first sheet instead of renderFirstSheet()
    //so we need to check the number of sheet and disable previous toolbutton if needed
    if (currentSheetNumber == 0)
        ui->toolBar->actions()[ToolButton::Previous]->setDisabled(true);
}
Esempio n. 2
0
KNMusicLrcParser::KNMusicLrcParser(QObject *parent) :
    QObject(parent),
    m_frameCatchRegExp(QRegularExpression("\\[[^\\]]*\\]")),
    m_noneNumberRegExp(QRegularExpression("[^0-9]")),
    m_utf8Codec(QTextCodec::codecForName("UTF-8")),
    m_localeCodec(knI18n->localeCodec())
{
}
Esempio n. 3
0
/**
 * Does a file name cleanup
 */
QString Note::cleanupFileName(QString name) {
    // remove characters from the name that are problematic
    name.remove(QRegularExpression("[\\/\\\\:]"));

    // remove multiple whitespaces from the name
    name.replace(QRegularExpression("\\s+"), " ");

    return name;
}
Esempio n. 4
0
void AvionShow::addAvion()
{
    Direction * dir=dynamic_cast<Direction *>(g());
    QString idc,idm;
    idc=_idc->model()->index(0,0).data().toString().split(QRegularExpression("\\s+"))[0];
    idm=_idm->model()->index(0,0).data().toString().split(QRegularExpression("\\s+"))[0];
    dir->setIAvion();
    connect(dir,SIGNAL(doneAddingAvion()),this,SLOT(maktir3ambetfidbascava()));
    dir->addAvion(idm,idc,ui->IdAvC->text(),"0");
}
Esempio n. 5
0
QRegularExpression SystemFactory::supportedUpdateFiles() {
#if defined(Q_OS_WIN)
  return QRegularExpression(QSL(".+win.+\\.(exe|7z)"));
#elif defined(Q_OS_MAC)
  return QRegularExpression(QSL(".dmg"));
#elif defined(Q_OS_LINUX)
  return QRegularExpression(QSL(".AppImage"));
#else
  return QRegularExpression(QSL(".*"));
#endif
}
Esempio n. 6
0
void PsUpdateDownloader::initOutput() {
	QString fileName;
	QRegularExpressionMatch m = QRegularExpression(qsl("/([^/\\?]+)(\\?|$)")).match(updateUrl);
	if (m.hasMatch()) {
		fileName = m.captured(1).replace(QRegularExpression(qsl("[^a-zA-Z0-9_\\-]")), QString());
	}
	if (fileName.isEmpty()) {
		fileName = qsl("tupdate-%1").arg(rand());
	}
	QString dirStr = cWorkingDir() + qsl("tupdates/");
	fileName = dirStr + fileName;
	QFileInfo file(fileName);

	QDir dir(dirStr);
	if (dir.exists()) {
		QFileInfoList all = dir.entryInfoList(QDir::Files);
		for (QFileInfoList::iterator i = all.begin(), e = all.end(); i != e; ++i) {
			if (i->absoluteFilePath() != file.absoluteFilePath()) {
				QFile::remove(i->absoluteFilePath());
			}
		}
	} else {
		dir.mkdir(dir.absolutePath());
	}
	outputFile.setFileName(fileName);
	if (file.exists()) {
		uint64 fullSize = file.size();
		if (fullSize < INT_MAX) {
			int32 goodSize = (int32)fullSize;
			if (goodSize % UpdateChunk) {
				goodSize = goodSize - (goodSize % UpdateChunk);
				if (goodSize) {
					if (outputFile.open(QIODevice::ReadOnly)) {
						QByteArray goodData = outputFile.readAll().mid(0, goodSize);
						outputFile.close();
						if (outputFile.open(QIODevice::WriteOnly)) {
							outputFile.write(goodData);
							outputFile.close();

							QMutexLocker lock(&mutex);
							already = goodSize;
						}
					}
				}
			} else {
				QMutexLocker lock(&mutex);
				already = goodSize;
			}
		}
		if (!already) {
			QFile::remove(fileName);
		}
	}
}
Esempio n. 7
0
/**
 * Parses a text document and builds the navigation tree for it
 */
void NavigationWidget::parse(QTextDocument *document) {
    const QSignalBlocker blocker(this);
    Q_UNUSED(blocker);

    setDocument(document);
    clear();
    _lastHeadingItemList.clear();

    for (int i = 0; i < document->blockCount(); i++) {
        QTextBlock block = document->findBlockByNumber(i);
        int elementType = block.userState();

        // ignore all non headline types
        if ((elementType < pmh_H1) || (elementType > pmh_H6)) {
            continue;
        }

        QString text = block.text();

        text.remove(QRegularExpression("^#+"))
                .remove(QRegularExpression("#+$"))
                .remove(QRegularExpression("^\\s+"))
                .remove(QRegularExpression("^=+$"))
                .remove(QRegularExpression("^-+$"));

        if (text.isEmpty()) {
            continue;
        }

        QTreeWidgetItem *item = new QTreeWidgetItem();
        item->setText(0, text);
        item->setData(0, Qt::UserRole, block.position());
        item->setToolTip(0, tr("headline %1").arg(elementType - pmh_H1 + 1));

        // attempt to find a suitable parent item for the element type
        QTreeWidgetItem *lastHigherItem = findSuitableParentItem(elementType);

        if (lastHigherItem == NULL) {
            // if there wasn't a last higher level item then add the current
            // item to the top level
            addTopLevelItem(item);
        } else {
            // if there was a last higher level item then add the current
            // item as child of that item
            lastHigherItem->addChild(item);
        }

        _lastHeadingItemList[elementType] = item;
    }

    expandAll();
}
Esempio n. 8
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 ScintillaEditor::changeSpacesToTabs() {
/*  -changes spaces into tabs */
    //go through the text line by line and replace spaces with tabs
    QStringList editorTextLines = text().split( QRegularExpression("\n") );

    QString textExpression = tr("\\s{2,%1}").arg( tabWidth() );

    for (int i = 0, l = editorTextLines.length(); i < l; i++) {
        editorTextLines[i].replace( QRegularExpression(textExpression), "\t");
    }

    setText( editorTextLines.join("\n") );
}
Esempio n. 10
0
void FloorCapVector::UnpackVector()
{
    Q_D(FloorCapVector);
    d->m_FloorVal.clear();
    d->m_CapVal.clear();
    if (d->m_Vector.isEmpty()) return;
    ExtractAnchorDate();
    QString TempVec(d->m_Vector.trimmed().toUpper());
    QStringList StringParts = TempVec.trimmed().toUpper().split(QRegularExpression("\\s"), QString::SkipEmptyParts);
    int StepLen;
    QString TempStr;
    for (int i = 1; i < StringParts.size(); i += 2) {
        TempStr = StringParts.at(i);
        TempStr.replace(QRegularExpression("\\D"), "");
        StepLen = TempStr.toInt();
        TempStr = StringParts.at(i);
        TempStr.replace(QRegularExpression("\\d"), "");
        for (int j = 0; j < StepLen; j++) {
            QString RawVal = StringParts.at(i - 1);
            RawVal.replace("[", "");
            RawVal.replace("]", "");
            auto CapFloor = RawVal.split(',', QString::KeepEmptyParts);
            if (CapFloor.size() > 0) {
                if (CapFloor.at(0).isEmpty()) d->m_FloorVal.append(std::shared_ptr<double>(nullptr));
                else d->m_FloorVal.append(std::make_shared<double>(CapFloor.at(0).toDouble()));
            }
            else d->m_FloorVal.append(std::shared_ptr<double>(nullptr));
            if (CapFloor.size() > 1) {
                if (CapFloor.at(1).isEmpty()) d->m_CapVal.append(std::shared_ptr<double>(nullptr));
                else d->m_CapVal.append(std::make_shared<double>(CapFloor.at(1).toDouble()));
            }
            else d->m_CapVal.append(std::shared_ptr<double>(nullptr));
        }
    }
    {
        QString RawVal = StringParts.last();
        RawVal.replace("[", "");
        RawVal.replace("]", "");
        auto CapFloor = RawVal.split(',', QString::KeepEmptyParts);
        if (CapFloor.size() > 0) {
            if (CapFloor.at(0).isEmpty()) d->m_FloorVal.append(std::shared_ptr<double>(nullptr));
            else d->m_FloorVal.append(std::make_shared<double>(CapFloor.at(0).toDouble()));
        }
        else d->m_FloorVal.append(std::shared_ptr<double>(nullptr));
        if (CapFloor.size() > 1) {
            if (CapFloor.at(1).isEmpty()) d->m_CapVal.append(std::shared_ptr<double>(nullptr));
            else d->m_CapVal.append(std::make_shared<double>(CapFloor.at(1).toDouble()));
        }
        else d->m_CapVal.append(std::shared_ptr<double>(nullptr));
    }
}
Esempio n. 11
0
QPointF SymbolDataEditor::getMovePoint(const QString &path)
{
    QString move = QRegularExpression("^[mM] *-?\\d+\\.?\\d*,? ?-?\\d+\\.?\\d*").match(path).captured();
    move.remove(QRegularExpression("^[mM] *"));
    int indexOfSeparator = move.indexOf(QRegularExpression("[ ,]"));

    if (indexOfSeparator >= 0 && indexOfSeparator + 1 < move.size())
    {
        QString x = move.left(indexOfSeparator);
        QString y = move.mid(indexOfSeparator + 1);
        return QPointF(x.toDouble(), y.toDouble());
    }

    return QPointF(0.0, 0.0);
}
Esempio n. 12
0
/*
  Creates a valid sheet name
    minimum length is 1
    maximum length is 31
    doesn't contain special chars: / \ ? * ] [ :
    Sheet names must not begin or end with ' (apostrophe)

  Invalid characters are replaced by one space character ' '.
 */
QString createSafeSheetName(const QString &nameProposal)
{
    if (nameProposal.isEmpty())
        return QString();

    QString ret = nameProposal;
    if (nameProposal.contains(QRegularExpression(QStringLiteral("[/\\\\?*\\][:]+"))))
        ret.replace(QRegularExpression(QStringLiteral("[/\\\\?*\\][:]+")), QStringLiteral(" "));
    while(ret.contains(QRegularExpression(QStringLiteral("^\\s*'\\s*|\\s*'\\s*$"))))
        ret.remove(QRegularExpression(QStringLiteral("^\\s*'\\s*|\\s*'\\s*$")));
    ret = ret.trimmed();
    if (ret.size() > 31)
        ret = ret.left(31);
    return ret;
}
Esempio n. 13
0
File: jobs.cpp Progetto: aelog/ark
void LoadJob::onNewEntry(const Archive::Entry *entry)
{
    m_extractedFilesSize += entry->property("size").toLongLong();
    m_isPasswordProtected |= entry->property("isPasswordProtected").toBool();

    if (entry->isDir()) {
        m_dirCount++;
    } else {
        m_filesCount++;
    }

    if (m_isSingleFolderArchive) {
        // RPM filenames have the ./ prefix, and "." would be detected as the subfolder name, so we remove it.
        const QString fullPath = entry->fullPath().replace(QRegularExpression(QStringLiteral("^\\./")), QString());
        const QString basePath = fullPath.split(QLatin1Char('/')).at(0);

        if (m_basePath.isEmpty()) {
            m_basePath = basePath;
            m_subfolderName = basePath;
        } else {
            if (m_basePath != basePath) {
                m_isSingleFolderArchive = false;
                m_subfolderName.clear();
            }
        }
    }
}
Esempio n. 14
0
void Application::startUpdateCheck(bool forceWait) {
	updateCheckTimer.stop();
	if (updateRequestId || updateThread || updateReply || !cAutoUpdate()) return;
	
	int32 updateInSecs = cLastUpdateCheck() + 3600 + (rand() % 3600) - unixtime();
	bool sendRequest = (updateInSecs <= 0 || updateInSecs > 7200);
	if (!sendRequest && !forceWait) {
		QDir updates(cWorkingDir() + "tupdates");
		if (updates.exists()) {
			QFileInfoList list = updates.entryInfoList(QDir::Files);
			for (QFileInfoList::iterator i = list.begin(), e = list.end(); i != e; ++i) {
                if (QRegularExpression("^(tupdate|tmacupd|tlinuxupd|tlinux32upd)\\d+$", QRegularExpression::CaseInsensitiveOption).match(i->fileName()).hasMatch()) {
					sendRequest = true;
				}
			}
		}
	}
    if (cManyInstance() && !cDebug()) return; // only main instance is updating

	if (sendRequest) {
		QNetworkRequest checkVersion(cUpdateURL());
		if (updateReply) updateReply->deleteLater();

		App::setProxySettings(updateManager);
		updateReply = updateManager.get(checkVersion);
		connect(updateReply, SIGNAL(finished()), this, SLOT(updateGotCurrent()));
		connect(updateReply, SIGNAL(error(QNetworkReply::NetworkError)), this, SLOT(updateFailedCurrent(QNetworkReply::NetworkError)));
//		updateRequestId = MTP::send(MTPhelp_GetAppUpdate(MTP_string(cApiDeviceModel()), MTP_string(cApiSystemVersion()), MTP_string(cApiAppVersion()), MTP_string(cApiLang())), rpcDone(&Application::onAppUpdate), rpcFail(&Application::onAppUpdateFail);
		emit updateChecking();
	} else {
		updateCheckTimer.start((updateInSecs + 5) * 1000);
	}
}
Esempio n. 15
0
void WebLoadManager::onMeta() {
	QNetworkReply *reply = qobject_cast<QNetworkReply*>(QObject::sender());
	if (!reply) return;

	Replies::iterator j = _replies.find(reply);
	if (j == _replies.cend()) { // handled already
		return;
	}
	webFileLoaderPrivate *loader = j.value();

	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()) {
				loader->setProgress(qMax(qint64(loader->data().size()), loader->already()), m.captured(1).toLongLong());
				if (!handleReplyResult(loader, WebReplyProcessProgress)) {
					_replies.erase(j);
					_loaders.remove(loader);
					delete loader;

					reply->abort();
					reply->deleteLater();
				}
			}
		}
	}
}
void MCGUILayoutAxis::set(const QString &str) {
    QString s = str;
    if (s.size() <= 0)
        return;
    s.replace(" ", "");
    QStringList a = s.split(QRegularExpression("(?=\\-|\\+)"));
    components.clear();
    for (QString p : a) {
        if (p.length() <= 0)
            continue;
        int i = p.indexOf("%");
        Component c;
        if (i >= 0) {
            c.value = p.midRef(0, i).toFloat() / 100.f;
            if (p.endsWith("x"))
                c.unit = Component::Unit::PERCENT_X;
            else if (p.endsWith("y"))
                c.unit = Component::Unit::PERCENT_Y;
            else
                c.unit = (axis == Axis::X ? Component::Unit::PERCENT_X : Component::Unit::PERCENT_Y);
        } else {
            if (p.endsWith("px"))
                c.value = p.midRef(0, p.length() - 2).toFloat();
            else
                c.value = p.toFloat();

            c.unit = Component::Unit::PIXELS;
        }
        components.push_back(c);
    }
}
void ExperimentConditionsDialog::read_energies_from_file(QString filename) {
    energies.clear();
    QFile file(filename);
    if(file.open(QFile::ReadOnly)) {
        QTextStream in(&file);
        auto line = in.readLine();
        while(!line.isNull()) {
            double energy = line.section(QRegularExpression("\\s+"), 0, 0).toDouble();
            double intensity = line.section(QRegularExpression("\\s+"), 1, 1).toDouble();
            energies[energy] += intensity;
            line = in.readLine();
        }
    } else {
        QMessageBox::critical(this, "File access error", "Could not open file " + ui->projectile_energy_file_name->text());
    }
}
Esempio n. 18
0
Shield::Shield(QObject *parent) :
QObject(parent), d_ptr(new ShieldPrivate)
{
	Q_D(Shield);
	ins = this;
	QJsonArray s = Config::getValue<QJsonArray>("/Shield/Sender");
	QJsonArray r = Config::getValue<QJsonArray>("/Shield/Regexp");
	for (const QJsonValue &item : s){
		d->shieldS.insert(item.toString());
	}
	for (const QJsonValue &item : r){
		d->shieldR.append(QRegularExpression(item.toString()));
	}
	int group = Config::getValue("/Shield/Group", 0);
	for (int i = 7; i >= 0; --i){
		d->shieldG[i] = group & 1;
		group = group >> 1;
	}
	connect(Config::instance(), &Config::aboutToSave, [d]{
		QJsonArray s, r;
		for (auto &item : d->shieldS){
			s.append(item);
		}
		Config::setValue("/Shield/Sender", s);
		for (auto &item : d->shieldR){
			r.append(item.pattern());
		}
		Config::setValue("/Shield/Regexp", r);
		int g = 0;
		for (int i = 0; i < 8; ++i){
			g = (g << 1) + d->shieldG[i];
		}
		Config::setValue("/Shield/Group", g);
	});
}
Esempio n. 19
0
void PmrWindowWidget::filter(const QString &pFilter)
{
    // Filter our list of exposures and remove any duplicates (they will be
    // 'reintroduced' in the next step)

    QStringList filteredExposureNames = mExposureNames.filter(QRegularExpression(pFilter, QRegularExpression::CaseInsensitiveOption));

    mNumberOfFilteredExposures = filteredExposureNames.count();

    filteredExposureNames.removeDuplicates();

    // Update our message and show/hide the relevant exposures

    page()->mainFrame()->documentElement().findFirst("p[id=message]").setInnerXml(message());

    QWebElement trElement = page()->mainFrame()->documentElement().findFirst(QString("tbody[id=exposures]")).firstChild();
    QWebElement ulElement;

    for (int i = 0, iMax = mExposureNames.count(); i < iMax; ++i) {
        if (mExposureDisplayed[i] != filteredExposureNames.contains(mExposureNames[i])) {
            QString displayValue = mExposureDisplayed[i]?"none":"table-row";

            trElement.setStyleProperty("display", displayValue);

            ulElement = trElement.firstChild().firstChild().nextSibling();

            if (ulElement.hasClass("visible"))
                ulElement.setStyleProperty("display", displayValue);

            mExposureDisplayed[i] = !mExposureDisplayed[i];
        }

        trElement = trElement.nextSibling();
    }
}
Esempio n. 20
0
void QtWebEnginePage::handlePageLoaded(const QString &result)
{
	QString string(url().toString());
	string.truncate(1000);

	const QRegularExpressionMatch match = QRegularExpression(QStringLiteral(">(<img style=\"-webkit-user-select: none;(?: cursor: zoom-in;)?\"|<video controls=\"\" autoplay=\"\" name=\"media\"><source) src=\"%1").arg(QRegularExpression::escape(string))).match(result);
	const bool isViewingMedia = match.hasMatch();

	if (isViewingMedia && match.captured().startsWith(QLatin1String("><img")))
	{
		settings()->setAttribute(QWebEngineSettings::AutoLoadImages, true);
		settings()->setAttribute(QWebEngineSettings::JavascriptEnabled, true);

		QFile file(QLatin1String(":/modules/backends/web/qtwebengine/resources/imageViewer.js"));
		file.open(QIODevice::ReadOnly);

		runJavaScript(file.readAll());

		file.close();
	}

	if (isViewingMedia != m_isViewingMedia)
	{
		m_isViewingMedia = isViewingMedia;

		emit viewingMediaChanged(m_isViewingMedia);
	}
}
Esempio n. 21
0
std::string Item::correct_name (const std::string &string) {

    QString name = QString::fromStdString(string);

    QRegularExpression has_adj_rx("<if:(.*?)>{");
    QRegularExpressionMatch has_adj_match = has_adj_rx.match(name);

    if (has_adj_match.hasMatch()) {
        QRegularExpression short_rx("<<set:(.*?)>>");
        QRegularExpressionMatch short_match = short_rx.match(name);
        QString adj_short = short_match.captured(1);

        QRegularExpression word_rx("if:" + adj_short + ">{(.*?)}");
        QRegularExpressionMatch word_match = word_rx.match(name);
        QString adj_word = word_match.captured(1);

        QRegularExpression last_rx("[^}]*$");
        QRegularExpressionMatch last_match = last_rx.match(name);
        QString last_word = last_match.captured(0);

        return adj_word.toStdString() + last_word.toStdString();
    }
    else {
        return name.remove(QRegularExpression("<(.*)>")).toStdString();
    }
}
Esempio n. 22
0
void Indenter::indentBlock(const QTextBlock &block,
                           const QChar &,
                           const TextEditor::TabSettings &settings,
                           int)
{
    int indent;

    QTextBlock previous = block.previous();
    // Previous line ends on comma, ignore everything and follow the indent
    if (previous.text().endsWith(',')) {
        indent = previous.text().indexOf(QRegularExpression("\\S")) / settings.m_indentSize;
    } else {
        // Use the stored indent plus some bizarre heuristics that even myself remember how it works.
        indent = block.userState() >> 20;
        if (indent < 0) {
            while (indent == -1 && previous.isValid()) {
                indent = previous.userState() >> 20;
                previous = previous.previous();
            }
        }

        if (didBlockStart(block) && indent > 0)
            indent--;
    }

    settings.indentLine(block, indent  * settings.m_indentSize);
}
Esempio n. 23
0
QStringList getSectionEnums(QString &section)
{
    QStringList result;
    QRegularExpressionMatchIterator currMatchIter = BL_ENUMERATED.globalMatch(section);

    while (currMatchIter.hasNext() )
    {
        result.append(currMatchIter.next().captured(1).remove(QRegularExpression("\\s") ).split(",") );

        #ifdef DEBUG
            qDebug() << "\n~~~~~~\n";
        #endif

        int resIter;
        for (resIter = 0; resIter < result.size()-1; ++resIter)
        {
            section.remove(result.at(resIter) );

            #ifdef DEBUG
                qDebug() << result.at(resIter).toLatin1().constData() << "\n";
            #endif
        }

        #ifdef DEBUG
            qDebug() << result.last().toLatin1().constData() << "\n";
        #endif
    }

    return result;
}   /* getSectionEnums */
Esempio n. 24
0
void Widget::removeFunction()
{
    //! [37]
    QString s = "Montreal";
    s.remove(1, 4);
    // s == "Meal"
    //! [37]

    //! [38]
    QString t = "Ali Baba";
    t.remove(QChar('a'), Qt::CaseInsensitive);
    // t == "li Bb"
    //! [38]

    //! [39]
    QString r = "Telephone";
    r.remove(QRegExp("[aeiou]."));
    // r == "The"
    //! [39]

    //! [96]
    QString r = "Telephone";
    r.remove(QRegularExpression("[aeiou]."));
    // r == "The"
    //! [96]
}
QString RawHtmlPostprocessor::run(const QString &text)
{
    std::shared_ptr<Markdown> markdown = this->markdown.lock();

    OrderedDict<QString> replacements;
    for ( int i = 0; i < markdown->htmlStash.html_counter; ++i ) {
        HtmlStash::Item item = markdown->htmlStash.rawHtmlBlocks[i];
        QString html = item.first;
        bool safe = item.second;
        if ( markdown->safeMode() != Markdown::default_mode && ! safe ) {
            if ( markdown->safeMode() == Markdown::escape_mode ) {
                html = this->escape(html);
            } else if ( markdown->safeMode() == Markdown::remove_mode ) {
                html = QString();
            } else {
                html = markdown->html_replacement_text();
            }
        }
        if ( this->isblocklevel(html) && ( safe || ! markdown->safeMode() ) ) {
            replacements[QString("<p>%1</p>").arg(markdown->htmlStash.get_placeholder(i))] = html+"\n";
        }
        replacements[markdown->htmlStash.get_placeholder(i)] = html;
    }
    QString result = text;
    if ( replacements.size() > 0 ) {
        pypp::str pattern = pypp::map(pypp::re::escape, replacements.keys()).join("|");
        result = pypp::re::sub(QRegularExpression(pattern), [&](const QRegularExpressionMatch &m) -> pypp::str {
            return replacements[m.captured()];
        }, result);
    }
    return result;
}
// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
void DataContainerCreationWidget::setupGui()
{
  blockSignals(true);
  if (getFilterParameter() != NULL)
  {
    label->setText(getFilterParameter()->getHumanLabel() );

    QString str = getFilter()->property(PROPERTY_NAME_AS_CHAR).toString();
    dataContainerName->setText(str);
  }
  blockSignals(false);

  applyChangesBtn->setVisible(false);

  // Do not allow the user to put a forward slash into the dataContainerName line edit
  dataContainerName->setValidator(new QRegularExpressionValidator(QRegularExpression("[^/]*"), this));

  // Catch when the filter is about to execute the preflight
  connect(getFilter(), SIGNAL(preflightAboutToExecute()),
          this, SLOT(beforePreflight()));

  // Catch when the filter is finished running the preflight
  connect(getFilter(), SIGNAL(preflightExecuted()),
          this, SLOT(afterPreflight()));

  // Catch when the filter wants its dataContainerNames updated
  connect(getFilter(), SIGNAL(updateFilterParameters(AbstractFilter*)),
          this, SLOT(filterNeedsInputParameters(AbstractFilter*)));


  connect(dataContainerName, SIGNAL(textChanged(const QString&)),
          this, SLOT(widgetChanged(const QString&)));

}
Esempio n. 27
0
TextWithTags::Tags ConvertEntitiesToTextTags(const EntitiesInText &entities) {
	TextWithTags::Tags result;
	if (entities.isEmpty()) {
		return result;
	}

	result.reserve(entities.size());
	for (const auto &entity : entities) {
		const auto push = [&](const QString &tag) {
			result.push_back({ entity.offset(), entity.length(), tag });
		};
		switch (entity.type()) {
		case EntityInTextMentionName: {
			auto match = QRegularExpression("^(\\d+\\.\\d+)$").match(entity.data());
			if (match.hasMatch()) {
				push(kMentionTagStart + entity.data());
			}
		} break;
		case EntityInTextCustomUrl: {
			const auto url = entity.data();
			if (Ui::InputField::IsValidMarkdownLink(url)
				&& !IsMentionLink(url)) {
				push(url);
			}
		} break;
		case EntityInTextBold: push(Ui::InputField::kTagBold); break;
		case EntityInTextItalic: push(Ui::InputField::kTagItalic); break;
		case EntityInTextCode: push(Ui::InputField::kTagCode); break;
		case EntityInTextPre: push(Ui::InputField::kTagPre); break;
		}
	}
	return result;
}
Esempio n. 28
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;
  }
Esempio n. 29
0
bool AddressWidget::isAddress(const QString &text)
{
	const QUrl url = QUrl::fromUserInput(text);

	if (!QRegularExpression(QLatin1String("^(\\w+\\:\\S+)|([\\w\\-]+\\.[a-zA-Z]{2,}(/\\S*)?$)")).match(text).hasMatch() || !url.isValid())
	{
		const QString shortcut = text.section(QLatin1Char(' '), 0, 0);
		const QStringList engines = SearchesManager::getSearchEngines();
		SearchInformation *engine = NULL;

		for (int i = 0; i < engines.count(); ++i)
		{
			engine = SearchesManager::getSearchEngine(engines.at(i));

			if (engine && shortcut == engine->shortcut)
			{
				emit requestedSearch(text.section(QLatin1Char(' '), 1), engine->identifier);

				return false;
			}
		}

		emit requestedSearch(text, SettingsManager::getValue(QLatin1String("Browser/DefaultSearchEngine")).toString());

		return false;
	}

	return true;
}
Esempio n. 30
0
void Highlighter::addRule(const QString &pattern, const QBrush &brush)
{
	HighlightingRule rule;
	rule.pattern = QRegularExpression(pattern);
	rule.format.setForeground(brush);
	highlightingRules.append(rule);
}