Example #1
0
QString XmlWriter::xmlString(const QString& s)
      {
      QString escaped;
      escaped.reserve(s.size());
      for (int i = 0; i < s.size(); ++i) {
            ushort c = s.at(i).unicode();
            escaped += xmlString(c);
            }
      return escaped;
      }
Example #2
0
QString QTextDocumentPrivate::plainText() const
{
    QString result;
    result.reserve(length());
    for (QTextDocumentPrivate::FragmentIterator it = begin(); it != end(); ++it) {
        const QTextFragmentData *f = *it;
        result += QString::fromRawData(text.unicode() + f->stringPosition, f->size);
    }
    // remove trailing block separator
    result.chop(1);
    return result;
}
Example #3
0
QString QSqlResultPrivate::namedToPositionalBinding(const QString &query)
{
    int n = query.size();

    QString result;
    result.reserve(n);
    QChar closingQuote;
    int count = 0;
    int i = 0;
    bool ignoreBraces = (sqldriver->d_func()->dbmsType == QSqlDriver::PostgreSQL);

    while (i < n) {
        QChar ch = query.at(i);
        if (!closingQuote.isNull()) {
            if (ch == closingQuote) {
                if (closingQuote == QLatin1Char(']')
                        && i + 1 < n && query.at(i + 1) == closingQuote) {
                    // consume the extra character. don't close.
                    ++i;
                    result += ch;
                } else {
                    closingQuote = QChar();
                }
            }
            result += ch;
            ++i;
        } else {
            if (ch == QLatin1Char(':')
                    && (i == 0 || query.at(i - 1) != QLatin1Char(':'))
                    && (i + 1 < n && qIsAlnum(query.at(i + 1)))) {
                int pos = i + 2;
                while (pos < n && qIsAlnum(query.at(pos)))
                    ++pos;
                QString holder(query.mid(i, pos - i));
                indexes[holder].append(count++);
                holders.append(QHolder(holder, i));
                result += QLatin1Char('?');
                i = pos;
            } else {
                if (ch == QLatin1Char('\'') || ch == QLatin1Char('"') || ch == QLatin1Char('`'))
                    closingQuote = ch;
                else if (!ignoreBraces && ch == QLatin1Char('['))
                    closingQuote = QLatin1Char(']');
                result += ch;
                ++i;
            }
        }
    }
    result.squeeze();
    values.resize(holders.size());
    return result;
}
Example #4
0
QString KexiDB::escapeBLOB(const QByteArray& array, BLOBEscapingType type)
{
    const int size = array.size();
    if (size == 0)
        return QString();
    int escaped_length = size * 2;
    if (type == BLOBEscape0xHex || type == BLOBEscapeOctal)
        escaped_length += 2/*0x or X'*/;
    else if (type == BLOBEscapeXHex)
        escaped_length += 3; //X' + '
    QString str;
    str.reserve(escaped_length);
    if (str.capacity() < escaped_length) {
        KexiDBWarn << "KexiDB::Driver::escapeBLOB(): no enough memory (cannot allocate " <<
        escaped_length << " chars)";
        return QString();
    }
    if (type == BLOBEscapeXHex)
        str = QString::fromLatin1("X'");
    else if (type == BLOBEscape0xHex)
        str = QString::fromLatin1("0x");
    else if (type == BLOBEscapeOctal)
        str = QString::fromLatin1("'");

    int new_length = str.length(); //after X' or 0x, etc.
    if (type == BLOBEscapeOctal) {
        // only escape nonprintable characters as in Table 8-7:
        // http://www.postgresql.org/docs/8.1/interactive/datatype-binary.html
        // i.e. escape for bytes: < 32, >= 127, 39 ('), 92(\).
        for (int i = 0; i < size; i++) {
            const unsigned char val = array[i];
            if (val < 32 || val >= 127 || val == 39 || val == 92) {
                str[new_length++] = '\\';
                str[new_length++] = '\\';
                str[new_length++] = '0' + val / 64;
                str[new_length++] = '0' + (val % 64) / 8;
                str[new_length++] = '0' + val % 8;
            } else {
                str[new_length++] = val;
            }
        }
    } else {
        for (int i = 0; i < size; i++) {
            const unsigned char val = array[i];
            str[new_length++] = (val / 16) < 10 ? ('0' + (val / 16)) : ('A' + (val / 16) - 10);
            str[new_length++] = (val % 16) < 10 ? ('0' + (val % 16)) : ('A' + (val % 16) - 10);
        }
    }
    if (type == BLOBEscapeXHex || type == BLOBEscapeOctal)
        str[new_length++] = '\'';
    return str;
}
Example #5
0
QString isa_65c816::decode_name_arg(const char arg, int &size)
{
	QString decode;
	decode.reserve(7);
	unsigned int operand = get_operand(0) | get_operand(1) | get_operand(2);
	switch(arg){
		case 'l':
			size += 3;
			return "$" + to_hex(operand & 0xFFFFFF, 6);
		case 'w':
			size += 2;
			return "$" + to_hex(operand & 0x00FFFF, 4);
		case 'b':
			size++;
			return "$" + to_hex(operand & 0x0000FF, 2);	
		case 'r':
			size++;
			return label_op(operand & 0x0000FF, 2, &ROM_buffer::branch_address);
		case 'R':
			size += 2;
			return label_op(operand & 0x00FFFF, 4, &ROM_buffer::branch_address);
		case 'j':
			size += 2;
			return label_op(operand & 0x00FFFF, 4, &ROM_buffer::jump_address);
		case 'J':
			size += 3;
			return label_op(operand & 0xFFFFFF, 6, &ROM_buffer::jump_address);
		case 'a':
			size += 1 + A_state;
			if(A_state){
				return "#$" + to_hex(operand & 0x00FFFF, 4);	
			}else{
				return "#$" + to_hex(operand & 0x0000FF, 2);	
			}
		case 'i':
			size += 1 + I_state;
			if(I_state){
				return "#$" + to_hex(operand & 0x00FFFF, 4);	
			}else{
				return "#$" + to_hex(operand & 0x0000FF, 2);	
			}
		case 'f':
			A_state = (operand & 0x20) ? data.at(delta-1) == (char)0xC2 : A_state;
			I_state = (operand & 0x10) ? data.at(delta-1) == (char)0xC2 : I_state;
		case 'c':
			size++;
			return "#$" + to_hex(operand & 0x0000FF, 2);	
		default:
			qFatal("Invalid name decode arg");
	}
	return "";
}
Example #6
0
QString Renderer::readTagName(const QString& content, int pos, int endPos)
{
	QString name;
	name.reserve(endPos - pos);
	while (content.at(pos).isSpace()) {
		++pos;
	}
	while (!content.at(pos).isSpace() && pos < endPos) {
		name += content.at(pos);
		++pos;
	}
	return name;
}
Example #7
0
QString IrcProtocol::ircFormatToPlainText(const QString &msg)
{
	QString result;
	result.reserve(msg.size());
	int pos = 0, oldPos = 0;
	while ((pos = formatRx.indexIn(msg, pos)) != -1) {
		result += msg.mid(oldPos, pos - oldPos);
		pos += formatRx.matchedLength();
		oldPos = pos;
	}
	result += msg.mid(oldPos);
	return result;
}
/*!
    \fn QString QVersionNumber::toString() const

    Returns a string with all of the segments delimited by a '.'.

    \sa majorVersion(), minorVersion(), microVersion(), segments()
*/
QString QVersionNumber::toString() const
{
    QString version;
    version.reserve(qMax(segmentCount() * 2 - 1, 0));
    bool first = true;
    for (int i = 0; i < segmentCount(); ++i) {
        if (!first)
            version += QLatin1Char('.');
        version += QString::number(segmentAt(i));
        first = false;
    }
    return version;
}
    QString FileSharingWidget::toLink() const
    {
        QString result;
        result.reserve(512);

        result = FsInfo_->GetUri();
        if (result.isEmpty())
        {
            result = FsInfo_->GetLocalPath();
        }

        return result;
    }
