Exemple #1
0
AnimExpression::Token AnimExpression::consumeNumber(const QString& str, QString::const_iterator& iter) const {
    assert(iter != str.end());
    assert(iter->isDigit());
    auto begin = iter;
    while (iter->isDigit() && iter != str.end()) {
        ++iter;
    }

    // parse whole integer part
    int pos = (int)(begin - str.begin());
    int len = (int)(iter - begin);
    QString sub = QStringRef(const_cast<const QString*>(&str), pos, len).toString();
    int whole = sub.toInt();

    // parse optional fractional part
    if (iter->unicode() == '.') {
        iter++;
        auto begin = iter;
        while (iter->isDigit() && iter != str.end()) {
            ++iter;
        }

        int pos = (int)(begin - str.begin());
        int len = (int)(iter - begin);
        QString sub = QStringRef(const_cast<const QString*>(&str), pos, len).toString();
        int fraction = sub.toInt();

        return Token(computeFloat(whole, fraction));

    } else {
        return Token(whole);
    }
}
std::pair<int, Snake> Parser::snakeFromString(const QString &t_message) const
{
    auto id = QStringRef(&t_message, 1, 1).toInt();
    auto snake = Snake::fromString(QStringRef(&t_message, 3, t_message.size() - 3).toString());
    qDebug() << snake.toString();
    return { id, std::move(snake) };
}
Exemple #3
0
Object* OgrFileImport::importPointGeometry(MapPart* map_part, OGRFeatureH feature, OGRGeometryH geometry)
{
	auto style = OGR_F_GetStyleString(feature);
	auto symbol = getSymbol(Symbol::Point, style);
	if (symbol->getType() == Symbol::Point)
	{
		auto object = new PointObject(symbol);
		object->setPosition(toMapCoord(OGR_G_GetX(geometry, 0), OGR_G_GetY(geometry, 0)));
		map_part->addObject(object);
		return object;
	}
	else if (symbol->getType() == Symbol::Text)
	{
		const auto& description = symbol->getDescription();
		auto length = description.length();
		auto split = description.indexOf(QLatin1Char(' '));
		Q_ASSERT(split > 0);
		Q_ASSERT(split < length);
		
		auto label = description.right(length - split - 1);
		if (label.startsWith('{') && label.endsWith('}'))
		{
			label.remove(0,1);
			label.chop(1);
			int index = OGR_F_GetFieldIndex(feature, label.toLatin1());
			if (index >= 0)
			{
				label = QString(OGR_F_GetFieldAsString(feature, index));
			}
		}
		if (!label.isEmpty())
		{
			auto object = new TextObject(symbol);
			object->setAnchorPosition(toMapCoord(OGR_G_GetX(geometry, 0), OGR_G_GetY(geometry, 0)));
			// DXF observation
			label.replace(QRegularExpression("(\\\\[^;]*;)*", QRegularExpression::MultilineOption), QString::null);
			label.replace(QLatin1String("^I"), "\t");
			object->setText(label);
			
			bool ok;
			auto anchor = QStringRef(&description, 1, 2).toInt(&ok);
			if (ok)
			{
				applyLabelAnchor(anchor, object);
			}
				
			auto angle = QStringRef(&description, 3, split-3).toFloat(&ok);
			if (ok)
			{
				object->setRotation(qDegreesToRadians(angle));
			}
			
			map_part->addObject(object);
			return object;
		}
	}
	
	return nullptr;
}
/*!
  \internal

   Treats \a outputItem as a node and calls the appropriate function,
   e.g., attribute() or comment(), depending on its
   QXmlNodeModelIndex::NodeKind.

   This is a helper function that subclasses can use to multiplex
   Nodes received via item().
 */