Example #10
0
void CoordXmlTest::writeHumanReadableStream_implementation(MapCoordVector& coords, QXmlStreamWriter& xml)
{
	QString data;
	data.reserve(coords.size() * 14);
	QTextStream stream(&data);
	for (const auto& coord : coords)
	{
		stream << coord.nativeX() << ' '
		       << coord.nativeY() << ' '
		       << coord.flags() << ';';
	}
	stream.flush();
	xml.writeCharacters(data);
}
Example #11
0
QString MigrateManager::possibleProblemsInfoMsg() const
{
    if (d_int->possibleProblems.isEmpty())
        return QString();
    QString str;
    str.reserve(1024);
    str = "<ul>";
    for (QStringList::ConstIterator it = d_int->possibleProblems.constBegin();
            it != d_int->possibleProblems.constEnd(); ++it) {
        str += (QString::fromLatin1("<li>") + *it + QString::fromLatin1("</li>"));
    }
    str += "</ul>";
    return str;
}
Example #12
0
QString RKRSharedFunctionality::quote (const QString &string) {
	QString ret;
	int s = string.size ();
	ret.reserve (s + 2);	// typical case: Only quotes added, no escapes needed.
	ret.append ('\"');
	for (int i = 0; i < s; ++i) {
		const QChar c = string[i];
		if ((c == '\\') || (c == '\"')) ret.append ('\\');
		ret.append (c);
	}
	ret.append ('\"');

	return ret;
}
Example #13
0
static inline QString createKey(const QString &filename, const QSize &size, QIcon::Mode mode, QIcon::State state, const QColor &col)
{
    QString key;
    key.reserve(filename.length() + 32);
    key += filename;
    key += QString::number(size.width());
    key += QLatin1Char('_');
    key += QString::number(size.height());
    key += QLatin1Char('_');
    key += QString::number(mode | (state << 8));
    key += QString::number(int(col.rgba()));

    return key;
}
bool Servatrice_DatabaseInterface::usernameIsValid(const QString &user)
{
	QString result;
	result.reserve(user.size());
	foreach (const QChar& c, user) {
		switch (c.category()) {
		// TODO: Figure out exactly which categories are OK and not
		case QChar::Other_Control: break;
		default: result += c;
		}
	}
	result = result.trimmed();
	return (result.size() > 0);
}
Example #15
0
QString EncoderUTF8::encode(const QString &input) const
{
    int len = input.length();
    int s = len * 9 / 8;
    QString output;
    output.reserve(s);
    bool inMathMode = false;

    /// Go through input char by char
    for (int i = 0; i < len; ++i) {
        /**
         * Repeatedly check if input data contains a verbatim command
         * like \url{...}, copy it to output, and update i to point
         * to the next character after the verbatim command.
         */
        while (testAndCopyVerbatimCommands(input, i, output));
        if (i >= len) break;

        const QChar c = input[i];

        /// Some characters have special meaning
        /// in TeX and have to be preceded with a backslash
        bool found = false;
        for (int k = 0; k < encoderLaTeXProtectedSymbolsLen; ++k)
            if (encoderLaTeXProtectedSymbols[k] == c) {
                output.append(QChar('\\'));
                found = true;
                break;
            }

        if (!found && !inMathMode)
            for (int k = 0; k < encoderLaTeXProtectedTextOnlySymbolsLen; ++k)
                if (encoderLaTeXProtectedTextOnlySymbols[k] == c) {
                    output.append(QChar('\\'));
                    break;
                }

        /// Dump character to output
        output.append(c);

        /// Finally, check if input character is a dollar sign
        /// without a preceding backslash, means toggling between
        /// text mode and math mode
        if (c == '$' && (i == 0 || input[i - 1] != QChar('\\')))
            inMathMode = !inMathMode;
    }

    return output;
}
void DesktopPreferencesDialog::onBrowseClicked() {
  QFileDialog dlg;
  dlg.setAcceptMode(QFileDialog::AcceptOpen);
  dlg.setFileMode(QFileDialog::ExistingFile);
  // compose a name fileter from QImageReader
  QString filter;
  filter.reserve(256);
  filter = tr("Image Files");
  filter += " (";
  QList<QByteArray> formats = QImageReader::supportedImageFormats();
  Q_FOREACH(QByteArray format, formats) {
    filter += "*.";
    filter += format.toLower();
    filter += ' ';
  }
 static inline void load(Archive & ar, QString & t, const unsigned int file_version)
 {
    Q_UNUSED(file_version);
    char cell, row;
    long lSize = 0;
    ar >> boost::serialization::make_nvp("size", lSize);
    t.clear();
    t.reserve(lSize);
    for (long l = 0; l < lSize; ++l)
    {
       ar >> boost::serialization::make_nvp(NULL, cell);
       ar >> boost::serialization::make_nvp(NULL, row);
       t.append(QChar(cell, row));
    }
 }
QString PdfPlug::UnicodeParsedString(GooString *s1)
{
	if ( !s1 || s1->getLength() == 0 )
		return QString();
	GBool isUnicode;
	int i;
	Unicode u;
	QString result;
	if ((s1->getChar(0) & 0xff) == 0xfe && (s1->getLength() > 1 && (s1->getChar(1) & 0xff) == 0xff))
	{
		isUnicode = gTrue;
		i = 2;
		result.reserve((s1->getLength() - 2) / 2);
	}
	else
	{
		isUnicode = gFalse;
		i = 0;
		result.reserve(s1->getLength());
	}
	while (i < s1->getLength())
	{
		if (isUnicode)
		{
			u = ((s1->getChar(i) & 0xff) << 8) | (s1->getChar(i+1) & 0xff);
			i += 2;
		}
		else
		{
			u = s1->getChar(i) & 0xff;
			++i;
		}
		result += QChar( u );
	}
	return result;
}
Example #19
0
void SciWrapper::integrateEdit(Edit * ed)
{
    QString msg;

    if(ed->GetType() & SC_MOD_INSERTTEXT)
    {
        int length = ed->GetLength();
        int line = ed->GetLine();
        int index = ed->GetIndex();
        char * val = ed->GetValue();

        QString str;
        str.reserve(length + 1);

        for(int i = 0; i < length; ++i)
        {
            m_doc->insertAt(line, index++, *(val+i));
            str.append(*(val+i));
        }

        m_okToInsert = false;
        m_sci->insertAt(str, ed->GetLine(), ed->GetIndex());
        m_okToInsert = true;

        msg = "Received edit: " + str + " (" + QString::number(ed->GetLine()) + "," +
            QString::number(ed->GetIndex()) + ")";
    }
    else if(ed->GetType() & SC_MOD_DELETETEXT)
    {
        msg = "Removing at (" + QString::number(ed->GetLine()) + "," +QString::number(ed->GetIndex()) + ")";
        m_doc->removeAt(ed->GetLine(), ed->GetIndex());

        //we need to check to see if the edit was before the current cursor position
        //if it is, then we need to adjust the new position.
        int line = 0, index = 0;
        m_okToInsert = false;
        m_sci->getCursorPosition(&line, &index);
        m_sci->setText(m_doc->Text());
        m_sci->setCursorPosition(line, index);
        m_okToInsert = true;
    }
    else
    {
        msg = "Received unrecognized edit";
    }

    emit statusMessage(msg);
}
Example #20
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());
		} 
	}	
}
Example #21
0
// Converts a QRegExp to a JS RegExp.
// The conversion is not 100% exact since ECMA regexp and QRegExp
// have different semantics/flags, but we try to do our best.
Heap::RegExpObject::RegExpObject(const QRegExp &re)
{
    global = false;

    // Convert the pattern to a ECMAScript pattern.
    QString pattern = QT_PREPEND_NAMESPACE(qt_regexp_toCanonical)(re.pattern(), re.patternSyntax());
    if (re.isMinimal()) {
        QString ecmaPattern;
        int len = pattern.length();
        ecmaPattern.reserve(len);
        int i = 0;
        const QChar *wc = pattern.unicode();
        bool inBracket = false;
        while (i < len) {
            QChar c = wc[i++];
            ecmaPattern += c;
            switch (c.unicode()) {
            case '?':
            case '+':
            case '*':
            case '}':
                if (!inBracket)
                    ecmaPattern += QLatin1Char('?');
                break;
            case '\\':
                if (i < len)
                    ecmaPattern += wc[i++];
                break;
            case '[':
                inBracket = true;
                break;
            case ']':
                inBracket = false;
                break;
            default:
                break;
            }
        }
        pattern = ecmaPattern;
    }

    Scope scope(internalClass->engine);
    Scoped<QV4::RegExpObject> o(scope, this);

    o->d()->value = QV4::RegExp::create(scope.engine, pattern, re.caseSensitivity() == Qt::CaseInsensitive, false);

    o->initProperties();
}
QString ColoringMessageHandler::colorifyDescription(const QString &in) const
{
    QXmlStreamReader reader(in);
    QString result;
    result.reserve(in.size());
    ColorType currentColor = RunningText;

    while(!reader.atEnd())
    {
        reader.readNext();

        switch(reader.tokenType())
        {
            case QXmlStreamReader::StartElement:
            {
                if(reader.name() == QLatin1String("span"))
                {
                    Q_ASSERT(m_classToColor.contains(reader.attributes().value(QLatin1String("class")).toString()));
                    currentColor = m_classToColor.value(reader.attributes().value(QLatin1String("class")).toString());
                }

                continue;
            }
            case QXmlStreamReader::Characters:
            {
                result.append(colorify(reader.text().toString(), currentColor));
                continue;
            }
            case QXmlStreamReader::EndElement:
            {
                currentColor = RunningText;
                continue;
            }
            /* Fallthrough, */
            case QXmlStreamReader::StartDocument:
            /* Fallthrough, */
            case QXmlStreamReader::EndDocument:
                continue;
            default:
                Q_ASSERT_X(false, Q_FUNC_INFO,
                           "Unexpected node.");
        }
    }

    Q_ASSERT_X(!reader.hasError(), Q_FUNC_INFO,
               "The output from Patternist must be well-formed.");
    return result;
}
Example #23
0
/*!
    Returns the reconstructed query string, formed from the key-value pairs
    currently stored in this QUrlQuery object and separated by the query
    delimiters chosen for this object. The keys and values are encoded using
    the options given by the \a encoding parameter.

    For this function, the only ambiguous delimiter is the hash ("#"), as in
    URLs it is used to separate the query string from the fragment that may
    follow.

    The order of the key-value pairs in the returned string is exactly the same
    as in the original query.

    \sa setQuery(), QUrl::setQuery(), QUrl::fragment(), {encoding}{Encoding}
*/
QString QUrlQuery::query(QUrl::ComponentFormattingOptions encoding) const
{
    if (!d)
        return QString();

    // unlike the component encoding, for the whole query we need to modify a little:
    //  - the "#" character is ambiguous, so we decode it only in DecodeAllDelimiters mode
    //  - the query delimiter pair must always be encoded
    //  - the non-delimiters vary on DecodeUnambiguousDelimiters
    // so:
    //  - full encoding: encode the non-delimiters, the pair, "#", "[" and "]"
    //  - pretty decode: decode the non-delimiters, "[" and "]"; encode the pair and "#"
    //  - decode all: decode the non-delimiters, "[", "]", "#"; encode the pair

    // start with what's always encoded
    ushort tableActions[] = {
        leave('+'),                          // 0
        encode(d->pairDelimiter.unicode()),  // 1
        encode(d->valueDelimiter.unicode()), // 2
        decode('#'),                         // 3
        0
    };
    if (encoding & QUrl::EncodeDelimiters) {
        tableActions[3] = encode('#');
    }

    QString result;
    Map::const_iterator it = d->itemList.constBegin();
    Map::const_iterator end = d->itemList.constEnd();

    {
        int size = 0;
        for ( ; it != end; ++it)
            size += it->first.length() + 1 + it->second.length() + 1;
        result.reserve(size + size / 4);
    }

    for (it = d->itemList.constBegin(); it != end; ++it) {
        if (!result.isEmpty())
            result += QChar(d->pairDelimiter);
        recodeAndAppend(result, it->first, encoding, tableActions);
        if (!it->second.isNull()) {
            result += QChar(d->valueDelimiter);
            recodeAndAppend(result, it->second, encoding, tableActions);
        }
    }
    return result;
}
Example #24
0
QString database::qqencode_string(const QString& str)
{
    QString res;
    res.reserve(str.length());

    static const QString c_hex("#%1");
    static const QChar c_zero('0');
    foreach (const QChar& ch, str)
    {
        if (ch.isLetterOrNumber())
            res += ch;
        else
            res += c_hex.arg(ch.unicode(), 4, 16, c_zero);
    }
    return res;
}
Example #25
0
void mainWindow::aboutWindow()
{
    QString out;
    out.reserve(200);
    out = tr("The Moth Hamster Wheel is Brought to you by:\n");
    out += tr("Coding: Daniel Fialkovsky,\nResearch: Thomson Paris\n\n");
    out += tr("Icons by David Vignoni ([email protected])\n\n");
    out += tr("Special THANKS to:\n");
    out += tr("The Citrus Research and Development Foundation,\n");
    out += tr("USDA ARS CMAVE,\n");
    out += tr("University of Florida,\n");
    out += tr("For supporting this project");

    QMessageBox::about(nullptr, tr("Credits"), 
		       out);
}
Example #26
0
void Widget::reserveFunction()
{
    //! [44]
    QString result;
    int maxSize;
    bool condition;
    QChar nextChar;

    result.reserve(maxSize);

    while (condition)
        result.append(nextChar);

    result.squeeze();
    //! [44]
}
Example #27
0
ZVariant operator *(const QString &var1, const ZVariant &var2)
{
    if(var2.type() == ZVariant::Int) {
        QString array;
        int count = var2.toInt();

        array.reserve(var1.size() * count);

        while(count-- > 0)
            array.append(var1);

        return array;
    }

    return ZVariant::Undefined;
}
Example #28
0
static QString escapeCharacters(QString str) {
    QString res;
    str = str.replace('\\', QString("\\\\")).replace('"', "\\\"").replace('\'', "\\\'").replace('\n', "\\n");
    res.reserve(str.size() * 2);
    for (QString::const_iterator it = str.begin(); it != str.end(); ++it) {
        QChar ch = *it;
        ushort code = ch.unicode();
        if (code < 0x80 && code >= 0x20) {
            res += ch;
        } else {
            res += "\\u";
            res += QString::number(code, 16).rightJustified(4, '0').toUpper();
        }
    }
    return res;
}
Example #29
0
	QString ChatEventInfo::formatMchatMembersList(const bool activeVoice) const
	{
		assert(!MyAimid_.isEmpty());

		QString result;
		result.reserve(512);

		const auto &friendlyMembers = Mchat_.MembersFriendly_;

		if (friendlyMembers.isEmpty())
		{
			return result;
		}

		const auto you =
            activeVoice ?
                QT_TRANSLATE_NOOP3("chat_event", "You", "active_voice") :
                QT_TRANSLATE_NOOP3("chat_event", "you", "passive_voice");

		const auto format =
			[this, you](const QString &name) -> const QString&
			{
				return (isMyAimid(name) ? you : name);
			};


		const auto &first = friendlyMembers.first();

		result += format(first);

		if (friendlyMembers.size() == 1)
		{
			return result;
		}

		const auto middle = friendlyMembers.mid(1, friendlyMembers.size() - 2);
		for (const auto &member : middle)
		{
			result += ", ";
			result += format(member);
		}

		result += QT_TRANSLATE_NOOP("chat_event", " and ");
		result += format(friendlyMembers.last());

		return result;
	}
Example #30
0
Item TranslateFN::evaluateSingleton(const DynamicContext::Ptr &context) const
{
    const Item item(m_operands.first()->evaluateSingleton(context));

    if(!item)
        return CommonValues::EmptyString;

    const QString mapString(m_operands.at(1)->evaluateSingleton(context).stringValue());
    const QString arg(item.stringValue());

    if(mapString.isEmpty())
        return AtomicString::fromValue(arg);

    const QString transString(m_operands.at(2)->evaluateSingleton(context).stringValue());
    const int transLen = transString.length();
    const int argLen = arg.length();

    QString result;
    result.reserve(argLen);
    int outI = 0;

    for(int i = 0; i < argLen; ++i)
    {
        const QChar argCh(arg.at(i));
        const int mapPos = mapString.indexOf(argCh);

        if(mapPos == -1)
        {
            result[outI] = argCh;
            ++outI;
            continue;
        }
        else if(mapPos >= transLen)
            continue;

        const QChar transCh(transString.at(mapPos));

        if(transCh.isNull())
            continue;

        result[outI] = transCh;
        ++outI;
    }

    result.truncate(outI);
    return AtomicString::fromValue(result);
}