void QAbstractXmlReceiver::sendAsNode(const QPatternist::Item &outputItem)
{
    Q_ASSERT(outputItem);
    Q_ASSERT(outputItem.isNode());
    const QXmlNodeModelIndex asNode = outputItem.asNode();

    switch(asNode.kind())
    {
        case QXmlNodeModelIndex::Attribute:
        {
            const QString &v = outputItem.stringValue();
            attribute(asNode.name(), QStringRef(&v));
            return;
        }
        case QXmlNodeModelIndex::Element:
        {
            startElement(asNode.name());

            /* First the namespaces, then attributes, then the children. */
            asNode.sendNamespaces(this);
            sendFromAxis<QXmlNodeModelIndex::AxisAttribute>(asNode);
            sendFromAxis<QXmlNodeModelIndex::AxisChild>(asNode);

            endElement();

            return;
        }
        case QXmlNodeModelIndex::Text:
        {
            const QString &v = asNode.stringValue();
            characters(QStringRef(&v));
            return;
        }
        case QXmlNodeModelIndex::ProcessingInstruction:
        {
            processingInstruction(asNode.name(), outputItem.stringValue());
            return;
        }
        case QXmlNodeModelIndex::Comment:
        {
            comment(outputItem.stringValue());
            return;
        }
        case QXmlNodeModelIndex::Document:
        {
            startDocument();
            sendFromAxis<QXmlNodeModelIndex::AxisChild>(asNode);
            endDocument();
            return;
        }
        case QXmlNodeModelIndex::Namespace:
            Q_ASSERT_X(false, Q_FUNC_INFO, "Not implemented");
    }

    Q_ASSERT_X(false, Q_FUNC_INFO,
               QString::fromLatin1("Unknown node type: %1").arg(asNode.kind()).toUtf8().constData());
}
/*!
    return layout offset for a \a filePath, \a layout, \a section.

    Only acceptable separator for filePath is '/'.
*/
int HbSharedCache::layoutDefinitionOffset(const QString &filePath,
                                          const QString &layout,
                                          const QString &section) const
{
    int offset = -1;
    int position = 0;
    int length = filePath.length();
    if (filePath.at(0) == ':') {
        //resource css use only file name as a key.
        int index = filePath.lastIndexOf('/');
        if (index >= 0) {
            position = index + 1;
            length = filePath.length() - position;
        }
    }
    if (mOffsetItemCount > 0) {
        //try first in prebuilt offset map.
        length -= WidgetMLFileExtension.length();
        QStringRef widgetname(&filePath, position, length);
        HbOffsetItem find(hash(widgetname));
        const HbOffsetItem *end = mOffsetItems + mOffsetItemCount;
        const HbOffsetItem *offsetItem = qBinaryFind(mOffsetItems, end, find);
        if (offsetItem != end) {
#ifdef CSSBIN_TRACES
            qDebug() << "Offset item found from static cache map for widget: " << widgetname;
#endif
            int tableSize = 0;
            const HbLayoutIndexItem *begin = layoutIndexItemBegin(
                    offsetItem->offsetLayoutIndexTable, &tableSize);
            if (begin) {
                const HbLayoutIndexItem *end = begin + tableSize;
                HbLayoutIndexItem find(hash(QStringRef(&layout)), hash(QStringRef(&section)));
                const HbLayoutIndexItem *item = qBinaryFind(begin, end, find);
                if (item != end) {
#ifdef CSSBIN_TRACES
                    qDebug() << "Layout definition offset found for layout: " << layout;
#endif
                    offset = item->offset;
                }
            }
        }
    }
    if (offset == -1) {
        QStringRef filePathRef(&filePath, position, filePath.length() - position);
        QString key;
        key.reserve(filePathRef.length() + 2 //key separators
                    + layout.length() + section.length());
        key.append(filePathRef)
           .append(KeySeparator)
           .append(layout)
           .append(KeySeparator)
           .append(section);
        offset = findOffsetFromDynamicMap(LayoutDefinition, QStringRef(&key));
    }
    return offset;
}
static bool parseVersion(const QString &str, int *major, int *minor)
{
    const int dotIndex = str.indexOf(QLatin1Char('.'));
    if (dotIndex != -1 && str.indexOf(QLatin1Char('.'), dotIndex + 1) == -1) {
        bool ok = false;
        *major = parseInt(QStringRef(&str, 0, dotIndex), &ok);
        if (ok)
            *minor = parseInt(QStringRef(&str, dotIndex + 1, str.length() - dotIndex - 1), &ok);
        return ok;
    }
    return false;
}
void loadMFile(QString f, QMap<QString, QString>& map){
	QFile i(f);QString t, n;
	i.open(QFile::ReadOnly | QFile::Text);
	while(!i.atEnd()){
		t = i.readLine();
		t = QStringRef(&t, 0, t.length()-1).toString();
		n = QStringRef(&t, t.indexOf(" ")+1, t.length()-t.indexOf(" ")).toString();
		t = QStringRef(&t, 0, t.indexOf(" ")-1).toString();

		map.insert(t, n);
	}
	i.close();
}
QStringRef QDeclarativeStyledTextPrivate::parseValue(const QChar *&ch, const QString &textIn)
{
    int valStart = ch - textIn.constData();
    int valLength = 0;
    while (*ch != singleQuote && *ch != doubleQuote && !ch->isNull()) {
        ++valLength;
        ++ch;
    }
    if (ch->isNull())
        return QStringRef();
    ++ch; // skip quote

    return QStringRef(&textIn, valStart, valLength);
}
QSharedPointer<MediaFile> NetworkManager::parseMedia(const QString &path, QHttpResponse *resp)
{
    int idx = path.lastIndexOf("/");
    if(idx <= 0 || idx++ == path.length())
    {
        sendError(QHttpResponse::STATUS_BAD_REQUEST, resp);
        return QSharedPointer<MediaFile>();
    }
    bool ok;
    int pngOffset = path.lastIndexOf(".png") > 0 ? 4 : 0;
    int mediaId = QStringRef(&path, idx, path.length() - idx - pngOffset).toInt(&ok);
    if(!ok)
    {
        sendError(QHttpResponse::STATUS_BAD_REQUEST, resp);
        return QSharedPointer<MediaFile>();
    }
    QSharedPointer<MediaFile> mediaEntry  = MediaFile::getByMediaId(mediaId);

    if(mediaEntry.isNull())
    {
        sendError(QHttpResponse::STATUS_NOT_FOUND, resp);
        return QSharedPointer<MediaFile>();
    }

    return mediaEntry;
}
Exemple #10
0
void MainWindow::renderNextSheet()
{
    QString text = ui->textEdit->toPlainText();
    text = simplifyEnd(text);
    currentSheetNumber++;
    int lettersToTheEnd = text.length() - sheetPointers.at(currentSheetNumber);
    ui->svgView->hideBorders(false);

    if (preferencesDialog->alternateMargins())
        ui->svgView->changeLeftRightMargins(currentSheetNumber % 2);
    else
        ui->svgView->changeLeftRightMargins(false);

    int endOfSheet = ui->svgView->renderText(QStringRef(&text, sheetPointers.at(currentSheetNumber), lettersToTheEnd));
    endOfSheet += sheetPointers.at(currentSheetNumber);

    ui->toolBar->actions()[5]->setEnabled(true); //enable "Previous Sheet" tool button

    if (endOfSheet >= text.length())    //this sheet is the last
    {
        ui->toolBar->actions()[4]->setDisabled(true); //disable "Next Sheet" tool button
        return;
    }

    if (currentSheetNumber >= sheetPointers.count() - 1) //if this sheet has not yet been rendered,
        sheetPointers.push_back(endOfSheet);             //remember, where the next sheet begins
}
Exemple #11
0
/*!
    \internal
    Parses configuration from \a stream.
*/
void QLoggingSettingsParser::setContent(QTextStream &stream)
{
    _rules.clear();
    QString line;
    while (stream.readLineInto(&line))
        parseNextLine(QStringRef(&line));
}
Exemple #12
0
void EventFactory::serialize(Payload *extension, QXmlStreamWriter *writer)
{
	Event *event = se_cast<Event*>(extension);
	AbstractPayloadFactory *factory = 0;
	QString node;
	const QList<Payload::Ptr> items = event->items();
	if (event->node().isEmpty() && items.isEmpty()) {
		return;
	} else if (!event->node().isEmpty()) {
		node = event->node();
		factory = findFactory(QStringRef(&node));
	} else {
		factory = findFactory(items.at(0)->payloadType());
		node = factory ? factory->features().value(0) : QString();
	}
	if (!factory || node.isEmpty()) {
		Logger::warning() << "Invalid stanza extension at PubSub::Event";
		return;
	}
	writer->writeStartElement(QLatin1String("event"));
	writer->writeDefaultNamespace(NS_EVENT);
	writer->writeStartElement(QLatin1String("items"));
	writer->writeAttribute(QLatin1String("node"), node);
	for (int i = 0; i < items.size(); i++) {
		const Payload::Ptr &entity = items.at(i);
		if (entity->payloadType() != factory->payloadType())
			continue;
		writer->writeStartElement(QLatin1String("item"));
		factory->serialize(entity.data(), writer);
		writer->writeEndElement();
	}
	writer->writeEndElement();
	writer->writeEndElement();
}
/*!
  \internal

   This function may be called instead of characters() if, and only if,
   \a value consists only of whitespace.

   The caller gurantees that \a value is not empty.

   \e Whitespace refers to a sequence of characters that are either
   spaces, tabs, or newlines, in any order. In other words, not all
   the Unicode whitespace category is considered whitespace here.

   However, there is no guarantee or requirement that whitespaceOnly()
   is called for text nodes containing whitespace only. characters()
   may be called just as well. This is why the default implementation
   for whitespaceOnly() calls characters().

   \sa characters()
 */
void QAbstractXmlReceiver::whitespaceOnly(const QStringRef &value)
{
    Q_ASSERT_X(value.toString().trimmed().isEmpty(), Q_FUNC_INFO,
               "The caller must guarantee only whitespace is passed. Use characters() in other cases.");
    const QString &v = value.toString();
    characters(QStringRef(&v));
}
void ImageProvider::loadDir() {
    files->clear();

    QString c = io->getCurrentDir();
    c = c.replace("\\", "/"); //  \/ Dir-only
    io->setCurrentDir(isImg(c) ? QStringRef(&c, 0, c.lastIndexOf('/')).toString() : (c.endsWith('/') ? c : c + '/'));

    for (const QFileInfo &i : QDir(io->getCurrentDir()).entryInfoList({"*.png", "*.jpg", "*.jpeg", "*.gif"},
                                                                      QDir::Files)) {
        files->append(i.absolutePath() + '/' + i.fileName());
    }

    if (isImg(c)) {
        c = c.remove(0, c.lastIndexOf('/') + 1); // File-name only
        for (int i = 0; i < files->size(); i++)
            if (files->value(i, "").endsWith(c))
                current = i;

    } else if (lastPicture.contains(getDir(io->getCurrentDir()))) {
        current = lastPicture.value(getDir(io->getCurrentDir())).toInt(0);
        current = current < files->size() ? current : 0;
    } else {
        current = 0;
    }

    if (io->getCurrentDir() != "")
        loadImage();
}
Exemple #15
0
void MainWindow::renderNextSheet()
{
    currentSheetNumber++;

    if (preferencesDialog->alternateMargins())
        ui->svgView->changeLeftRightMargins(currentSheetNumber % 2);
    else
        ui->svgView->changeLeftRightMargins(false);

    int lettersToTheEnd = text.length() - sheetPointers.at(currentSheetNumber);
    int endOfSheet = ui->svgView->renderText(QStringRef(&text, sheetPointers.at(currentSheetNumber), lettersToTheEnd));
    endOfSheet += sheetPointers.at(currentSheetNumber);

    ui->toolBar->actions()[ToolButton::Previous]->setEnabled(true);
    showSheetNumber(currentSheetNumber);

    if (endOfSheet >= text.length())    //i.e. this sheet is the last
    {
        ui->toolBar->actions()[ToolButton::Next]->setDisabled(true);
        return;
    }

    if (currentSheetNumber >= sheetPointers.count() - 1) //if this sheet has not yet been rendered,
        sheetPointers.push_back(endOfSheet);             //remember, where the next sheet begins
}
Exemple #16
0
bool TreeSearch::on_match_helper() {
    //check if matches with Diacritics
    filled_details = false;
    fill_details();
    int startPos = info.start, subpos, last;

    if (reduce_thru_diacritics) {
        int count = sub_positionsOFCurrentMatch.count();

        for (int k = 0; k < count; k++) {
            subpos = sub_positionsOFCurrentMatch[k]; //getLastDiacritic(position-1,info.text)-1);
            QStringRef subword = addlastDiacritics(startPos, subpos, info.text, last);

            //qDebug() <<subword;
            for (int j = 0; j < possible_raw_datasOFCurrentMatch[k].count(); j++) {
                QString rawdata = possible_raw_datasOFCurrentMatch[k][j].getActual();
                bool raw_has_diacritics = startPos > 0 && isDiacritic((*info.text)[startPos - 1]);
                bool input_ended_with_diacritic = subword.size() > 0 && isDiacritic(subword.at(subword.size() - 1));

                if (raw_has_diacritics ||
                    input_ended_with_diacritic) {//in this case we can assume we are working in the first suffix or recursive affixes whose diacritics are for those before them
                    QStringRef diacritics_of_word = getDiacriticsBeforePosition(startPos, info.text),
                               diacritics_of_rawdata = (rawdata.size() > 0 ? addlastDiacritics(0, 0,
                                                        &rawdata) : QStringRef()); //to get first couple of diacritics of raw_data without letters

                    if (!equal(diacritics_of_word, diacritics_of_rawdata, true)) { //force_shadde
                        possible_raw_datasOFCurrentMatch[k].removeAt(j);
                        j--;
                        continue;
                    }
                }

                if (!equal(subword, rawdata, true)) { //force_shadde
                    possible_raw_datasOFCurrentMatch[k].removeAt(j);
                    j--;
                }
            }

            startPos = subpos + 1;
        }

        for (int i = 0; i < possible_raw_datasOFCurrentMatch.count(); i++)
            if (0 == possible_raw_datasOFCurrentMatch[i].count()) {
                return true;    //not matching, continue without doing anything
            }
    } else {
        last = getLastDiacritic(position - 1, info.text);
    }

    info.finish = last - 1;
    position = last;

    if (!onMatch()) {
        return false;
    } else {
        return true;
    }
}
Exemple #17
0
QStringList split(cqstring s, cqstring sep, cqstring tq, QString::SplitBehavior behavior) {
	QStringList parts;

	int len = s.length();
	int tqLen = tq.length();
	int i = 0;

	while (i <= len) {
		int start, end;
		if (tqLen > 0 && QStringRef(&s, i, len - i).startsWith(tq)) {
			// part with text qualifier
			start = i + tqLen;
			end = s.indexOf(tq, start);
			if (end == -1) {
				// no closing text qualifier found, point i to the end of the string
				i = len - 1;
			} else {
				// point i to the beginning of the separator (there should be one after the closing text qualifier)
				i = end == -1 ? len - 1 : end + tqLen;
			}
		} else {
			// part without text qualifier
			start = i;
			end = s.indexOf(sep, i);
			if (end == -1) end = len;
			i = end; // point i to the beginning of the separator
		}

		// add part
		if (end - start > 0 || behavior == QString::KeepEmptyParts) {
			// add part, even it is empty
			parts << QStringRef(&s, start, end - start).toString();
		} // else part is empty and behavior was set to QString::SkipEmptyParts
		
		// if we are not at the end of the string, there must be a separator
		if (i < len && !QStringRef(&s, i, len - i).startsWith(sep)) {
			// incorrect formatted input string
			throw std::invalid_argument(QString("Missing separator at position %1 of '%2', last part2: '%3', i: %4, len: %5").arg(i).arg(s).arg(QStringRef(&s, start, end - start).toString()).arg(i).arg(len).toStdString());
		}
		// skip the separator
		i += sep.length();
	}

	return parts;
}
Exemple #18
0
TEST(Log, Types)
{
    TestLogMsgHandler handler1;
    LogControl logControl;
    logControl.registerMsgHandler(&handler1);
    TestUtilLogControlSwap swap(&logControl);

    char c = 'c';
    TRACE("msg:" << QChar('a') << 'b' << c);
    EXPECT_TRUE(handler1.lastLogMsg.text == QString("msg: a b c"));

    TRACE("msg:" << false << true);
    EXPECT_TRUE(handler1.lastLogMsg.text == QString("msg: false true"));

    signed short signedShort = 10;
    unsigned short unsignedShort = 20;
    TRACE("msg:" << signedShort << unsignedShort);
    EXPECT_TRUE(handler1.lastLogMsg.text == QString("msg: 10 20"));

    signed int signedInt = 10;
    unsigned int unsignedInt = 20;
    TRACE("msg:" << signedInt << unsignedInt);
    EXPECT_TRUE(handler1.lastLogMsg.text == QString("msg: 10 20"));

    signed long signedLong = 10;
    unsigned long unsignedLong = 20;
    TRACE("msg:" << signedLong << unsignedLong);
    EXPECT_TRUE(handler1.lastLogMsg.text == QString("msg: 10 20"));

    qint64 signedLong64 = 10;
    quint64 unsignedLong64 = 20;
    TRACE("msg:" << signedLong64 << unsignedLong64);
    EXPECT_TRUE(handler1.lastLogMsg.text == QString("msg: 10 20"));

    float f = 0.5;
    double d = 1.55;
    TRACE("msg:" << f << d);
    EXPECT_TRUE(handler1.lastLogMsg.text == QString("msg: 0.5 1.55"));

    QString str("str1");
    TRACE("msg:" << QStringRef(&str, 1, 2));
    EXPECT_TRUE(handler1.lastLogMsg.text == QString("msg: tr"));

    TRACE("msg:" << QLatin1String("str1"));
    EXPECT_TRUE(handler1.lastLogMsg.text == QString("msg: str1"));

    QByteArray bytes("string1", 3);
    TRACE("msg:" << bytes);
    EXPECT_TRUE(handler1.lastLogMsg.text == QString("msg: str"));

    QStringList list;
    list << "one" << "two" << "three";
    TRACE("msg:" << list);
    EXPECT_TRUE(handler1.lastLogMsg.text == QString("msg: [one, two, three]")) << handler1.lastLogMsg.text;

    swap.restore();
}
void QQuickStyledTextPrivate::appendText(const QString &textIn, int start, int length, QString &textOut)
{
    if (prependSpace)
        textOut.append(space);
    textOut.append(QStringRef(&textIn, start, length));
    prependSpace = false;
    hasSpace = false;
    hasNewLine = false;
}
Exemple #20
0
static QStringRef joinTokens(const QVarLengthArray<QStringRef>& tokens)
{
	Q_ASSERT(!tokens.isEmpty());

	const QStringRef& last = tokens[tokens.size() - 1];
	int start = tokens[0].position();
	int end = last.position() + last.size();

	return QStringRef(last.string(), start, end - start);
}
void loadFile(QString f, QStringList& list){
	QFile i(f);QString t;
	i.open(QFile::ReadOnly | QFile::Text);
	while(!i.atEnd()){
		t = i.readLine();
		t = QStringRef(&t, 0, t.length()-1).toString();
		list << t;
	}
	i.close();
}
void tst_QAbstractXmlReceiver::charactersStringRef() const
{
    TestAbstractXmlReceiver receiver;

    const QString input(QLatin1String("input"));

    QCOMPARE(receiver.receivedFromCharacters, QString());
    receiver.characters(QStringRef(&input));
    QCOMPARE(receiver.receivedFromCharacters, QString::fromLatin1("input"));
}
void tst_QAbstractXmlReceiver::attributeQXmlNameStringRef() const
{
    TestAbstractXmlReceiver receiver;

    const QString input(QLatin1String("input"));

    QCOMPARE(receiver.receivedFromAttribute, QString());
    receiver.attribute(QXmlName(), QStringRef(&input));
    QCOMPARE(receiver.receivedFromAttribute, QString::fromLatin1("input"));
}
Exemple #24
0
    /**
     * Build the segment array by parsing the path. when the path is modified,
     * the existing map is invalidated and needs to be remapped.
     */
    void parse()
    {
        // Already been here?
        if (segmentCount > 0) return;

        segmentCount = 0;
        extraSegments.clear();

        if (path.isEmpty())
        {
            // There always has to be at least one segment.
            allocSegment(&emptyPath);

            DENG2_ASSERT(segmentCount > 0);
            return;
        }

        QChar const *segBegin = path.constData();
        QChar const *segEnd   = path.constData() + path.length() - 1;

        // Skip over any trailing delimiters.
        for (int i = path.length();
            segEnd->unicode() && *segEnd == separator && i-- > 0;
            --segEnd) {}

        // Scan the path for segments, in reverse order.
        QChar const *from;
        forever
        {
            if (segEnd < segBegin) break; // E.g., path is "/"

            // Find the start of the next segment.
            for (from = segEnd; from > segBegin && !(*from == separator); from--)
            {}

            int startIndex = (*from == separator? from + 1 : from) - path.constData();
            int length = (segEnd - path.constData()) - startIndex + 1;
            allocSegment(QStringRef(&path, startIndex, length));

            // Are there no more parent directories?
            if (from == segBegin) break;

            // So far so good. Move one directory level upwards.
            // The next name ends here.
            segEnd = from - 1;
        }

        // Unix style zero-length root name?
        if (*segBegin == separator)
        {
            allocSegment(&emptyPath);
        }

        DENG2_ASSERT(segmentCount > 0);
    }
Exemple #25
0
void FileInfo::splitIntoDirectoryAndFileName(const QString &filePath, QStringRef *dirPath, QStringRef *fileName)
{
    int idx = filePath.lastIndexOf(QLatin1Char('/'));
    if (idx < 0) {
        dirPath->clear();
        *fileName = QStringRef(&filePath);
        return;
    }
    *dirPath = filePath.leftRef(idx);
    *fileName = filePath.midRef(idx + 1);
}
void BoostBuildParser::setToolsetParser(QString const& toolsetName)
{
    if (!toolsetName.isEmpty() && toolsetName_.isEmpty())
    {
        if (QStringRef(&toolsetName, 0, 3) == QLatin1String("gcc"))
        {
            appendOutputParser(new ProjectExplorer::GccParser());
            toolsetName_ = toolsetName;
        }
        else if (QStringRef(&toolsetName, 0, 5) == QLatin1String("clang"))
        {
            // clang-xxx found (e.g. clang-linux)
            appendOutputParser(new ProjectExplorer::ClangParser());
            toolsetName_ = toolsetName;
        }
        else
        {
            // TODO: Add more toolsets (Intel, VC++, etc.)
        }
    }
}
Exemple #27
0
void WriteIncludes::writeHeaders(const OrderedSet &headers, bool global)
{
    const QChar openingQuote = global ? QLatin1Char('<') : QLatin1Char('"');
    const QChar closingQuote = global ? QLatin1Char('>') : QLatin1Char('"');

    // Check for the old headers 'qslider.h' and replace by 'QtGui/QSlider'
    for (const QString &header : headers) {
        const QString value = m_oldHeaderToNewHeader.value(header, header);
        const auto trimmed = QStringRef(&value).trimmed();
        if (!trimmed.isEmpty())
            m_output << "#include " << openingQuote << trimmed << closingQuote << QLatin1Char('\n');
    }
}
/**
 * Called if window is hidden when it recieves a message.
 * Displays the message in a ballon-popup in the tray.
 * Also sets tray icon to be red, to indicate an unread message.
 * @brief MainWindow::displayTrayMsg
 * @param index Tabindex
 * @param text "{sender_name}|{message}"
 */
void MainWindow::displayTrayMsg(int index, const QString& text)
{
    lastUpdatedTab = index;
    if(ui->actionBalloon_Notification->isChecked())
    {
        QStringList lst = text.split("|", QString::SkipEmptyParts);
        if(lst.count() > 1)
        {
            QStringRef txt(&lst.at(1), 0, lst.at(1).length());
            if(lst.at(1).length() > 20) txt = QStringRef(&lst.at(1), 0, 20);
            trayIcon->showMessage(lst.at(0) + " says:", txt.toString());
        }
    }
    trayIcon->setIcon(QIcon(APPLICATION_ICON_RED));
}
Exemple #29
0
QStringRef ChessEngine::nextToken(const QStringRef& previous, bool untilEnd)
{
	const QString* str = previous.string();
	if (str == 0)
		return QStringRef();

	int i;
	int start = -1;
	int firstPos = previous.position() + previous.size();

	for (i = firstPos; i < str->size(); i++)
	{
		if (str->at(i).isSpace())
		{
			if (start == -1)
				continue;
			break;
		}
		else if (start == -1)
		{
			start = i;
			if (untilEnd)
			{
				int end = str->size();
				while (str->at(--end).isSpace())
					;
				i = end + 1;
				break;
			}
		}
	}

	if (start == -1)
		return QStringRef();
	return QStringRef(str, start, i - start);
}
Exemple #30
0
void ThesaurusDatabaseType::load(QFile& file){
	REQUIRE(!buffer); //only call it once
	
	QTextStream stream(&file);
	QString line;
	QStringRef key;
	line = stream.readLine();
	stream.setCodec(qPrintable(line));
	buffer = new QString();
	buffer->reserve(file.size());
	do {
		int currentBufferLength = buffer->length();
		line = stream.readLine();
		int firstSplitter = line.indexOf('|');
        if (firstSplitter >= 0) {
            if (line.startsWith("-|") || line.startsWith("(") || line.startsWith("|")){
				buffer->append(line.mid(firstSplitter+1));
				thesaurus.insert(key, ThesaurusDatabaseType::TinyStringRef(currentBufferLength, buffer->length() - currentBufferLength));
				//using TinyStringRef instead of QString reduces the memory usage (with German thesaurus) by 4mb without any noticable performance decrease (it could even be faster, because the buffer fits better in the cache).

				//TODO: do something something that word type is included in key and still correct search is possible
			} else {
				buffer->append(line.left(firstSplitter));
				key = QStringRef(buffer, currentBufferLength, firstSplitter);
			}
		}
	} while (!line.isNull());
	buffer->squeeze();
	
	if (!userFileName.isEmpty()) {
		//simpler format: category|word|word|...
		QFile f(userFileName);
		if (f.open(QIODevice::ReadOnly)) {
			QTextStream s(&f);
			s.setCodec(QTextCodec::codecForMib(MIB_UTF8));
			do {
				line = s.readLine();
				if (line.startsWith("#") || line.startsWith("%")) continue; //comments
				QStringList splitted = line.split("|",QString::SkipEmptyParts);
				if (splitted.size() < 2) continue;
				userWords.insert(splitted[0].toLower(), splitted);
				for (int i=1;i<splitted.length();i++)
					userCategories.insert(splitted[i].toLower(), splitted[0]);
				
			} while (!line.isNull());
		} 
	}	
}