Example #1
0
void dspIndentedBOM::sFillList()
{
  _bomitem->clear();
  
  if (_item->isValid())
  {
	q.prepare("SELECT * FROM indentedBOM(:item_id, :revision_id, :expired, :effective) "
		      "WHERE (bomdata_item_id > 0);");
    q.bindValue(":item_id", _item->id());
    q.bindValue(":revision_id", _revision->id());
    if (!_showExpired->isChecked())
	  q.bindValue(":expired", 0);
	else
      q.bindValue(":expired", _expiredDays->value());
    if (!_showFuture->isChecked())
      q.bindValue(":effective", 0);
	else
      q.bindValue(":effective", _effectiveDays->value());
    q.exec();

    QStack<XTreeWidgetItem*> parent;
    XTreeWidgetItem *last = 0;
    int level = 1;
    while(q.next())
    {
      // If the level this item is on is lower than the last level we just did then we need
      // to pop the stack a number of times till we are equal.
      while(q.value("bomdata_bomwork_level").toInt() < level)
      {
        level--;
        last = parent.pop();
      }

      // If the level this item is on is higher than the last level we need to push the last
      // item onto the stack a number of times till we are equal. (Should only ever be 1.)
      while(q.value("bomdata_bomwork_level").toInt() > level)
      {
        level++;
        parent.push(last);
        last = 0;
      }

      // If there is an item in the stack use that as the parameter to the new xlistviewitem
      // otherwise we'll just use the xlistview _layout
      if(!parent.isEmpty() && parent.top())
        last = new XTreeWidgetItem(parent.top(), last, q.value("bomdata_bomwork_id").toInt(),
                                    q.value("bomdata_bomwork_seqnumber"), q.value("bomdata_item_number"),
                                    q.value("bomdata_itemdescription"), q.value("bomdata_uom_name"),
                                    q.value("bomdata_qtyper"), q.value("bomdata_scrap"),
                                    q.value("bomdata_effective"), q.value("bomdata_expires") );
      else
        last = new XTreeWidgetItem(_bomitem, last, q.value("bomdata_bomwork_id").toInt(),
                                    q.value("bomdata_bomwork_seqnumber"), q.value("bomdata_item_number"),
                                    q.value("bomdata_itemdescription"), q.value("bomdata_uom_name"),
                                    q.value("bomdata_qtyper"), q.value("bomdata_scrap"),
                                    q.value("bomdata_effective"), q.value("bomdata_expires") );
	          
	  if (q.value("bomdata_expired").toBool())
        last->setTextColor("red");
      else if (q.value("bomdata_future").toBool())
        last->setTextColor("blue");
    }
    _bomitem->expandAll();
  }
}
bool QQuickStyledTextPrivate::parseTag(const QChar *&ch, const QString &textIn, QString &textOut, QTextCharFormat &format)
{
    skipSpace(ch);

    int tagStart = ch - textIn.constData();
    int tagLength = 0;
    while (!ch->isNull()) {
        if (*ch == greaterThan) {
            if (tagLength == 0)
                return false;
            QStringRef tag(&textIn, tagStart, tagLength);
            const QChar char0 = tag.at(0);
            if (char0 == QLatin1Char('b')) {
                if (tagLength == 1) {
                    format.setFontWeight(QFont::Bold);
                    return true;
                } else if (tagLength == 2 && tag.at(1) == QLatin1Char('r')) {
                    textOut.append(QChar(QChar::LineSeparator));
                    hasSpace = true;
                    prependSpace = false;
                    return false;
                }
            } else if (char0 == QLatin1Char('i')) {
                if (tagLength == 1) {
                    format.setFontItalic(true);
                    return true;
                }
            } else if (char0 == QLatin1Char('p')) {
                if (tagLength == 1) {
                    if (!hasNewLine)
                        textOut.append(QChar::LineSeparator);
                    hasSpace = true;
                    prependSpace = false;
                } else if (tag == QLatin1String("pre")) {
                    preFormat = true;
                    if (!hasNewLine)
                        textOut.append(QChar::LineSeparator);
                    format.setFontFamily(QString::fromLatin1("Courier New,courier"));
                    format.setFontFixedPitch(true);
                    return true;
                }
            } else if (char0 == QLatin1Char('u')) {
                if (tagLength == 1) {
                    format.setFontUnderline(true);
                    return true;
                } else if (tag == QLatin1String("ul")) {
                    List listItem;
                    listItem.level = 0;
                    listItem.type = Unordered;
                    listItem.format = Bullet;
                    listStack.push(listItem);
                }
            } else if (char0 == QLatin1Char('h') && tagLength == 2) {
                int level = tag.at(1).digitValue();
                if (level >= 1 && level <= 6) {
                    if (!hasNewLine)
                        textOut.append(QChar::LineSeparator);
                    hasSpace = true;
                    prependSpace = false;
                    setFontSize(7 - level, format);
                    format.setFontWeight(QFont::Bold);
                    return true;
                }
            } else if (tag == QLatin1String("strong")) {
                format.setFontWeight(QFont::Bold);
                return true;
            } else if (tag == QLatin1String("ol")) {
                List listItem;
                listItem.level = 0;
                listItem.type = Ordered;
                listItem.format = Decimal;
                listStack.push(listItem);
            } else if (tag == QLatin1String("li")) {
                if (!hasNewLine)
                    textOut.append(QChar(QChar::LineSeparator));
                if (!listStack.isEmpty()) {
                    int count = ++listStack.top().level;
                    for (int i = 0; i < listStack.size(); ++i)
                        textOut += QString(tabsize, QChar::Nbsp);
                    switch (listStack.top().format) {
                    case Decimal:
                        textOut += QString::number(count) % QLatin1Char('.');
                        break;
                    case LowerAlpha:
                        textOut += toAlpha(count, false) % QLatin1Char('.');
                        break;
                    case UpperAlpha:
                        textOut += toAlpha(count, true) % QLatin1Char('.');
                        break;
                    case LowerRoman:
                        textOut += toRoman(count, false) % QLatin1Char('.');
                        break;
                    case UpperRoman:
                        textOut += toRoman(count, true) % QLatin1Char('.');
                        break;
                    case Bullet:
                        textOut += bullet;
                        break;
                    case Disc:
                        textOut += disc;
                        break;
                    case Square:
                        textOut += square;
                        break;
                    }
                    textOut += QString(2, QChar::Nbsp);
                }
            }
            return false;
        } else if (ch->isSpace()) {
            // may have params.
            QStringRef tag(&textIn, tagStart, tagLength);
            if (tag == QLatin1String("font"))
                return parseFontAttributes(ch, textIn, format);
            if (tag == QLatin1String("ol")) {
                parseOrderedListAttributes(ch, textIn);
                return false; // doesn't modify format
            }
            if (tag == QLatin1String("ul")) {
                parseUnorderedListAttributes(ch, textIn);
                return false; // doesn't modify format
            }
            if (tag == QLatin1String("a")) {
                return parseAnchorAttributes(ch, textIn, format);
            }
            if (tag == QLatin1String("img")) {
                parseImageAttributes(ch, textIn, textOut);
                return false;
            }
            if (*ch == greaterThan || ch->isNull())
                continue;
        } else if (*ch != slash) {
            tagLength++;
        }
        ++ch;
    }
    return false;
}
Example #3
0
QVector<ApiTraceCall*>
TraceLoader::fetchFrameContents(ApiTraceFrame *currentFrame)
{
    Q_ASSERT(currentFrame);

    if (currentFrame->isLoaded()) {
        return currentFrame->calls();
    }

    if (m_parser.supportsOffsets()) {
        unsigned frameIdx = currentFrame->number;
        int numOfCalls = numberOfCallsInFrame(frameIdx);

        if (numOfCalls) {
            quint64 binaryDataSize = 0;
            QStack<ApiTraceCall*> groups;
            QVector<ApiTraceCall*> topLevelItems;
            QVector<ApiTraceCall*> allCalls(numOfCalls);
            const FrameBookmark &frameBookmark = m_frameBookmarks[frameIdx];

            m_parser.setBookmark(frameBookmark.start);

            trace::Call *call;
            int parsedCalls = 0;
            while ((call = m_parser.parse_call())) {
                ApiTraceCall *apiCall =
                    apiCallFromTraceCall(call, m_helpHash,
                                         currentFrame, groups.isEmpty() ? 0 : groups.top(), this);
                Q_ASSERT(apiCall);
                Q_ASSERT(parsedCalls < allCalls.size());
                allCalls[parsedCalls++] = apiCall;
                if (groups.count() == 0) {
                    topLevelItems.append(apiCall);
                } else {
                    groups.top()->addChild(apiCall);
                }
                if (call->flags & trace::CALL_FLAG_MARKER_PUSH) {
                    groups.push(apiCall);
                } else if (call->flags & trace::CALL_FLAG_MARKER_POP) {
                    if (groups.count()) {
                        groups.top()->finishedAddingChildren();
                        groups.pop();
                    }
                }
                if (apiCall->hasBinaryData()) {
                    QByteArray data =
                        apiCall->arguments()[
                            apiCall->binaryDataIndex()].toByteArray();
                    binaryDataSize += data.size();
                }

                delete call;

                if (apiCall->flags() & trace::CALL_FLAG_END_FRAME) {
                    break;
                }

            }
            // There can be fewer parsed calls when call in different
            // threads cross the frame boundary
            Q_ASSERT(parsedCalls <= numOfCalls);
            Q_ASSERT(parsedCalls <= allCalls.size());
            allCalls.resize(parsedCalls);
            allCalls.squeeze();

            Q_ASSERT(parsedCalls <= currentFrame->numChildrenToLoad());
            if (topLevelItems.count() == allCalls.count()) {
                emit frameContentsLoaded(currentFrame, allCalls,
                                         allCalls, binaryDataSize);
            } else {
                emit frameContentsLoaded(currentFrame, topLevelItems,
                                         allCalls, binaryDataSize);
            }
            return allCalls;
        }
    }
    return QVector<ApiTraceCall*>();
}
Example #4
0
void fractin::on_equal_clicked()
{
    QStack<QChar> t;
    int d=0;
    QString str=text;
    QChar ch=text[0];
    text.remove(0,1);
    if((!ch.isDigit()&&ch!='(')||text.isEmpty()){
        text="格式不支持!";
        ui->show->setText(text);
        return;
    }
    while(!text.isEmpty()){
        if(ch.isDigit()){
            while(ch.isDigit()&&!text.isEmpty()){
              ch=text[0];
              text.remove(0,1);
            }
            if(ch!='|'||text.isEmpty()){
              text="格式不支持!";
              ui->show->setText(text);
              return;
            }
            ch=text[0];
            text.remove(0,1);
            if(!ch.isDigit()){
                text="格式不支持!";
                ui->show->setText(text);
                return;
            }
            while(ch.isDigit()&&!text.isEmpty()){
                d=d*10+ch.unicode()-48;
                ch=text[0];
                text.remove(0,1);
            }
            if(ch.isDigit())
                d=d*10+ch.unicode()-48;
            if(d==0){
                text="分母不能为零!";
                ui->show->setText(text);
                return;
            }
            if(ch=='.'||ch=='('||ch=='|'){
                text="格式不支持!";
                ui->show->setText(text);
                return;
            }
            continue;
        }
        if(ch=='+'||ch=='-'||ch=='*'||ch=='/'){
           if(text.isEmpty()){
               text="格式不支持!";
               ui->show->setText(text);
               return;
           }
           ch=text[0];
           text.remove(0,1);
           if(!(ch.isDigit()||ch=='(')||(ch.isDigit()&&text.isEmpty())){
               text="格式不支持!";
               ui->show->setText(text);
               return;
           }
           continue;
        }
        if(ch=='('){
            t.push(ch);
            if(text.isEmpty()){
                text="格式不支持!";
                ui->show->setText(text);
                return;
            }
            ch=text[0];
            text.remove(0,1);
            if(!ch.isDigit()&&ch!='('&&ch!='-'){
                text="格式不支持!";
                ui->show->setText(text);
                return;
            }
            if(ch=='-'){
                if(text.isEmpty()){
                    text="格式不支持!";
                    ui->show->setText(text);
                    return;
                }
                ch=text[0];
                text.remove(0,1);
                if(!ch.isDigit()){
                    text="格式不支持!";
                    ui->show->setText(text);
                    return;
                }
                while(ch.isDigit()&&!text.isEmpty()){
                    ch=text[0];
                    text.remove(0,1);
                }
                if(text.isEmpty()||ch!='|'){
                    text="格式不支持!";
                    ui->show->setText(text);
                    return;
                }

                ch=text[0];
                text.remove(0,1);
                while(ch.isDigit()&&!text.isEmpty()){
                    ch=text[0];
                    text.remove(0,1);
                }
                if(text.isEmpty()&&ch.isDigit()){
                    text="格式不支持!";
                    ui->show->setText(text);
                    return;
                }
                if(ch!=')'){
                    text="格式不支持!";
                    ui->show->setText(text);
                    return;
                }
                t.pop();
                if(!text.isEmpty()){
                ch=text[0];
                text.remove(0,1);
                if(ch.isDigit()||ch=='.'||ch=='('||ch=='|'){
                    text="格式不支持!";
                    ui->show->setText(text);
                    return;
                }
                }
                else
                    ch='0';
            }
            continue;
        }
        if(ch==')'){
            if(t.isEmpty()){
                text="格式不支持!";
                ui->show->setText(text);
                return;
            }
            else{
                t.pop();
                if(!text.isEmpty()){
                    ch=text[0];
                    text.remove(0,1);
                    if(ch!='+'&&ch!='-'&&ch!='*'&&ch!='/'&&ch!=')'){
                        text="格式不支持!";
                        ui->show->setText(text);
                        return;
                    }
                }

                continue;
            }
        }
        text="格式不支持!";
        ui->show->setText(text);
        return;
    }
    if(ch!=')'&&!ch.isDigit()){
        text="格式不支持!";
        ui->show->setText(text);
        return;
    }
    if(ch==')'){
        if(t.isEmpty()){
            text="格式不支持!";
            ui->show->setText(text);
            return;
        }
        else
           t.pop();
    }
    if(!t.isEmpty()){
        text="格式不支持!";
        ui->show->setText(text);
        return;
    }
   text=str;
   Fraction_expression f;
   text=f.input(text);
   ui->show->setText(text);


}
bool QMimeTypeParserBase::parse(QIODevice *dev, const QString &fileName, QString *errorMessage)
{
#ifdef QT_NO_XMLSTREAMREADER
    if (errorMessage)
        *errorMessage = QString::fromLatin1("QXmlStreamReader is not available, cannot parse.");
    return false;
#else
    QMimeTypePrivate data;
    int priority = 50;
    QStack<QMimeMagicRule *> currentRules; // stack for the nesting of rules
    QList<QMimeMagicRule> rules; // toplevel rules
    QXmlStreamReader reader(dev);
    ParseState ps = ParseBeginning;
    QXmlStreamAttributes atts;
    while (!reader.atEnd()) {
        switch (reader.readNext()) {
        case QXmlStreamReader::StartElement:
            ps = nextState(ps, reader.name());
            atts = reader.attributes();
            switch (ps) {
            case ParseMimeType: { // start parsing a MIME type name
                const QString name = atts.value(QLatin1String(mimeTypeAttributeC)).toString();
                if (name.isEmpty()) {
                    reader.raiseError(QString::fromLatin1("Missing '%1'-attribute").arg(QString::fromLatin1(mimeTypeAttributeC)));
                } else {
                    data.name = name;
                }
            }
                break;
            case ParseGenericIcon:
                data.genericIconName = atts.value(QLatin1String(nameAttributeC)).toString();
                break;
            case ParseIcon:
                data.iconName = atts.value(QLatin1String(nameAttributeC)).toString();
                break;
            case ParseGlobPattern: {
                const QString pattern = atts.value(QLatin1String(patternAttributeC)).toString();
                unsigned weight = atts.value(QLatin1String(weightAttributeC)).toString().toInt();
                const bool caseSensitive = atts.value(QLatin1String(caseSensitiveAttributeC)).toString() == QLatin1String("true");

                if (weight == 0)
                    weight = QMimeGlobPattern::DefaultWeight;

                Q_ASSERT(!data.name.isEmpty());
                const QMimeGlobPattern glob(pattern, data.name, weight, caseSensitive ? Qt::CaseSensitive : Qt::CaseInsensitive);
                if (!process(glob, errorMessage))   // for actual glob matching
                    return false;
                data.addGlobPattern(pattern); // just for QMimeType::globPatterns()
            }
                break;
            case ParseSubClass: {
                const QString inheritsFrom = atts.value(QLatin1String(mimeTypeAttributeC)).toString();
                if (!inheritsFrom.isEmpty())
                    processParent(data.name, inheritsFrom);
            }
                break;
            case ParseComment: {
                // comments have locale attributes. We want the default, English one
                QString locale = atts.value(QLatin1String(localeAttributeC)).toString();
                const QString comment = reader.readElementText();
                if (locale.isEmpty())
                    locale = QString::fromLatin1("en_US");
                data.localeComments.insert(locale, comment);
            }
                break;
            case ParseAlias: {
                const QString alias = atts.value(QLatin1String(mimeTypeAttributeC)).toString();
                if (!alias.isEmpty())
                    processAlias(alias, data.name);
            }
                break;
            case ParseMagic: {
                priority = 50;
                const QString priorityS = atts.value(QLatin1String(priorityAttributeC)).toString();
                if (!priorityS.isEmpty()) {
                    if (!parseNumber(priorityS, &priority, errorMessage))
                        return false;

                }
                currentRules.clear();
                //qDebug() << "MAGIC start for mimetype" << data.name;
            }
                break;
            case ParseMagicMatchRule: {
                QMimeMagicRule *rule = 0;
                if (!createMagicMatchRule(atts, errorMessage, rule))
                    return false;
                QList<QMimeMagicRule> *ruleList;
                if (currentRules.isEmpty())
                    ruleList = &rules;
                else // nest this rule into the proper parent
                    ruleList = &currentRules.top()->m_subMatches;
                ruleList->append(*rule);
                //qDebug() << " MATCH added. Stack size was" << currentRules.size();
                currentRules.push(&ruleList->last());
                delete rule;
                break;
            }
            case ParseError:
                reader.raiseError(QString::fromLatin1("Unexpected element <%1>").
                                  arg(reader.name().toString()));
                break;
            default:
                break;
            }
            break;
        // continue switch QXmlStreamReader::Token...
        case QXmlStreamReader::EndElement: // Finished element
        {
            const QStringRef elementName = reader.name();
            if (elementName == QLatin1String(mimeTypeTagC)) {
                if (!process(QMimeType(data), errorMessage))
                    return false;
                data.clear();
            } else if (elementName == QLatin1String(matchTagC)) {
                // Closing a <match> tag, pop stack
                currentRules.pop();
                //qDebug() << " MATCH closed. Stack size is now" << currentRules.size();
            } else if (elementName == QLatin1String(magicTagC)) {
                //qDebug() << "MAGIC ended, we got" << rules.count() << "rules, with prio" << priority;
                // Finished a <magic> sequence
                QMimeMagicRuleMatcher ruleMatcher(data.name, priority);
                ruleMatcher.addRules(rules);
                processMagicMatcher(ruleMatcher);
                rules.clear();
            }
            break;
        }
        default:
            break;
        }
    }

    if (reader.hasError()) {
        if (errorMessage)
            *errorMessage = QString::fromLatin1("An error has been encountered at line %1 of %2: %3:").arg(reader.lineNumber()).arg(fileName, reader.errorString());
        return false;
    }

    return true;
#endif //QT_NO_XMLSTREAMREADER
}
Example #6
0
QString Speech::prepareCommand(QString command, const QString &text,
                               const QString &filename, const QString &language)
{
#ifdef macroExpander
    QHash<QChar, QString> map;
    map[QLatin1Char('t')] = text;
    map[QLatin1Char('f')] = filename;
    map[QLatin1Char('l')] = language;
    return KMacroExpander::expandMacrosShellQuote(command, map);
#else
    QStack<bool> stack;  // saved isdoublequote values during parsing of braces
    bool issinglequote = false; // inside '...' ?
    bool isdoublequote = false; // inside "..." ?
    int noreplace = 0; // nested braces when within ${...}
    QString escText = K3ShellProcess::quote(text);

    // character sequences that change the state or need to be otherwise processed
    QRegExp re_singlequote("('|%%|%t|%f|%l)");
    QRegExp re_doublequote("(\"|\\\\|`|\\$\\(|\\$\\{|%%|%t|%f|%l)");
    QRegExp re_noquote("('|\"|\\\\|`|\\$\\(|\\$\\{|\\(|\\{|\\)|\\}|%%|%t|%f|%l)");

    // parse the command:
    for (int i = re_noquote.search(command);
         i != -1;
         i = (issinglequote ? re_singlequote.search(command, i)
              : isdoublequote ? re_doublequote.search(command, i)
              : re_noquote.search(command, i))
        )
        // while there are character sequences that need to be processed
    {
        if ((command[i] == '(') || (command[i] == '{')) { // (...) or {...}
            // assert(isdoublequote == false)
            stack.push(isdoublequote);
            if (noreplace > 0)
                // count nested braces when within ${...}
                noreplace++;
            i++;
        } else if (command[i] == '$') { // $(...) or ${...}
            stack.push(isdoublequote);
            isdoublequote = false;
            if ((noreplace > 0) || (command[i + 1] == '{'))
                // count nested braces when within ${...}
                noreplace++;
            i += 2;
        } else if ((command[i] == ')') || (command[i] == '}')) {
            // $(...) or (...) or ${...} or {...}
            if (!stack.isEmpty())
                isdoublequote = stack.pop();
            else
                qWarning("Parse error.");
            if (noreplace > 0)
                // count nested braces when within ${...}
                noreplace--;
            i++;
        } else if (command[i] == '\'') {
            issinglequote = !issinglequote;
            i++;
        } else if (command[i] == '"') {
            isdoublequote = !isdoublequote;
            i++;
        } else if (command[i] == '\\')
            i += 2;
        else if (command[i] == '`') {
            // Replace all `...` with safer $(...)
            command.replace(i, 1, "$(");
            QRegExp re_backticks("(`|\\\\`|\\\\\\\\|\\\\\\$)");
            for (int i2 = re_backticks.search(command, i + 2);
                 i2 != -1;
                 i2 = re_backticks.search(command, i2)
                ) {
                if (command[i2] == '`') {
                    command.replace(i2, 1, ")");
                    i2 = command.length(); // leave loop
                } else {
                    // remove backslash and ignore following character
                    command.remove(i2, 1);
                    i2++;
                }
            }
            // Leave i unchanged! We need to process "$("
        } else if (noreplace > 0) { // do not replace macros within ${...}
            if (issinglequote)
                i += re_singlequote.matchedLength();
            else if (isdoublequote)
                i += re_doublequote.matchedLength();
            else
                i += re_noquote.matchedLength();
        } else { // replace macro
            QString match, v;

            // get match
            if (issinglequote)
                match = re_singlequote.cap();
            else if (isdoublequote)
                match = re_doublequote.cap();
            else
                match = re_noquote.cap();

            // substitute %variables
            if (match == "%t")
                v = escText;
            else if (match == "%f")
                v = filename;
            else if (match == "%%")
                v = "%";
            else if (match == "%l")
                v = language;

            // %variable inside of a quote?
            if (isdoublequote)
                v = '"' + v + '"';
            else if (issinglequote)
                v = '\'' + v + '\'';

            command.replace(i, match.length(), v);
            i += v.length();
        }
    }
    return command;
#endif
}
Example #7
0
/*!
    \internal
*/
void QDirIteratorPrivate::advance()
{
    // Store the current entry
    if (!fileEngineIterators.isEmpty())
        currentFilePath = fileEngineIterators.top()->currentFilePath();

    // Advance to the next entry
    if (followNextDir) {
        // Start by navigating into the current directory.
        followNextDir = false;

        QAbstractFileEngineIterator *it = fileEngineIterators.top();

        QString subDir = it->currentFilePath();
#ifdef Q_OS_WIN
        if (fileInfo.isSymLink())
            subDir = fileInfo.canonicalFilePath();
#endif
        pushSubDirectory(subDir, it->nameFilters(), it->filters());
    }

    if (fileEngineIterators.isEmpty())
        done = true;

    bool foundValidEntry = false;
    while (!fileEngineIterators.isEmpty()) {
        QAbstractFileEngineIterator *it = fileEngineIterators.top();

        // Find the next valid iterator that matches the filters.
        foundValidEntry = false;
        while (it->hasNext()) {
            it->next();
            if (matchesFilters(it)) {
                foundValidEntry = true;
                break;
            }
        }

        if (!foundValidEntry) {
            // If this iterator is done, pop and delete it, and continue
            // iteration on the parent. Otherwise break, we're done.
            if (!fileEngineIterators.isEmpty()) {
                delete it;
                it = fileEngineIterators.pop();
                continue;
            }
            break;
        }

        fileInfo = it->currentFileInfo();

        // If we're doing flat iteration, we're done.
        if (!(iteratorFlags & QDirIterator::Subdirectories))
            break;

        // Subdirectory iteration.
        QString filePath = fileInfo.filePath();

        // Never follow . and ..
        if (fileInfo.fileName() == QLatin1String(".") || fileInfo.fileName() == QLatin1String(".."))
            break;

        // Never follow non-directory entries
        if (!fileInfo.isDir())
            break;
      
        // Check symlinks
        if (fileInfo.isSymLink() && !(iteratorFlags & QDirIterator::FollowSymlinks)) {
            // Follow symlinks only if FollowSymlinks was passed
            break;
        }

        // Stop link loops
        if (visitedLinks.contains(fileInfo.canonicalFilePath()))
            break;

        // Signal that we want to follow this entry.
        followNextDir = true;
        break;
    }

    if (!foundValidEntry)
        done = true;
}
Example #8
0
/*!
  \param points Series of data points
  \return Curve points
*/
QPolygonF QwtWeedingCurveFitter::fitCurve( const QPolygonF &points ) const
{
    QStack<Line> stack;
    stack.reserve( 500 );

    const QPointF *p = points.data();
    const int nPoints = points.size();

    QVector<bool> usePoint( nPoints, false );

    double distToSegment;

    stack.push( Line( 0, nPoints - 1 ) );

    while ( !stack.isEmpty() )
    {
        const Line r = stack.pop();

        // initialize line segment
        const double vecX = p[r.to].x() - p[r.from].x();
        const double vecY = p[r.to].y() - p[r.from].y();

        const double vecLength = qSqrt( vecX * vecX + vecY * vecY );

        const double unitVecX = ( vecLength != 0.0 ) ? vecX / vecLength : 0.0;
        const double unitVecY = ( vecLength != 0.0 ) ? vecY / vecLength : 0.0;

        double maxDist = 0.0;
        int nVertexIndexMaxDistance = r.from + 1;
        for ( int i = r.from + 1; i < r.to; i++ )
        {
            //compare to anchor
            const double fromVecX = p[i].x() - p[r.from].x();
            const double fromVecY = p[i].y() - p[r.from].y();
            const double fromVecLength =
                qSqrt( fromVecX * fromVecX + fromVecY * fromVecY );

            if ( fromVecX * unitVecX + fromVecY * unitVecY < 0.0 )
            {
                distToSegment = fromVecLength;
            }
            if ( fromVecX * unitVecX + fromVecY * unitVecY < 0.0 )
            {
                distToSegment = fromVecLength;
            }
            else
            {
                const double toVecX = p[i].x() - p[r.to].x();
                const double toVecY = p[i].y() - p[r.to].y();
                const double toVecLength = qSqrt( toVecX * toVecX + toVecY * toVecY );
                const double s = toVecX * ( -unitVecX ) + toVecY * ( -unitVecY );
                if ( s < 0.0 )
                    distToSegment = toVecLength;
                else
                {
                    distToSegment = qSqrt( qFabs( toVecLength * toVecLength - s * s ) );
                }
            }

            if ( maxDist < distToSegment )
            {
                maxDist = distToSegment;
                nVertexIndexMaxDistance = i;
            }
        }
        if ( maxDist <= d_data->tolerance )
        {
            usePoint[r.from] = true;
            usePoint[r.to] = true;
        }
        else
        {
            stack.push( Line( r.from, nVertexIndexMaxDistance ) );
            stack.push( Line( nVertexIndexMaxDistance, r.to ) );
        }
    }

    int cnt = 0;

    QPolygonF stripped( nPoints );
    for ( int i = 0; i < nPoints; i++ )
    {
        if ( usePoint[i] )
            stripped[cnt++] = p[i];
    }
    stripped.resize( cnt );
    return stripped;
}
Example #9
0
void
Volume::findConnectedRegion(int mind, int maxd,
			    int minw, int maxw,
			    int minh, int maxh,
			    QList<int> pos,
			    bool sliceOnly)
{
  m_connectedbitmask.fill(false);

  uchar *lut = Global::lut();
  QStack<int> stack;

  uchar *vslice;
  uchar v0, g0;
  int d = pos[0];
  int w = pos[1];
  int h = pos[2];
  vslice = m_pvlFileManager.rawValue(d, w, h);
  v0 = vslice[0];
//  vslice = m_gradFileManager.rawValue(d, w, h);
//  g0 = vslice[0];
  g0 = 0;


  // put the seeds in
  for(int pi=0; pi<pos.size()/3; pi++)
    {
      int d = pos[3*pi];
      int w = pos[3*pi+1];
      int h = pos[3*pi+2];
      if (d >= mind && d <= maxd &&
	  w >= minw && w <= maxw &&
	  h >= minh && h <= maxh)
	{
	  qint64 idx = d*m_width*m_height + w*m_height + h;
	  if (m_bitmask.testBit(idx))
	    {
	      m_connectedbitmask.setBit(idx);
	      stack.push(d);
	      stack.push(w);
	      stack.push(h);
	    }
	}
    }

  if (sliceOnly)
    stack.clear();

  int pv = 0;
  int progv = 0;
  while(!stack.isEmpty())
    {
      progv++;
      if (progv == 1000)
	{
	  progv = 0;
	  pv = (++pv % 100);
	  emit progressChanged(pv);	  
	}

      int h = stack.pop();
      int w = stack.pop();
      int d = stack.pop();
      qint64 idx = d*m_width*m_height + w*m_height + h;
      if (m_bitmask.testBit(idx))
	{
	  int d0 = qMax(d-1, 0);
	  int d1 = qMin(d+1, m_depth-1);
	  int w0 = qMax(w-1, 0);
	  int w1 = qMin(w+1, m_width-1);
	  int h0 = qMax(h-1, 0);
	  int h1 = qMin(h+1, m_height-1);
	      
	  for(int d2=d0; d2<=d1; d2++)
	    for(int w2=w0; w2<=w1; w2++)
	      for(int h2=h0; h2<=h1; h2++)
		{
		  if (d2 >= mind && d2 <= maxd &&
		      w2 >= minw && w2 <= maxw &&
		      h2 >= minh && h2 <= maxh)
		    {
		      qint64 idx = d2*m_width*m_height +
			           w2*m_height + h2;
		      if ( m_bitmask.testBit(idx) &&
			   !m_connectedbitmask.testBit(idx) )
			{
//			  uchar v, g;
//			  vslice = m_pvlFileManager.rawValue(d2, w2, h2);
//			  v = vslice[0];
//			  vslice = m_gradFileManager.rawValue(d2, w2, h2);
//			  g = vslice[0];
//
//			  if (qAbs(v-v0) < Global::deltaV() &&
//			      g < Global::deltaG())
			    {
			      m_connectedbitmask.setBit(idx);
			      stack.push(d2);
			      stack.push(w2);
			      stack.push(h2);
			    }
			}
		    }
		}
	}
    } // end find connected
  //------------------------------------------------------

  emit progressReset();
}
Example #10
0
bool RCCResourceLibrary::interpretResourceFile(QIODevice *inputDevice,
    const QString &fname, QString currentPath, bool ignoreErrors)
{
    Q_ASSERT(m_errorDevice);
    const QChar slash = QLatin1Char('/');
    if (!currentPath.isEmpty() && !currentPath.endsWith(slash))
        currentPath += slash;

    QXmlStreamReader reader(inputDevice);
    QStack<RCCXmlTag> tokens;

    QString prefix;
    QLocale::Language language = QLocale::c().language();
    QLocale::Country country = QLocale::c().country();
    QString alias;
    int compressLevel = m_compressLevel;
    int compressThreshold = m_compressThreshold;

    while (!reader.atEnd()) {
        QXmlStreamReader::TokenType t = reader.readNext();
        switch (t) {
        case QXmlStreamReader::StartElement:
            if (reader.name() == m_strings.TAG_RCC) {
                if (!tokens.isEmpty())
                    reader.raiseError(QLatin1String("expected <RCC> tag"));
                else
                    tokens.push(RccTag);
            } else if (reader.name() == m_strings.TAG_RESOURCE) {
                if (tokens.isEmpty() || tokens.top() != RccTag) {
                    reader.raiseError(QLatin1String("unexpected <RESOURCE> tag"));
                } else {
                    tokens.push(ResourceTag);

                    QXmlStreamAttributes attributes = reader.attributes();
                    language = QLocale::c().language();
                    country = QLocale::c().country();

                    if (attributes.hasAttribute(m_strings.ATTRIBUTE_LANG)) {
                        QString attribute = attributes.value(m_strings.ATTRIBUTE_LANG).toString();
                        QLocale lang = QLocale(attribute);
                        language = lang.language();
                        if (2 == attribute.length()) {
                            // Language only
                            country = QLocale::AnyCountry;
                        } else {
                            country = lang.country();
                        }
                    }

                    prefix.clear();
                    if (attributes.hasAttribute(m_strings.ATTRIBUTE_PREFIX))
                        prefix = attributes.value(m_strings.ATTRIBUTE_PREFIX).toString();
                    if (!prefix.startsWith(slash))
                        prefix.prepend(slash);
                    if (!prefix.endsWith(slash))
                        prefix += slash;
                }
            } else if (reader.name() == m_strings.TAG_FILE) {
                if (tokens.isEmpty() || tokens.top() != ResourceTag) {
                    reader.raiseError(QLatin1String("unexpected <FILE> tag"));
                } else {
                    tokens.push(FileTag);

                    QXmlStreamAttributes attributes = reader.attributes();
                    alias.clear();
                    if (attributes.hasAttribute(m_strings.ATTRIBUTE_ALIAS))
                        alias = attributes.value(m_strings.ATTRIBUTE_ALIAS).toString();

                    compressLevel = m_compressLevel;
                    if (attributes.hasAttribute(m_strings.ATTRIBUTE_COMPRESS))
                        compressLevel = attributes.value(m_strings.ATTRIBUTE_COMPRESS).toString().toInt();

                    compressThreshold = m_compressThreshold;
                    if (attributes.hasAttribute(m_strings.ATTRIBUTE_THRESHOLD))
                        compressThreshold = attributes.value(m_strings.ATTRIBUTE_THRESHOLD).toString().toInt();

                    // Special case for -no-compress. Overrides all other settings.
                    if (m_compressLevel == -2)
                        compressLevel = 0;
                }
            } else {
                reader.raiseError(QString(QLatin1String("unexpected tag: %1")).arg(reader.name().toString()));
            }
            break;

        case QXmlStreamReader::EndElement:
            if (reader.name() == m_strings.TAG_RCC) {
                if (!tokens.isEmpty() && tokens.top() == RccTag)
                    tokens.pop();
                else
                    reader.raiseError(QLatin1String("unexpected closing tag"));
            } else if (reader.name() == m_strings.TAG_RESOURCE) {
                if (!tokens.isEmpty() && tokens.top() == ResourceTag)
                    tokens.pop();
                else
                    reader.raiseError(QLatin1String("unexpected closing tag"));
            } else if (reader.name() == m_strings.TAG_FILE) {
                if (!tokens.isEmpty() && tokens.top() == FileTag)
                    tokens.pop();
                else
                    reader.raiseError(QLatin1String("unexpected closing tag"));
            }
            break;

        case QXmlStreamReader::Characters:
            if (reader.isWhitespace())
                break;
            if (tokens.isEmpty() || tokens.top() != FileTag) {
                reader.raiseError(QLatin1String("unexpected text"));
            } else {
                QString fileName = reader.text().toString();
                if (fileName.isEmpty()) {
                    const QString msg = QString::fromLatin1("RCC: Warning: Null node in XML of '%1'\n").arg(fname);
                    m_errorDevice->write(msg.toUtf8());
                }

                if (alias.isNull())
                    alias = fileName;

                alias = QDir::cleanPath(alias);
                while (alias.startsWith(QLatin1String("../")))
                    alias.remove(0, 3);
                alias = QDir::cleanPath(m_resourceRoot) + prefix + alias;

                QString absFileName = fileName;
                if (QDir::isRelativePath(absFileName))
                    absFileName.prepend(currentPath);
                QFileInfo file(absFileName);
                if (!file.exists()) {
                    m_failedResources.push_back(absFileName);
                    const QString msg = QString::fromLatin1("RCC: Error in '%1': Cannot find file '%2'\n").arg(fname).arg(fileName);
                    m_errorDevice->write(msg.toUtf8());
                    if (ignoreErrors)
                        continue;
                    else
                        return false;
                } else if (file.isFile()) {
                    const bool arc =
                        addFile(alias,
                                RCCFileInfo(alias.section(slash, -1),
                                            file,
                                            language,
                                            country,
                                            RCCFileInfo::NoFlags,
                                            compressLevel,
                                            compressThreshold)
                                );
                    if (!arc)
                        m_failedResources.push_back(absFileName);
                } else {
                    QDir dir;
                    if (file.isDir()) {
                        dir.setPath(file.filePath());
                    } else {
                        dir.setPath(file.path());
                        dir.setNameFilters(QStringList(file.fileName()));
                        if (alias.endsWith(file.fileName()))
                            alias = alias.left(alias.length()-file.fileName().length());
                    }
                    if (!alias.endsWith(slash))
                        alias += slash;
                    QDirIterator it(dir, QDirIterator::FollowSymlinks|QDirIterator::Subdirectories);
                    while (it.hasNext()) {
                        it.next();
                        QFileInfo child(it.fileInfo());
                        if (child.fileName() != QLatin1String(".") && child.fileName() != QLatin1String("..")) {
                            const bool arc =
                                addFile(alias + child.fileName(),
                                        RCCFileInfo(child.fileName(),
                                                    child,
                                                    language,
                                                    country,
                                                    RCCFileInfo::NoFlags,
                                                    compressLevel,
                                                    compressThreshold)
                                        );
                            if (!arc)
                                m_failedResources.push_back(child.fileName());
                        }
                    }
                }
            }
            break;

        default:
            break;
        }
    }

    if (reader.hasError()) {
        if (ignoreErrors)
            return true;
        int errorLine = reader.lineNumber();
        int errorColumn = reader.columnNumber();
        QString errorMessage = reader.errorString();
        QString msg = QString::fromLatin1("RCC Parse Error: '%1' Line: %2 Column: %3 [%4]\n").arg(fname).arg(errorLine).arg(errorColumn).arg(errorMessage);
        m_errorDevice->write(msg.toUtf8());
        return false;
    }

    if (m_root == 0) {
        const QString msg = QString::fromUtf8("RCC: Warning: No resources in '%1'.\n").arg(fname);
        m_errorDevice->write(msg.toUtf8());
        if (!ignoreErrors && m_format == Binary) {
            // create dummy entry, otherwise loading with QResource will crash
            m_root = new RCCFileInfo(QString(), QFileInfo(),
                    QLocale::C, QLocale::AnyCountry, RCCFileInfo::Directory);
        }
    }

    return true;
}
Example #11
0
/**
    \internal
*/
bool GetOpt::parse( bool untilFirstSwitchOnly )
{
    // qDebug( "parse(%s)", args.join( QString( "," ) ).toLocal8Bit().constData() );
    // push all arguments as we got them on a stack
    // more pushes might following when parsing condensed arguments
    // like --key=value.
    QStack<QString> stack;
    {
        QStringList::const_iterator it = args.isEmpty() ? args.end() : --args.end();

        while ( it != args.constEnd() )
        {
            stack.push( *it );

            if ( it == args.begin() )
            {
                it = args.constEnd();
            }
            else
            {
                --it;
            }
        }
    }

    //qWarning() << stack;

    enum { StartState, ExpectingState, OptionalState } state = StartState;
    enum TokenType { LongOpt, ShortOpt, Arg, End } t, currType = End;

    const OptionConstIterator obegin = options.begin();
    const OptionConstIterator oend = options.end();
    Option currOpt;
    bool extraLoop = true; // we'll do an extra round. fake an End argument

    while ( !stack.isEmpty() || extraLoop )
    {
        QString a;
        QString origA;

        // identify argument type
        if ( !stack.isEmpty() )
        {
            a = stack.pop();
            currArg++;
            origA = a;

            // qDebug( "popped %s", a.toLocal8Bit().constData() );
            if ( a.startsWith( QLatin1String( "--" ) ) )
            {
                // recognized long option
                a = a.mid( 2 );

                if ( a.isEmpty() )
                {
                    qWarning( "'--' feature not supported, yet" );
                    //exit( 2 );
                    return false;
                }

                t = LongOpt;
                int equal = a.indexOf( '=' ); // split key=value style arguments

                if ( equal >= 0 )
                {
                    stack.push( a.mid( equal +1 ) );
                    currArg--;
                    a = a.left( equal );
                }
            }
            else if ( a.length() == 1 )
            {
                t = Arg;
            }
            else if ( a[ 0 ] == '-' )
            {
#if 0 // compat mode for -long style options
                if ( a.length() == 2 )
                {
                    t = ShortOpt;
                    a = a[ 1 ];
                }
                else
                {
                    a = a.mid( 1 );
                    t = LongOpt;
                    int equal = a.find( '=' ); // split key=value style arguments

                    if ( equal >= 0 )
                    {
                        stack.push( a.mid( equal +1 ) );
                        currArg--;
                        a = a.left( equal );
                    }
                }
#else
                // short option
                t = ShortOpt;

                // followed by an argument ? push it for later processing.
                if ( a.length() > 2 )
                {
                    stack.push( a.mid( 2 ) );
                    currArg--;
                }

                a = a[ 1 ];
#endif
            }
            else
            {
                t = Arg;
            }
        }
        else
        {
            // faked closing argument
            t = End;
        }

        // look up among known list of options
        Option opt;
        if ( t != End )
        {
            OptionConstIterator oit = obegin;

            while ( oit != oend )
            {
                const Option &o = *oit;

                if ( ( t == LongOpt && a == o.lname ) || ( t == ShortOpt && a[ 0 ].unicode() == o.sname ) )
                {
                    opt = o;
                    break;
                }

                ++oit;
            }

            if ( t == LongOpt && opt.type == OUnknown )
            {
                if ( currOpt.type != OVarLen )
                {
                    qWarning( "Unknown option --%s", a.toLocal8Bit().constData() );
                    return false;
                }
                else
                {
                    // VarLength options support arguments starting with '-'
                    t = Arg;
                }
            }
            else if ( t == ShortOpt && opt.type == OUnknown )
            {
                if ( currOpt.type != OVarLen )
                {
                    qWarning( "Unknown option -%c", a[ 0 ].unicode() );
                    return false;
                }
                else
                {
                    // VarLength options support arguments starting with '-'
                    t = Arg;
                }
            }

        }
        else
        {
            opt = Option( OEnd );
        }

        // interpret result
        switch ( state )
        {
        case StartState:
            if ( opt.type == OSwitch )
            {
                setSwitch( opt );
                setOptions.insert( opt.lname, 1 );
                setOptions.insert( QString( QChar( opt.sname ) ), 1 );
            }
            else if ( opt.type == OArg1 || opt.type == ORepeat )
            {
                state = ExpectingState;
                currOpt = opt;
                currType = t;
                setOptions.insert( opt.lname, 1 );
                setOptions.insert( QString( QChar( opt.sname ) ), 1 );
            }
            else if ( opt.type == OOpt || opt.type == OVarLen )
            {
                state = OptionalState;
                currOpt = opt;
                currType = t;
                setOptions.insert( opt.lname, 1 );
                setOptions.insert( QString( QChar( opt.sname ) ), 1 );
            }
            else if ( opt.type == OEnd )
            {
                // we're done
            }
            else if ( opt.type == OUnknown && t == Arg )
            {
                if ( numReqArgs > 0 )
                {
                    if ( reqArg.stringValue->isNull() )
                    {
                        *reqArg.stringValue = a;
                    }
                    else
                    {
                        qWarning( "Too many arguments" );
                        return false;
                    }
                }
                else if ( numOptArgs > 0 )
                {
                    if ( optArg.stringValue->isNull() )
                    {
                        *optArg.stringValue = a;
                    }
                    else
                    {
                        qWarning( "Too many arguments" );
                        return false;
                    }
                }
            }
            else
            {
                qFatal( "unhandled StartState case %d",  opt.type );
            }
            break;
        case ExpectingState:
            if ( t == Arg )
            {
                if ( currOpt.type == OArg1 )
                {
                    *currOpt.stringValue = a;
                    state = StartState;
                }
                else if ( currOpt.type == ORepeat )
                {
                    currOpt.listValue->append( a );
                    state = StartState;
                }
                else
                {
                    abort();
                }
            }
            else
            {
                QString n = currType == LongOpt ? currOpt.lname : QString( QChar( currOpt.sname ) );
                qWarning( "Expected an argument after '%s' option", n.toLocal8Bit().constData() );
                return false;
            }
            break;
        case OptionalState:
            if ( t == Arg )
            {
                if ( currOpt.type == OOpt )
                {
                    *currOpt.stringValue = a;
                    state = StartState;
                }
                else if ( currOpt.type == OVarLen )
                {
                    currOpt.listValue->append( origA );
                    // remain in this state
                }
                else
                {
                    abort();
                }
            }
            else
            {
                // optional argument not specified
                if ( currOpt.type == OOpt )
                {
                    *currOpt.stringValue = currOpt.def;
                }

                if ( t != End )
                {
                    // re-evaluate current argument
                    stack.push( origA );
                    currArg--;
                }

                state = StartState;
            }
            break;
        }

        if ( untilFirstSwitchOnly && opt.type == OSwitch )
        {
            return true;
        }

        // are we in the extra loop ? if so, flag the final end
        if ( t == End )
        {
            extraLoop = false;
        }
    }

    if ( numReqArgs > 0 && reqArg.stringValue->isNull() )
    {
        qWarning( "Lacking required argument" );
        return false;
    }

    return true;
}
QString plainTextToHtml(const QString &plaintext, const FlowedFormat flowed)
{
    QRegExp quotemarks;
    switch (flowed) {
    case FlowedFormat::FLOWED:
    case FlowedFormat::FLOWED_DELSP:
        quotemarks = QRegExp(QLatin1String("^>+"));
        break;
    case FlowedFormat::PLAIN:
        // Also accept > interleaved by spaces. That's what KMail happily produces.
        // A single leading space is accepted, too. That's what Gerrit produces.
        quotemarks = QRegExp(QLatin1String("^( >|>)+"));
        break;
    }
    const int SIGNATURE_SEPARATOR = -2;

    auto lines = plaintext.split(QLatin1Char('\n'));
    std::vector<TextInfo> lineBuffer;
    lineBuffer.reserve(lines.size());

    // First pass: determine the quote level for each source line.
    // The quote level is ignored for the signature.
    bool signatureSeparatorSeen = false;
    Q_FOREACH(const QString &line, lines) {

        // Fast path for empty lines
        if (line.isEmpty()) {
            lineBuffer.emplace_back(0, line);
            continue;
        }

        // Special marker for the signature separator
        if (signatureSeparator().exactMatch(line)) {
            lineBuffer.emplace_back(SIGNATURE_SEPARATOR, lineWithoutTrailingCr(line));
            signatureSeparatorSeen = true;
            continue;
        }

        // Determine the quoting level
        int quoteLevel = 0;
        if (!signatureSeparatorSeen && quotemarks.indexIn(line) == 0) {
            quoteLevel = quotemarks.cap(0).count(QLatin1Char('>'));
        }

        lineBuffer.emplace_back(quoteLevel, lineWithoutTrailingCr(line));
    }

    // Second pass:
    // - Remove the quotemarks for everything prior to the signature separator.
    // - Collapse the lines with the same quoting level into a single block
    //   (optionally into a single line if format=flowed is active)
    auto it = lineBuffer.begin();
    while (it < lineBuffer.end() && it->depth != SIGNATURE_SEPARATOR) {

        // Remove the quotemarks
        it->text.remove(quotemarks);

        switch (flowed) {
        case FlowedFormat::FLOWED:
        case FlowedFormat::FLOWED_DELSP:
            if (flowed == FlowedFormat::FLOWED || flowed == FlowedFormat::FLOWED_DELSP) {
                // check for space-stuffing
                if (it->text.startsWith(QLatin1Char(' '))) {
                    it->text.remove(0, 1);
                }

                // quirk: fix a flowed line which actually isn't flowed
                if (it->text.endsWith(QLatin1Char(' ')) && (
                        it+1 == lineBuffer.end() || // end-of-document
                        (it+1)->depth == SIGNATURE_SEPARATOR || // right in front of the separator
                        (it+1)->depth != it->depth // end of paragraph
                   )) {
                    it->text.chop(1);
                }
            }
            break;
        case FlowedFormat::PLAIN:
            if (it->depth > 0 && it->text.startsWith(QLatin1Char(' '))) {
                // Because the space is re-added when we prepend the quotes. Adding that space is done
                // in order to make it look nice, i.e. to prevent lines like ">>something".
                it->text.remove(0, 1);
            }
            break;
        }


        if (it == lineBuffer.begin()) {
            // No "previous line"
            ++it;
            continue;
        }

        // Check for the line joining
        auto prev = it - 1;
        if (prev->depth == it->depth) {

            QString separator = QStringLiteral("\n");
            switch (flowed) {
            case FlowedFormat::PLAIN:
                // nothing fancy to do here, we cannot really join lines
                break;
            case FlowedFormat::FLOWED:
            case FlowedFormat::FLOWED_DELSP:
                // CR LF trailing is stripped already (LFs by the split into lines, CRs by lineWithoutTrailingCr in pass #1),
                // so we only have to check for the trailing space
                if (prev->text.endsWith(QLatin1Char(' '))) {

                    // implement the DelSp thingy
                    if (flowed == FlowedFormat::FLOWED_DELSP) {
                        prev->text.chop(1);
                    }

                    if (it->text.isEmpty() || prev->text.isEmpty()) {
                        // This one or the previous line is a blank one, so we cannot really join them
                    } else {
                        separator = QString();
                    }
                }
                break;
            }
            prev->text += separator + it->text;
            it = lineBuffer.erase(it);
        } else {
            ++it;
        }
    }

    // Third pass: HTML escaping, formatting and adding fancy markup
    signatureSeparatorSeen = false;
    int quoteLevel = 0;
    QStringList markup;
    int interactiveControlsId = 0;
    QStack<QPair<int,int> > controlStack;
    for (it = lineBuffer.begin(); it != lineBuffer.end(); ++it) {

        if (it->depth == SIGNATURE_SEPARATOR && !signatureSeparatorSeen) {
            // The first signature separator
            signatureSeparatorSeen = true;
            closeQuotesUpTo(markup, controlStack, quoteLevel, 0);
            markup << QLatin1String("<span class=\"signature\">") + helperHtmlifySingleLine(it->text);
            markup << QStringLiteral("\n");
            continue;
        }

        if (signatureSeparatorSeen) {
            // Just copy the data
            markup << helperHtmlifySingleLine(it->text);
            if (it+1 != lineBuffer.end())
                markup << QStringLiteral("\n");
            continue;
        }

        Q_ASSERT(quoteLevel == 0 || quoteLevel != it->depth);

        if (quoteLevel > it->depth) {
            // going back in the quote hierarchy
            closeQuotesUpTo(markup, controlStack, quoteLevel, it->depth);
        }

        // Pretty-formatted block of the ">>>" characters
        QString quotemarks;

        if (it->depth) {
            quotemarks += QLatin1String("<span class=\"quotemarks\">");
            for (int i = 0; i < it->depth; ++i) {
                quotemarks += QLatin1String("&gt;");
            }
            quotemarks += QLatin1String(" </span>");
        }

        static const int previewLines = 5;
        static const int charsPerLineEquivalent = 160;
        static const int forceCollapseAfterLines = 10;

        if (quoteLevel < it->depth) {
            // We're going deeper in the quote hierarchy
            QString line;
            while (quoteLevel < it->depth) {
                ++quoteLevel;

                // Check whether there is anything at the newly entered level of nesting
                bool anythingOnJustThisLevel = false;

                // A short summary of the quotation
                QString preview;

                auto runner = it;
                while (runner != lineBuffer.end()) {
                    if (runner->depth == quoteLevel) {
                        anythingOnJustThisLevel = true;

                        ++interactiveControlsId;
                        controlStack.push(qMakePair(quoteLevel, interactiveControlsId));

                        QString omittedStuff;
                        QString previewPrefix, previewSuffix;
                        QString currentChunk = firstNLines(runner->text, previewLines, charsPerLineEquivalent);
                        QString omittedPrefix, omittedSuffix;
                        QString previewQuotemarks;

                        if (runner != it ) {
                            // we have skipped something, make it obvious to the user

                            // Find the closest level which got collapsed
                            int closestDepth = std::numeric_limits<int>::max();
                            auto depthRunner(it);
                            while (depthRunner != runner) {
                                closestDepth = std::min(closestDepth, depthRunner->depth);
                                ++depthRunner;
                            }

                            // The [...] marks shall be prefixed by the closestDepth quote markers
                            omittedStuff = QStringLiteral("<span class=\"quotemarks\">");
                            for (int i = 0; i < closestDepth; ++i) {
                                omittedStuff += QLatin1String("&gt;");
                            }
                            for (int i = runner->depth; i < closestDepth; ++i) {
                                omittedPrefix += QLatin1String("<blockquote>");
                                omittedSuffix += QLatin1String("</blockquote>");
                            }
                            omittedStuff += QStringLiteral(" </span><label for=\"q%1\">...</label>").arg(interactiveControlsId);

                            // Now produce the proper quotation for the preview itself
                            for (int i = quoteLevel; i < runner->depth; ++i) {
                                previewPrefix.append(QLatin1String("<blockquote>"));
                                previewSuffix.append(QLatin1String("</blockquote>"));
                            }
                        }

                        previewQuotemarks = QStringLiteral("<span class=\"quotemarks\">");
                        for (int i = 0; i < runner->depth; ++i) {
                            previewQuotemarks += QLatin1String("&gt;");
                        }
                        previewQuotemarks += QLatin1String(" </span>");

                        preview = previewPrefix
                                    + omittedPrefix + omittedStuff + omittedSuffix
                                + previewQuotemarks
                                + helperHtmlifySingleLine(currentChunk)
                                    .replace(QLatin1String("\n"), QLatin1String("\n") + previewQuotemarks)
                                + previewSuffix;

                        break;
                    }
                    if (runner->depth < quoteLevel) {
                        // This means that we have left the current level of nesting, so there cannot possible be anything else
                        // at the current level of nesting *and* in the current quote block
                        break;
                    }
                    ++runner;
                }

                // Is there nothing but quotes until the end of mail or until the signature separator?
                bool nothingButQuotesAndSpaceTillSignature = true;
                runner = it;
                while (++runner != lineBuffer.end()) {
                    if (runner->depth == SIGNATURE_SEPARATOR)
                        break;
                    if (runner->depth > 0)
                        continue;
                    if (runner->depth == 0 && !runner->text.isEmpty()) {
                        nothingButQuotesAndSpaceTillSignature = false;
                        break;
                    }
                }

                // Size of the current level, including the nested stuff
                int currentLevelCharCount = 0;
                int currentLevelLineCount = 0;
                runner = it;
                while (runner != lineBuffer.end() && runner->depth >= quoteLevel) {
                    currentLevelCharCount += runner->text.size();
                    // one for the actual block
                    currentLevelLineCount += runner->text.count(QLatin1Char('\n')) + 1;
                    ++runner;
                }


                if (!anythingOnJustThisLevel) {
                    // no need for fancy UI controls
                    line += QLatin1String("<blockquote>");
                    continue;
                }

                if (quoteLevel == it->depth
                        && currentLevelCharCount <= charsPerLineEquivalent * previewLines
                        && currentLevelLineCount <= previewLines) {
                    // special case: the quote is very short, no point in making it collapsible
                    line += QStringLiteral("<span class=\"level\"><input type=\"checkbox\" id=\"q%1\"/>").arg(interactiveControlsId)
                            + QLatin1String("<span class=\"shortquote\"><blockquote>") + quotemarks
                            + helperHtmlifySingleLine(it->text).replace(QLatin1String("\n"), QLatin1String("\n") + quotemarks);
                } else {
                    bool collapsed = nothingButQuotesAndSpaceTillSignature
                            || quoteLevel > 1
                            || currentLevelCharCount >= charsPerLineEquivalent * forceCollapseAfterLines
                            || currentLevelLineCount >= forceCollapseAfterLines;

                    line += QStringLiteral("<span class=\"level\"><input type=\"checkbox\" id=\"q%1\" %2/>")
                            .arg(QString::number(interactiveControlsId),
                                 collapsed ? QStringLiteral("checked=\"checked\"") : QString())
                            + QLatin1String("<span class=\"short\"><blockquote>")
                              + preview
                              + QStringLiteral(" <label for=\"q%1\">...</label>").arg(interactiveControlsId)
                              + QLatin1String("</blockquote></span>")
                            + QLatin1String("<span class=\"full\"><blockquote>");
                    if (quoteLevel == it->depth) {
                        // We're now finally on the correct level of nesting so we can output the current line
                        line += quotemarks + helperHtmlifySingleLine(it->text)
                                .replace(QLatin1String("\n"), QLatin1String("\n") + quotemarks);
                    }
                }
            }
            markup << line;
        } else {
            // Either no quotation or we're continuing an old quote block and there was a nested quotation before
            markup << quotemarks + helperHtmlifySingleLine(it->text)
                      .replace(QLatin1String("\n"), QLatin1String("\n") + quotemarks);
        }

        auto next = it + 1;
        if (next != lineBuffer.end()) {
            if (next->depth >= 0 && next->depth < it->depth) {
                // Decreasing the quotation level -> no starting <blockquote>
                markup << QStringLiteral("\n");
            } else if (it->depth == 0) {
                // Non-quoted block which is not enclosed in a <blockquote>
                markup << QStringLiteral("\n");
            }
        }
    }

    if (signatureSeparatorSeen) {
        // Terminate the signature
        markup << QStringLiteral("</span>");
    }

    if (quoteLevel) {
        // Terminate the quotes
        closeQuotesUpTo(markup, controlStack, quoteLevel, 0);
    }

    Q_ASSERT(controlStack.isEmpty());

    return markup.join(QString());
}
Example #13
0
void dspIndentedWhereUsed::sFillList()
{
  _bomitem->clear();

  if (_item->isValid())
  {
    q.prepare("SELECT indentedWhereUsed(:item_id) AS workset_id;");
    q.bindValue(":item_id", _item->id());
    q.exec();
    if (q.first())
    {
      int worksetid = q.value("workset_id").toInt();

      QString sql( "SELECT bomwork_level, bomwork_id, item_id, bomwork_parent_id,"
		           "       bomworkitemsequence(bomwork_id) as seqord, "
                   "       bomwork_seqnumber, item_number, uom_name,"
                   "       (item_descrip1 || ' ' || item_descrip2) AS itemdescription,"
                   "       formatQtyPer(bomwork_qtyper) AS qtyper,"
                   "       formatScrap(bomwork_scrap) AS scrap,"
                   "       formatDate(bomwork_effective, 'Always') AS effective,"
                   "       formatDate(bomwork_expires, 'Never') AS expires "
                   "FROM bomwork, item, uom "
                   "WHERE ( (bomwork_item_id=item_id)"
                   " AND (item_inv_uom_id=uom_id)"
                   " AND (bomwork_set_id=:bomwork_set_id)" );

      if (!_showExpired->isChecked())
        sql += " AND (bomwork_expires > CURRENT_DATE)";

      if (!_showFuture->isChecked())
        sql += " AND (bomwork_effective <= CURRENT_DATE)";

      sql += ") "
             "ORDER BY seqord;";

      q.prepare(sql);
      q.bindValue(":bomwork_set_id", worksetid);
      q.exec();

      QStack<XTreeWidgetItem*> parent;
      XTreeWidgetItem *last = 0;
      int level = 0;
      while(q.next())
      {
        // If the level this item is on is lower than the last level we just did then we need
        // to pop the stack a number of times till we are equal.
        while(q.value("bomwork_level").toInt() < level)
        {
          level--;
          last = parent.pop();
        }

        // If the level this item is on is higher than the last level we need to push the last
        // item onto the stack a number of times till we are equal. (Should only ever be 1.)
        while(q.value("bomwork_level").toInt() > level)
        {
          level++;
          parent.push(last);
          last = 0;
        }

        // If there is an item in the stack use that as the parameter to the new xlistviewitem
        // otherwise we'll just use the xlistview _layout
        if(!parent.isEmpty() && parent.top())
          last = new XTreeWidgetItem(parent.top(), last, q.value("bomwork_id").toInt(), q.value("item_id").toInt(),
                             q.value("bomwork_seqnumber"), q.value("item_number"),
                             q.value("itemdescription"), q.value("uom_name"),
                             q.value("qtyper"), q.value("scrap"),
                             q.value("effective"), q.value("expires") );
        else
          last = new XTreeWidgetItem(_bomitem, last, q.value("bomwork_id").toInt(), q.value("item_id").toInt(),
                             q.value("bomwork_seqnumber"), q.value("item_number"),
                             q.value("itemdescription"), q.value("uom_name"),
                             q.value("qtyper"), q.value("scrap"),
                             q.value("effective"), q.value("expires") );

      }
      _bomitem->expandAll();

      q.prepare("SELECT deleteBOMWorkset(:workset_id) AS result;");
      q.bindValue(":bomwork_set_id", worksetid);
      q.exec();
    }
  }
}
Example #14
0
void FlatTextarea::parseLinks() { // some code is duplicated in text.cpp!
	LinkRanges newLinks;

	QString text(toPlainText());
	if (text.isEmpty()) {
		if (!_links.isEmpty()) {
			_links.clear();
			emit linksChanged();
		}
		return;
	}

	initLinkSets();

	int32 len = text.size();
	const QChar *start = text.unicode(), *end = start + text.size();
	for (int32 offset = 0, matchOffset = offset; offset < len;) {
		QRegularExpressionMatch m = reDomain().match(text, matchOffset);
		if (!m.hasMatch()) break;

		int32 domainOffset = m.capturedStart();

		QString protocol = m.captured(1).toLower();
		QString topDomain = m.captured(3).toLower();

		bool isProtocolValid = protocol.isEmpty() || validProtocols().contains(hashCrc32(protocol.constData(), protocol.size() * sizeof(QChar)));
		bool isTopDomainValid = !protocol.isEmpty() || validTopDomains().contains(hashCrc32(topDomain.constData(), topDomain.size() * sizeof(QChar)));

		if (protocol.isEmpty() && domainOffset > offset + 1 && *(start + domainOffset - 1) == QChar('@')) {
			QString forMailName = text.mid(offset, domainOffset - offset - 1);
			QRegularExpressionMatch mMailName = reMailName().match(forMailName);
			if (mMailName.hasMatch()) {
				offset = matchOffset = m.capturedEnd();
				continue;
			}
		}
		if (!isProtocolValid || !isTopDomainValid) {
			offset = matchOffset = m.capturedEnd();
			continue;
		}

		QStack<const QChar*> parenth;
		const QChar *domainEnd = start + m.capturedEnd(), *p = domainEnd;
		for (; p < end; ++p) {
			QChar ch(*p);
			if (chIsLinkEnd(ch)) break; // link finished
			if (chIsAlmostLinkEnd(ch)) {
				const QChar *endTest = p + 1;
				while (endTest < end && chIsAlmostLinkEnd(*endTest)) {
					++endTest;
				}
				if (endTest >= end || chIsLinkEnd(*endTest)) {
					break; // link finished at p
				}
				p = endTest;
				ch = *p;
			}
			if (ch == '(' || ch == '[' || ch == '{' || ch == '<') {
				parenth.push(p);
			} else if (ch == ')' || ch == ']' || ch == '}' || ch == '>') {
				if (parenth.isEmpty()) break;
				const QChar *q = parenth.pop(), open(*q);
				if ((ch == ')' && open != '(') || (ch == ']' && open != '[') || (ch == '}' && open != '{') || (ch == '>' && open != '<')) {
					p = q;
					break;
				}
			}
		}
		if (p > domainEnd) { // check, that domain ended
			if (domainEnd->unicode() != '/' && domainEnd->unicode() != '?') {
				matchOffset = domainEnd - start;
				continue;
			}
		}
		newLinks.push_back(qMakePair(domainOffset - 1, p - start - domainOffset + 2));
		offset = matchOffset = p - start;
	}

	if (newLinks != _links) {
		_links = newLinks;
		emit linksChanged();
	}
}
void MessageLinksParser::parse() {
	const auto &textWithTags = _field->getTextWithTags();
	const auto &text = textWithTags.text;
	const auto &tags = textWithTags.tags;
	const auto &markdownTags = _field->getMarkdownTags();
	if (text.isEmpty()) {
		_list = QStringList();
		return;
	}

	auto ranges = QVector<LinkRange>();

	auto tag = tags.begin();
	const auto tagsEnd = tags.end();
	const auto processTag = [&] {
		Expects(tag != tagsEnd);

		if (Ui::InputField::IsValidMarkdownLink(tag->id)
			&& !IsMentionLink(tag->id)) {
			ranges.push_back({ tag->offset, tag->length, tag->id });
		}
		++tag;
	};
	const auto processTagsBefore = [&](int offset) {
		while (tag != tagsEnd && tag->offset + tag->length <= offset) {
			processTag();
		}
	};
	const auto hasTagsIntersection = [&](int till) {
		if (tag == tagsEnd || tag->offset >= till) {
			return false;
		}
		while (tag != tagsEnd && tag->offset < till) {
			processTag();
		}
		return true;
	};

	auto markdownTag = markdownTags.begin();
	const auto markdownTagsEnd = markdownTags.end();
	const auto markdownTagsAllow = [&](int from, int length) {
		while (markdownTag != markdownTagsEnd
			&& (markdownTag->adjustedStart
				+ markdownTag->adjustedLength <= from
				|| !markdownTag->closed)) {
			++markdownTag;
			continue;
		}
		if (markdownTag == markdownTagsEnd
			|| markdownTag->adjustedStart >= from + length) {
			return true;
		}
		// Ignore http-links that are completely inside some tags.
		// This will allow sending http://test.com/__test__/test correctly.
		return (markdownTag->adjustedStart > from)
			|| (markdownTag->adjustedStart
				+ markdownTag->adjustedLength < from + length);
	};

	const auto len = text.size();
	const QChar *start = text.unicode(), *end = start + text.size();
	for (auto offset = 0, matchOffset = offset; offset < len;) {
		auto m = qthelp::RegExpDomain().match(text, matchOffset);
		if (!m.hasMatch()) break;

		auto domainOffset = m.capturedStart();

		auto protocol = m.captured(1).toLower();
		auto topDomain = m.captured(3).toLower();
		auto isProtocolValid = protocol.isEmpty() || TextUtilities::IsValidProtocol(protocol);
		auto isTopDomainValid = !protocol.isEmpty() || TextUtilities::IsValidTopDomain(topDomain);

		if (protocol.isEmpty() && domainOffset > offset + 1 && *(start + domainOffset - 1) == QChar('@')) {
			auto forMailName = text.mid(offset, domainOffset - offset - 1);
			auto mMailName = TextUtilities::RegExpMailNameAtEnd().match(forMailName);
			if (mMailName.hasMatch()) {
				offset = matchOffset = m.capturedEnd();
				continue;
			}
		}
		if (!isProtocolValid || !isTopDomainValid) {
			offset = matchOffset = m.capturedEnd();
			continue;
		}

		QStack<const QChar*> parenth;
		const QChar *domainEnd = start + m.capturedEnd(), *p = domainEnd;
		for (; p < end; ++p) {
			QChar ch(*p);
			if (chIsLinkEnd(ch)) break; // link finished
			if (chIsAlmostLinkEnd(ch)) {
				const QChar *endTest = p + 1;
				while (endTest < end && chIsAlmostLinkEnd(*endTest)) {
					++endTest;
				}
				if (endTest >= end || chIsLinkEnd(*endTest)) {
					break; // link finished at p
				}
				p = endTest;
				ch = *p;
			}
			if (ch == '(' || ch == '[' || ch == '{' || ch == '<') {
				parenth.push(p);
			} else if (ch == ')' || ch == ']' || ch == '}' || ch == '>') {
				if (parenth.isEmpty()) break;
				const QChar *q = parenth.pop(), open(*q);
				if ((ch == ')' && open != '(') || (ch == ']' && open != '[') || (ch == '}' && open != '{') || (ch == '>' && open != '<')) {
					p = q;
					break;
				}
			}
		}
		if (p > domainEnd) { // check, that domain ended
			if (domainEnd->unicode() != '/' && domainEnd->unicode() != '?') {
				matchOffset = domainEnd - start;
				continue;
			}
		}
		const auto range = LinkRange {
			domainOffset,
			static_cast<int>(p - start - domainOffset),
			QString()
		};
		processTagsBefore(domainOffset);
		if (!hasTagsIntersection(range.start + range.length)) {
			if (markdownTagsAllow(range.start, range.length)) {
				ranges.push_back(range);
			}
		}
		offset = matchOffset = p - start;
	}
	processTagsBefore(QFIXED_MAX);

	apply(text, ranges);
}
LongInt Algorithm::Toom_Cook(LongInt a, LongInt b)
{
    /*/
    a=LongInt("529834750827340585463450529834750827340585463450529834750827340585463450529834750827340585463450529834750827340585463450529834750827340585463450529834750827340585463450529834750827340585463450529834750827340585463450529834750827340585463450529834750827340585463450529834750827340585463450529834750827340585463450529834750827340585463450529834750827340585463450529834750827340585463450529834750827340585463450529834750827340585463450529834750827340585463450529834750827340585463450529834750827340585463450529834750827340585463450529834750827340585463450529834750827340585463450529834750827340585463450529834750827340585463450529834750827340585463450529834750827340585463450529834750827340585463450529834750827340585463450529834750827340585463450529834750827340585463450");
    b=LongInt("29834750827340585463450529834750827340585463450529834750827340585463450529834750827340585463450529834750827340585463450529834750827340585463450529834750827340585463450529834750827340585463450529834750827340585463450529834750827340585463450529834750827340585463450529834750827340585463450529834750827340585463450529834750827340585463450529834750827340585463450529834750827340585463450529834750827340585463450529834750827340585463450529834750827340585463450529834750827340585463450529834750827340585463450529834750827340585463450529834750827340585463450529834750827340585463450");
    qDebug()<<a.length();
    LongInt z=Strassen(a,b);
    /*/
    //===T1===========initialization=table=and=stack===
    qDebug()<<"Hello Lord of Iteration";
    QStack<LongInt> U,V;
    QStack<LongInt> W;
    QStack<int> C;

    int Index,i,j;//for iteration;
    //=======================Table===========
    int k=1;
    int Q=2,R=1;
    Table table={4,2};

    QVector<Table> qv_table;
    qv_table<<table<<table;
    QVector<Table>::iterator iter_table;//=qv_table.begin();

    int last_q=4;

    qDebug()<<qA<<"\"(0)\""<<Q<<R<<table.q<<table.r;
    while(a.length()>(qv_table.last().q+last_q))
    {
        qDebug()<<"algorithm.cpp:"<<"("+QString::number(k)+")"<<Q<<R<<table.q<<table.r;
        k++;
        Q+=R;
        table.q*=table.r;
        R++;
        if(R*R<=Q)//if((R+1)^2>=Q) R++;
        {
            table.r*=2;
        }
        else R--;
        last_q=qv_table.last().q;
        qv_table<<table;
    }
    qDebug()<<"algorithm.cpp:"<<"("+QString::number(k)+")"<<Q<<R<<table.q<<table.r;
    iter_table=qv_table.end();
    iter_table--;
    LongInt numbers[10*iter_table->r+1];
    //===================T2============================
    C.push(-1);
    C<<a.number<<-5<<b.number;
    a.clear();
    b.clear();
    int forSwitch=1;//iter_table--;
    //====================Cycle========================
    //bool isEnd=0;
    while(1)
    {
        switch(forSwitch)
        {
        case 1://T3
        {
            k--;
            iter_table--;
            //qDebug()<<"K="<<k;
            if(!k)
            {
                a.clear();
                b.clear();
                //qDebug()<<"C="<<C;
                while(!C.isEmpty())
                {
                    Q=C.pop();
                    if(Q>=0)
                    {
                        b.push_front(Q);
                    }
                    else
                    {
                        break;
                    }
                }
                //qDebug()<<"C="<<C;
                while(!C.isEmpty())
                {
                    Q=C.pop();
                    if(Q>=0)
                    {
                        a.push_front(Q);
                    }
                    else
                    {
                        C.push(Q);
                        break;
                    }
                }
                //qDebug()<<"algorithm.cpp:"<<a<<"*"<<b<<"=";
                forSwitch=5;
                a*=b;
                //qDebug()<<"algorithm.cpp:"<<a;
            }
            else
            {
                forSwitch=2;
            }
            break;
        }
        case 2://T4 T5
        {
            //=====T4=========
            Index=0;
            numbers[0].clear();
            //qDebug()<<"T4 C"<<C;

            while(!C.isEmpty())
            {
                Q=C.pop();
                if(Q>=0)
                {
                    if(numbers[Index].length()>=iter_table->q)
                    {
                        //qDebug()<<"algorithm.cpp:("<<Index<<")"<<numbers[Index];
                        numbers[Index].normalization();
                        Index++;
                        numbers[Index].clear();
                    }
                    numbers[Index].push_front(Q);
                }
                else
                {
                    break;
                }
            }
            //qDebug()<<"algorithm.cpp:("<<Index<<")"<<numbers[Index];
            R=iter_table->r+Index;
            //qDebug()<<R;
            //qDebug()<<Index;
            for(j=0;j<=R;j++)
            {
                a=numbers[Index];
                for(i=Index-1;i>=0;i--)
                {
                    a*=j;
                    a+=numbers[i];
                }
                U<<a;
            }
            Index=0;
            numbers[0].clear();
            while(!C.isEmpty())
            {
                Q=C.pop();
                if(Q>=0)
                {
                    if(numbers[Index].length()>=iter_table->q)
                    {
                        //qDebug()<<"algorithm.cpp:("<<Index<<")"<<numbers[Index];
                        numbers[Index].normalization();
                        Index++;
                        numbers[Index].clear();
                    }
                    numbers[Index].push_front(Q);
                }
                else
                {
                    C.push(Q);
                    break;
                }
            }
            //qDebug()<<"algorithm.cpp:("<<Index<<")"<<numbers[Index];
            //qDebug()<<Index;
            for(j=0;j<=R;j++)
            {
                a=numbers[Index];
                //qDebug()<<"algorithm.cpp:j="<<j;
                for(i=Index-1;i>=0;i--)
                {
                    a*=j;
                    a+=numbers[i];
                }
                //qDebug()<<"algorithm.cpp:a="<<a;
                V<<a;
            }
            //qDebug()<<"algorithm.cpp:V="<<V;
            //=====T5=========
            if(!U.isEmpty()||!V.isEmpty())
            {
                C<<-2<<V.pop().number<<-5<<U.pop().number;
                while(!U.isEmpty()||!V.isEmpty())
                {
                    C<<-3<<V.pop().number<<-5<<U.pop().number;
                }
            }
            else
            {
                //qDebug()<<"Error algorithm.cpp: U or V Empty";
            }
            //qDebug()<<"C="<<C;
            b.clear();
            b.push_front(-4);
            W<<b;
            forSwitch=1;
            break;
        }
        case 3://T6
        {
            W<<a;
            forSwitch=1;
            //qDebug()<<"algorithm.cpp:a="<<a;
            break;
        }
        case 4://T7 T8 T9
        {
            //qDebug()<<W<<"\n";
            //W.clear();
            //W<<-4<<10<<304<<1980<<7084<<18526;
            Index=-1;
            while (!W.isEmpty())
            {
                //b=W.pop();
                Index++;
                //qDebug()<<"W="<<W;
                numbers[Index]=W.pop();
                //qDebug()<<W.length();
                if(numbers[Index]<0)
                {
                    //qDebug()<<W.length();
                    Index--;
                    break;
                }
            }
            //qDebug()<<W;
            //=====T7=========
            for(j=1;j<=Index;j++)
            {
                for(i=0;i<=Index-j;i++)
                {
                    numbers[i]=(numbers[i]-numbers[i+1])/LongInt(j);
                    //qDebug()<<"numb"<<numbers[i]<<j;
                }
                //qDebug()<<numbers[Index-j+1]<<j;
            }
            //qDebug()<<numbers[Index-j+1];

            /*/
            for(i=0;i<=Index;i++)
            {
                qDebug()<<"(T7)numbers="<<numbers[i];
            }
            /*/

            //=====T8=========
            //qDebug()<<"";
            for(j=Index-1;j>=1;j--)
            {
                for(i=Index-j;i>=1;i--)
                {
                    //qDebug()<<j<<i;
                    numbers[i]-=numbers[i-1]*j;
                }
            }

            /*/
            for(i=0;i<=Index;i++)
            {
                qDebug()<<"(T8)numbers="<<numbers[i];
            }
            /*/

            //=====T9=========
            a=numbers[0];
            //qDebug()<<iter_table->q;
            for(i=1;i<=Index;i++)
            {
                a=(a<<iter_table->q)+numbers[i];
                //qDebug()<<a<<a.length()<<iter_table->q<<numbers[i];
            }
            //qDebug()<<"";
            forSwitch=5;
            break;
        }
        case 5://T10
        {
            k++;
            iter_table++;
            if(!C.isEmpty())
            switch(C.pop())
            {
            case -1:
            {
                /*/
                qDebug()<<"a=  "<<a;
                qDebug()<<"z=  "<<z;
                if(a==z)
                {
                    qDebug()<<"a=z";
                }
                /*/
                return a;
                break;
            }
            case -2:
            {
                W<<a;
                forSwitch=4;
                //qDebug()<<"-2";
                break;
            }
            case -3:
            {
                forSwitch=3;
                //qDebug()<<"-3";
                break;
            }
            default:
            {
                //qDebug()<<"error";
                break;
            }
            }
            else
            {
                //qDebug()<<"Error algorithm.cpp: C Empty";
            }

            break;
        }
        }
    }
}
Example #17
0
bool SGFParser::doParse(const QString &toParseStr)
{
	if (toParseStr.isNull() || toParseStr.isEmpty())
	{
		qWarning("Failed loading from file. Is it empty?");
		return false;
	}
	QString tmp;

	if(!loadedfromfile)
	{
		/* This bit of ugliness is because sgfs are used to duplicate boards as well
		 * as load from file FIXME */
		parseProperty(toParseStr, "CA", tmp);		//codec
		if (!tmp.isEmpty())
			readCodec = QTextCodec::codecForName(tmp.toLatin1().constData());
	}
	
	const MyString *toParse = NULL;

//////TODO	if (static_cast<Codec>(setting->readIntEntry("CODEC")) == codecNone)
/////////		toParse = new MySimpleString(toParseStr);
///////	else
		toParse = new MyString(toParseStr);

	Q_CHECK_PTR(toParse);
	
	int 	pos = 0,
		posVarBegin = 0,
		posVarEnd = 0,
		posNode = 0,
		moves = 0,
		i, x=-1, y=-1;

	int 	a_offset = QChar::fromLatin1('a').unicode() - 1 ;

	unsigned int pointer = 0,
		strLength = toParse->length();
	bool black = true,
		setup = false,
        old_label = false;
	isRoot = true;
	bool remember_root;
	QString unknownProperty;
	State state;
	MarkType markType;
	QString moveStr, commentStr;
	Position *position;
	MoveNum *moveNum;
	QStack<Move*> stack;
	QStack<MoveNum*> movesStack;
	/* FIXME toRemove, et., al., appears unused Remove it */
	QStack<Position*> toRemove;
/*
////TODO	stack.setAutoDelete(false);
	movesStack.setAutoDelete(true);
	toRemove.setAutoDelete(true);
*/
	// Initialises the tree with board size
	parseProperty(toParseStr, "SZ", tmp);
//	Tree *tree = new Tree(tmp.isEmpty() ? 19 : tmp.toInt()) ;// boardHandler->getTree();
	
	state = stateVarBegin;
	
	bool cancel = false;
    //FIXME abort does nothing!!
	
	// qDebug("File length = %d", strLength);
	
    tree->setLoadingSGF(true);
	
	QString sss="";
    do {
		posVarBegin = toParse->find('(', pointer);
		posVarEnd = toParse->find(')', pointer);
		posNode = toParse->find(';', pointer);
		
		pos = minPos(posVarBegin, posVarEnd, posNode);

		// Switch states

		// Node -> VarEnd
		if (state == stateNode && pos == posVarEnd)
			state = stateVarEnd;
		
		// Node -> VarBegin
		if (state == stateNode && pos == posVarBegin)
			state = stateVarBegin;
		
		// VarBegin -> Node
		else if (state == stateVarBegin && pos == posNode)
			state = stateNode;
		
		// VarEnd -> VarBegin
		else if (state == stateVarEnd && pos == posVarBegin)
			state = stateVarBegin;
		
		// qDebug("State after switch = %d", state);
		
		// Do the work
		switch (state)
		{
		case stateVarBegin:
			if (pos != posVarBegin)
			{
				delete toParse;
				return corruptSgf(pos);
			}
			
			// qDebug("Var BEGIN at %d, moves = %d", pos, moves);
			
			stack.push(tree->getCurrent());
			moveNum = new MoveNum;
			moveNum->n = moves;
			movesStack.push(moveNum);
			pointer = pos + 1;
			break;
			
		case stateVarEnd:
			if (pos != posVarEnd)
			{
				delete toParse;
				return corruptSgf(pos);
			}
			
			// qDebug("VAR END");
			
			if (!movesStack.isEmpty() && !stack.isEmpty())
			{
				Move *m = stack.pop();
				Q_CHECK_PTR(m);
				x = movesStack.pop()->n;
				
				// qDebug("Var END at %d, moves = %d, moves from stack = %d", pos, moves, x);
				
				for (i=moves; i > x; i--)
				{
					position = toRemove.pop();
					if (position == NULL)
						continue;
///////////////////			boardHandler->getStoneHandler()->removeStone(position->x, position->y);
//					tree->removeStone(position->x, position->y);
					// qDebug("Removing %d %d from stoneHandler.", position->x, position->y);
				}
				
				moves = x;
 							
				
				tree->setCurrent(m);
			}
			pointer = pos + 1;
			break;
			
		case stateNode:
			if (pos != posNode)
			{
				delete toParse;
				return corruptSgf(pos);
			}
			
			// qDebug("Node at %d", pos);
			commentStr = QString();
			setup = false;
			markType = markNone;
			
			// Create empty node
			remember_root = isRoot;
			if (!isRoot)
			{
/////////////////////		boardHandler->createMoveSGF();
//				qDebug("############### Before creating move ####################");
//				qDebug(toParse->Str.toLatin1().constData());
				//tree->createMoveSGF();
				/* This does happen, why??? FIXME */
//				qDebug("###############                      ####################");
//				qDebug(toParse->Str.toLatin1().constData());
//				qDebug("############### After creating move ####################");
				unknownProperty = QString();
#ifdef FIXME	//why is this a warning? this happens on loading a file with time info
				if (tree->getCurrent()->getTimeinfo())
				qWarning("*** Timeinfo set !!!!");
#endif //FIXME
				//tree->getCurrent()->setTimeinfo(false);
			}
			else
				isRoot = false;
						
			Property prop;
			pos ++;

			do {
				uint tmppos=0;
				pos = toParse->next_nonspace (pos);
				
                if ((tmppos = toParse->isProperty("B",pos)))
				{
					prop = moveBlack;
					pos = tmppos;
					black = true;
				}
                else if ((tmppos = toParse->isProperty("W",pos)))
				{
					prop = moveWhite;
					pos = tmppos;
					black = false;
				}
                else if ((tmppos = toParse->isProperty("N",pos)))
				{
					prop = nodeName;
					pos = tmppos;
				}
                else if ((tmppos = toParse->isProperty("AB",pos)))
				{
					prop = editBlack;
					pos = tmppos;
					setup = true;
					black = true;
				}
                else if ((tmppos = toParse->isProperty("AW",pos)))
				{
					prop = editWhite;
					pos = tmppos;
					setup = true;
					black = false;
				}
                else if ((tmppos = toParse->isProperty("AE",pos)))
				{
					prop = editErase;
					pos = tmppos;
					setup = true;
				}
                else if ((tmppos = toParse->isProperty("TR",pos)))
				{
					prop = editMark;
					markType = markTriangle;
					pos = tmppos;
				}
                else if ((tmppos = toParse->isProperty("CR",pos)))
				{
					prop = editMark;
					markType = markCircle;
					pos = tmppos;
				}
                else if ((tmppos = toParse->isProperty("SQ",pos)))
				{
					prop = editMark;
					markType = markSquare;
					pos = tmppos;
				}
                else if ((tmppos = toParse->isProperty("MA",pos)))
				{
					prop = editMark;
					markType = markCross;
					pos = tmppos;
				}
				// old definition
                else if ((tmppos = toParse->isProperty("M",pos)))
				{
					prop = editMark;
					markType = markCross;
					pos = tmppos;
				}
                else if ((tmppos = toParse->isProperty("LB",pos)))
				{
					prop = editMark;
					markType = markText;
					pos = tmppos;
					old_label = false;
				}
				// Added old L property. This is not SGF4, but many files contain this tag.
                else if ((tmppos = toParse->isProperty("L",pos)))
				{
					prop = editMark;
					markType = markText;
					pos = tmppos;
					old_label = true;
				}
                else if ((tmppos = toParse->isProperty("C",pos)))
				{
					prop = comment;
					pos = tmppos;
				}
                else if ((tmppos = toParse->isProperty("TB",pos)))
				{
					prop = editMark;
					markType = markTerrBlack;
					pos = tmppos;
					black = true;
				}
                else if ((tmppos = toParse->isProperty("TW",pos)))
				{
					prop = editMark;
					markType = markTerrWhite;
					pos = tmppos;
					black = false;
				}
                else if ((tmppos = toParse->isProperty("BL",pos)))
				{
					prop = timeLeft;
					pos = tmppos;
					black = true;
				}
                else if ((tmppos = toParse->isProperty("WL",pos)))
				{
					prop = timeLeft;
					pos = tmppos;
					black = false;
				}
                else if ((tmppos = toParse->isProperty("OB",pos)))
				{
					prop = openMoves;
					pos = tmppos;
					black = true;
				}
                else if ((tmppos = toParse->isProperty("OW",pos)))
				{
					prop = openMoves;
					pos = tmppos;
					black = false;
				}
                else if ((tmppos = toParse->isProperty("PL",pos)))
				{
					prop = nextMove;
					pos = tmppos;
				}
                    else if ((tmppos = toParse->isProperty("RG",pos)))
				{
					prop = unknownProp;
					pos = tmppos;
          				setup = true;
				}
				// Empty node
				else if (toParse->at(pos) == ';' || toParse->at(pos) == '(' || toParse->at(pos) == ')')
				{
					qDebug("Found empty node at %d", pos);
					while (toParse->at(pos).isSpace())
						pos++;
					continue;
				}
				else
				{
					// handle like comment
					prop = unknownProp;
					pos = toParse->next_nonspace (pos);
					//qDebug("SGF: next nonspace (1st):" + QString(toParse->at(pos)) + QString(toParse->at(pos+1)) + QString(toParse->at(pos+2)));
				}
				
				//qDebug("Start do loop : FOUND PROP %d, pos at %d now", prop, pos);
				//qDebug(toParse->getStr());			//causes crash
				// Next is one or more '[xx]'.
				// Only one in a move property, several in a setup propery
				do {
					if (toParse->at(pos) != '[' && prop != unknownProp)
					{
						delete toParse;
						return corruptSgf(pos);
					}
					
					// Empty type
					if (toParse->at(pos+1) == ']')
					{
						// CGoban stores pass as 'B[]' or 'W[]'
						if (prop == moveBlack || prop == moveWhite)
						{
							tree->doPass(true);
							
							// Remember this move for later, to remove from the matrix.
							position = new Position;
							position->x = x;
							position->y = y;
							toRemove.push(position);
							moves ++;
						}
						
						pos += 2;
						continue;
					}
					
					switch (prop)
					{
					case moveBlack:
					case moveWhite:
						// rare case: root contains move or placed stone:
						if (remember_root)
						{
							qDebug("root contains stone -> node created");
							/* Something is screwy here, inconsistencies
							 * in the way SGF's are treated. Like the below:
							 * the whole point of "remember_root", FIXME*/
							tree->addEmptyMove();
							isRoot = false;
							unknownProperty = QString();
#ifdef FIXME	//why is this a warning?
							if (tree->getCurrent()->getTimeinfo())
								qWarning("*** Timeinfo set (2)!!!!");
#endif //FIXME
							//tree->getCurrent()->setTimeinfo(false);
						}
					case editBlack:
					case editWhite:
					case editErase:
					{
						x = toParse->at(pos+1).unicode() - a_offset ;// - 'a';// + 1;
						y = toParse->at(pos+2).unicode() - a_offset ; //- 'a' + 1;

						int x1, y1;
						bool compressed_list;

						// check for compressed lists
						if (toParse->at(pos+3) == ':')
						{
							x1 = toParse->at(pos+4).unicode() -a_offset;// - 'a' + 1;
							y1 = toParse->at(pos+5).unicode() -a_offset;// - 'a' + 1;
							compressed_list = true;
						}
						else
						{
							x1 = x;
							y1 = y;
							compressed_list = false;
						}
/*								
*						TODO Do we nned this when the tree is created from file ?
*						boardHandler->setModeSGF(setup || compressed_list ? modeEdit : modeNormal);
*/
						
						int i, j;
						for (i = x; i <= x1; i++)
							for (j = y; j <= y1; j++)
                            {
                                if (prop == editErase)
								{
									tree->addStoneToCurrentMove(stoneErase, i, j);
								}
								else
								{
									if(setup)
									{
                                        if ((!remember_root) && (stack.top() == tree->getCurrent()))
                                            tree->addEmptyMove(); //if this is first in branch we need to add an empty move

										tree->addStoneToCurrentMove(black ? stoneBlack : stoneWhite, i, j);
									}
									else
                                    {
                                        Move *result = tree->getCurrent()->makeMove(black ? stoneBlack : stoneWhite, i, j);
                                        if (result)
                                            tree->setCurrent(result);
                                    }
								}
								// tree->getCurrent()->getMatrix()->debug();
								//qDebug("ADDING MOVE %s %d/%d", black?"B":"W", x, y);
								
								// Remember this move for later, to remove from the matrix.
								position = new Position;
								position->x = i;
								position->y = j;
								toRemove.push(position);
								moves ++;
							}
												
						if (compressed_list)
							// Advance pos by 7
							pos += 7;
						else
							// Advance pos by 4
							pos += 4;
						break;
					}
						
					case nodeName:
					{
						commentStr = QString();
						bool skip = false;
						
						while (toParse->at(++pos) != ']')
						{
							if (static_cast<unsigned int>(pos) > strLength-1)
							{
								qDebug("SGF: Nodename string ended immediately");
								delete toParse;
								return corruptSgf(pos, "SGF: Nodename string ended immediately");
							}

							// white spaces
							if (toParse->at(pos) == '\\')
							{
								while (toParse->at(pos+1).isSpace() &&
									static_cast<unsigned int>(pos) < strLength-2)
									pos++;
								if (toParse->at(pos).isSpace())
									pos++;

								// case: "../<cr><lf>]"
								if (toParse->at(pos) == ']')
								{
									pos--;
									skip = true;
								}
							}

							// escaped chars: '\', ']', ':'
							if (!(toParse->at(pos) == '\\' &&
								(toParse->at(pos+1) == ']' ||
								 toParse->at(pos+1) == '\\' ||
								 toParse->at(pos+1) == ':')) &&
								 !skip &&
								 // no formatting
								!(toParse->at(pos) == '\n') &&
								!(toParse->at(pos) == '\r'))
								commentStr.append(toParse->at(pos));
						}
						
					 	//qDebug("Node name read: %s", commentStr.toLatin1().constData());
						if (!commentStr.isEmpty())
							// add comment; skip 'C[]'
							tree->getCurrent()->setNodeName(commentStr);
						pos++;
						break;
					}

					case comment:
					{
						commentStr = QString();
						bool skip = false;
						
						while (toParse->at(++pos) != ']' ||
							(toParse->at(pos-1) == '\\' && toParse->at(pos) == ']'))
						{
							if (static_cast<unsigned int>(pos) > strLength-1)
							{
								qDebug("SGF: Comment string ended immediately");
								delete toParse;
								return corruptSgf(pos, "SGF: Comment string ended immediately");
							}

							// white spaces
							if (toParse->at(pos) == '\\')
							{
								while (toParse->at(pos+1).isSpace() &&
									static_cast<unsigned int>(pos) < strLength-2)
									pos++;
								if (toParse->at(pos).isSpace())
									pos++;

								// case: "../<cr><lf>]"
								if (toParse->at(pos) == ']')
								{
									pos--;
									skip = true;
								}
							}

							// escaped chars: '\', ']', ':'
							if (!(toParse->at(pos) == '\\' &&
								(toParse->at(pos+1) == ']' ||
								 toParse->at(pos+1) == '\\' ||
								 toParse->at(pos+1) == ':')) &&
								 !skip)
								commentStr.append(toParse->at(pos));
						}

						//qDebug("Comment read: %s", commentStr.toLatin1().constData());
						if (!commentStr.isEmpty())
						{
							// add comment; skip 'C[]'
							if(readCodec)
								tree->getCurrent()->setComment(readCodec->toUnicode(commentStr.toLatin1().constData()));
							else
								tree->getCurrent()->setComment(commentStr.toLatin1().constData());
						}
						pos ++;
						break;
					}

					case unknownProp:
					{
						// skip if property is known anyway
						bool skip = false;

						// save correct property name (or p.n. + '[')
						commentStr = QString(toParse->at(pos));
						commentStr += toParse->at(tmppos = toParse->next_nonspace (pos + 1));
						pos = tmppos;

						// check if it's really necessary to hold properties
						// maybe they are handled at another position
						if (commentStr == "WR" ||
							commentStr == "BR" ||
							commentStr == "PW" ||
							commentStr == "PB" ||
							commentStr == "SZ" ||
							commentStr == "KM" ||
							commentStr == "HA" ||
							commentStr == "RE" ||
							commentStr == "DT" ||
							commentStr == "PC" ||
							commentStr == "CP" ||
							commentStr == "GN" ||
							commentStr == "OT" ||
							commentStr == "TM" ||
							// now: general options
							commentStr == "GM" ||
							commentStr == "ST" ||
							commentStr == "AP" ||
							commentStr == "FF")
						{
							skip = true;
						}
						sss= toParse->at(pos);
						while (toParse->at(++pos) != ']' ||
							(toParse->at(pos-1) == '\\' && toParse->at(pos) == ']'))
						{
							if (static_cast<unsigned int>(pos) > strLength-1)
							{
								qDebug("SGF: Unknown property ended immediately");
								delete toParse;
								return corruptSgf(pos, "SGF: Unknown property ended immediately");
							}
              						sss= toParse->at(pos);
							if (!skip)
								commentStr.append(toParse->at(pos));
						}

						if (!skip)
							commentStr.append("]");

						// qDebug("Comment read: %s", commentStr.latin1());
						if ((!commentStr.isEmpty()) && (!skip))
						{
							// cumulate unknown properties; skip empty property 'XZ[]'
							unknownProperty += commentStr;
							tree->getCurrent()->setUnknownProperty(unknownProperty);
						}
						pos ++;
            					sss= toParse->at(pos);
						break;
					}

					case editMark:
						// set moveStr for increment labels of old 'L[]' property
						moveStr = "A";
						while (toParse->at(pos) == '[' &&
							static_cast<unsigned int>(pos) < strLength)
						{
							x = toParse->at(pos+1).unicode() -a_offset;// - 'a' + 1;
							y = toParse->at(pos+2).unicode() -a_offset;// - 'a' + 1;
							// qDebug("MARK: %d at %d/%d", markType, x, y);
							pos += 3;
							
							// 'LB' property? Then we need to get the text
							if (markType == markText && !old_label)
							{
								if (toParse->at(pos) != ':')
								{
									delete toParse;
									return corruptSgf(pos);
								}
								moveStr = "";
								while (toParse->at(++pos) != ']' &&
									static_cast<unsigned int>(pos) < strLength)
									moveStr.append(toParse->at(pos));
								// qDebug("LB TEXT = %s", moveStr.latin1());
								// It might me a number mark?
								bool check = false;
								moveStr.toInt(&check);  // Try to convert to Integer
								// treat integers as characters...
								check = false;
								
								if (check)
									tree->getCurrent()->getMatrix()->
									insertMark(x, y, markNumber);  // Worked, its a number
								else
									tree->getCurrent()->getMatrix()->
									insertMark(x, y, markType);    // Nope, its a letter
								tree->getCurrent()->getMatrix()->
										setMarkText(x, y, moveStr);
							
								/*else	//fastload
								{
									if (check)  // Number
										tree->getCurrent()->insertFastLoadMark(x, y, markNumber);
									else        // Text
										tree->getCurrent()->insertFastLoadMark(x, y, markType, moveStr);
								}*/
							}
							else
							{
								int x1, y1;
								bool compressed_list;

								// check for compressed lists
								if (toParse->at(pos) == ':')
								{
									x1 = toParse->at(pos+1).unicode() -a_offset;// - 'a' + 1;
									y1 = toParse->at(pos+2).unicode() -a_offset;// - 'a' + 1;
									compressed_list = true;
								}
								else
								{
									x1 = x;
									y1 = y;
									compressed_list = false;
								}
								
								int i, j;
								for (i = x; i <= x1; i++)
									for (j = y; j <= y1; j++)
									{
										tree->getCurrent()->getMatrix()->insertMark(i, j, markType);
										//else	//fastload
										//	tree->getCurrent()->insertFastLoadMark(i, j, markType);

										// auto increment for old property 'L'
										if (old_label)
										{
											tree->getCurrent()->getMatrix()->
												setMarkText(x, y, moveStr);
											QChar c1 = moveStr[0];
											if (c1 == 'Z')
												moveStr = QString("a");
											else
												moveStr = c1.unicode() + 1;
										}
									}

//								new_node = false;

								if (compressed_list)
									// Advance pos by 3
									pos += 3;

								if((markType == markTerrWhite || markType == markTerrBlack) && !tree->getCurrent()->isTerritoryMarked())
									tree->getCurrent()->setTerritoryMarked();
							}

							//old_label = false;
							pos ++;
							while (toParse->at(pos).isSpace()) pos++;
						}
						break;

					case openMoves:
					{
						QString tmp_mv;
						while (toParse->at(++pos) != ']')
							tmp_mv += toParse->at(pos);
						tree->getCurrent()->setOpenMoves(tmp_mv.toInt());
						pos++;

						if (!tree->getCurrent()->getTimeinfo())
						{
							tree->getCurrent()->setTimeinfo(true);
							tree->getCurrent()->setTimeLeft(0);
						}
						break;
					}

					case timeLeft:
					{
						QString tmp_mv;
						while (toParse->at(++pos) != ']')
							tmp_mv += toParse->at(pos);
						tree->getCurrent()->setTimeLeft(tmp_mv.toFloat());
						pos++;

						if (!tree->getCurrent()->getTimeinfo())
						{
							tree->getCurrent()->setTimeinfo(true);
							tree->getCurrent()->setOpenMoves(0);
						}
						break;
					}

					case nextMove:
						if (toParse->at(++pos) == 'W')
							tree->getCurrent()->setPLinfo(stoneWhite);
						else if (toParse->at(pos) == 'B')
							tree->getCurrent()->setPLinfo(stoneBlack);

						pos += 2;
						break;

					default:
						break;
				}
		
				while (toParse->at(pos).isSpace())
			    		pos++;
        	
				sss= toParse->at(pos);

			} while (setup && toParse->at(pos) == '[');
			
//			tree->getCurrent()->getMatrix()->debug();
//			qDebug("end do loop");
//			qDebug(toParse->getStr());
			
			while (toParse->at(pos).isSpace())
				pos++;

		} while (toParse->at(pos) != ';' && toParse->at(pos) != '(' && toParse->at(pos) != ')' &&    static_cast<unsigned int>(pos) < strLength);
		
		// Advance pointer
		pointer = pos;
	
		break;
	
	default:
		delete toParse;
		return corruptSgf(pointer);
	}
	
	} while (pointer < strLength && pos >= 0);

	tree->setLoadingSGF(false);
	
	delete toParse;
	return !cancel;
}
Example #18
0
bool KArchiveDirectory::copyTo(const QString &dest, bool recursiveCopy) const
{
    QDir root;

    QList<const KArchiveFile *> fileList;
    QMap<qint64, QString> fileToDir;

    // placeholders for iterated items
    QStack<const KArchiveDirectory *> dirStack;
    QStack<QString> dirNameStack;

    dirStack.push(this);       // init stack at current directory
    dirNameStack.push(dest);   // ... with given path
    do {
        const KArchiveDirectory *curDir = dirStack.pop();
        const QString curDirName = dirNameStack.pop();
        if (!root.mkpath(curDirName)) {
            return false;
        }

        const QStringList dirEntries = curDir->entries();
        for (QStringList::const_iterator it = dirEntries.begin(); it != dirEntries.end(); ++it) {
            const KArchiveEntry *curEntry = curDir->entry(*it);
            if (!curEntry->symLinkTarget().isEmpty()) {
                QString linkName = curDirName + QLatin1Char('/') + curEntry->name();
                // To create a valid link on Windows, linkName must have a .lnk file extension.
#ifdef Q_OS_WIN
                if (!linkName.endsWith(QStringLiteral(".lnk"))) {
                    linkName += QStringLiteral(".lnk");
                }
#endif
                QFile symLinkTarget(curEntry->symLinkTarget());
                if (!symLinkTarget.link(linkName)) {
                    //qDebug() << "symlink(" << curEntry->symLinkTarget() << ',' << linkName << ") failed:" << strerror(errno);
                }
            } else {
                if (curEntry->isFile()) {
                    const KArchiveFile *curFile = dynamic_cast<const KArchiveFile *>(curEntry);
                    if (curFile) {
                        fileList.append(curFile);
                        fileToDir.insert(curFile->position(), curDirName);
                    }
                }

                if (curEntry->isDirectory() && recursiveCopy) {
                    const KArchiveDirectory *ad = dynamic_cast<const KArchiveDirectory *>(curEntry);
                    if (ad) {
                        dirStack.push(ad);
                        dirNameStack.push(curDirName + QLatin1Char('/') + curEntry->name());
                    }
                }
            }
        }
    } while (!dirStack.isEmpty());

    qSort(fileList.begin(), fileList.end(), sortByPosition);    // sort on d->pos, so we have a linear access

    for (QList<const KArchiveFile *>::const_iterator it = fileList.constBegin(), end = fileList.constEnd();
            it != end; ++it) {
        const KArchiveFile *f = *it;
        qint64 pos = f->position();
        if (!f->copyTo(fileToDir[pos])) {
            return false;
        }
    }
    return true;
}
Example #19
0
void Highlighter::iterateThroughRules(const QString &text,
                                      const int length,
                                      ProgressData *progress,
                                      const bool childRule,
                                      const QList<QSharedPointer<Rule> > &rules)
{
    typedef QList<QSharedPointer<Rule> >::const_iterator RuleIterator;

    bool contextChanged = false;
    bool atLeastOneMatch = false;

    RuleIterator it = rules.begin();
    RuleIterator endIt = rules.end();
    while (it != endIt && progress->offset() < length) {
        int startOffset = progress->offset();
        const QSharedPointer<Rule> &rule = *it;
        if (rule->matchSucceed(text, length, progress)) {
            atLeastOneMatch = true;

            if (!m_indentationBasedFolding) {
                if (!rule->beginRegion().isEmpty()) {
                    blockData(currentBlockUserData())->m_foldingRegions.push(rule->beginRegion());
                    ++m_regionDepth;
                    if (progress->isOpeningBraceMatchAtFirstNonSpace())
                        ++blockData(currentBlockUserData())->m_foldingIndentDelta;
                }
                if (!rule->endRegion().isEmpty()) {
                    QStack<QString> *currentRegions =
                        &blockData(currentBlockUserData())->m_foldingRegions;
                    if (!currentRegions->isEmpty() && rule->endRegion() == currentRegions->top()) {
                        currentRegions->pop();
                        --m_regionDepth;
                        if (progress->isClosingBraceMatchAtNonEnd())
                            --blockData(currentBlockUserData())->m_foldingIndentDelta;
                    }
                }
                progress->clearBracesMatches();
            }

            if (progress->isWillContinueLine()) {
                createWillContinueBlock();
                progress->setWillContinueLine(false);
            } else {
                if (rule->hasChildren())
                    iterateThroughRules(text, length, progress, true, rule->children());

                if (!rule->context().isEmpty() && contextChangeRequired(rule->context())) {
                    m_currentCaptures = progress->captures();
                    changeContext(rule->context(), rule->definition());
                    contextChanged = true;
                }
            }

            // Format is not applied to child rules directly (but relative to the offset of their
            // parent) nor to look ahead rules.
            if (!childRule && !rule->isLookAhead()) {
                if (rule->itemData().isEmpty())
                    applyFormat(startOffset, progress->offset() - startOffset,
                                m_currentContext->itemData(), m_currentContext->definition());
                else
                    applyFormat(startOffset, progress->offset() - startOffset, rule->itemData(),
                                rule->definition());
            }

            // When there is a match of one child rule the others should be skipped. Otherwise
            // the highlighting would be incorret in a case like 9ULLLULLLUULLULLUL, for example.
            if (contextChanged || childRule) {
                break;
            } else {
                it = rules.begin();
                continue;
            }
        }
        ++it;
    }

    if (!childRule && !atLeastOneMatch) {
        if (m_currentContext->isFallthrough()) {
            handleContextChange(m_currentContext->fallthroughContext(),
                                m_currentContext->definition());
            iterateThroughRules(text, length, progress, false, m_currentContext->rules());
        } else {
            applyFormat(progress->offset(), 1, m_currentContext->itemData(),
                        m_currentContext->definition());
            if (progress->isOnlySpacesSoFar() && !text.at(progress->offset()).isSpace())
                progress->setOnlySpacesSoFar(false);
            progress->incrementOffset();
        }
    }
}
TableFieldBinaryTreeEvalNode* TableFieldBinaryTreeEvalNode::buildTree(QList<TableFieldEvalNode *>& list, QObject *parent)
{
  if (list.isEmpty())
  {
      return nullptr;
  }

  // Build a new list that is surrounded with parenthesis.
  QList<TableFieldEvalNode *> safeList;
  TableFieldEvalNode leftParenEvalNode(TableFieldEvalNode::L_PAREN);
  TableFieldEvalNode rightParenEvalNode(TableFieldEvalNode::R_PAREN);
  TableFieldBinaryTreeEvalNode* headNode = new TableFieldBinaryTreeEvalNode(parent);

  safeList.append(&leftParenEvalNode);
  safeList.append(list);
  safeList.append(&rightParenEvalNode);

  bool isError = false;
  QStack<TableFieldBinaryTreeEvalNode*> values;
  QStack<TableFieldBinaryTreeEvalNode*> operators;

  QListIterator<TableFieldEvalNode*> i(safeList);
  while (i.hasNext() && !isError)
  {
      TableFieldEvalNode* eNode = i.next();
      if (eNode == nullptr)
      {
        qDebug(qPrintable(tr("Cannot build a tree from null nodes.")));
        isError = true;
      }
      else if (eNode->isValue())
      {
          // Push value nodes on the value stack.
          TableFieldBinaryTreeEvalNode* bNode = new TableFieldBinaryTreeEvalNode(headNode);
          bNode->setNode(eNode->clone(bNode));
          values.push(bNode);
      }
      else if (eNode->isLeftParen())
      {
          // Push left parenthesis onto the operator stack.
          // Will be removed when a right parenthesis is found.
          TableFieldBinaryTreeEvalNode* bNode = new TableFieldBinaryTreeEvalNode(headNode);
          bNode->setNode(eNode->clone(bNode));
          operators.push(bNode);
      }
      else if (eNode->isRightParen())
      {
          // Found a right parenthesis.
          // Process all operators until a left parenthesis is found then get rid of it.
          while (!isError && !operators.isEmpty() && !operators.top()->isLeftParen())
        {
          isError = processOneTreeLevel(values, operators);
        }
        if (!isError)
        {
          if (operators.isEmpty())
          {
            qDebug(qPrintable(tr("Have a ')' without a '('")));
            isError = true;
          }
          else
          {
            // Dispose of the open parenthesis.
            TableFieldBinaryTreeEvalNode* opNode = operators.pop();
            delete opNode;
          }
        }
      }
      else if (eNode->isNoType())
      {
          qDebug(qPrintable(tr("Cannot build a tree from raw nodes with no type")));
          isError = true;
      }
      else
      {
          // Found an operator.
          // Process all operators whose priority / precidence is the same or greater than this one.
          // So, after reading "a OR b OR", you know you can set "a OR b", but you don't know yet if you can
          // process the second OR.
        while (!isError && !operators.isEmpty() && !operators.top()->isLeftParen() && operators.top()->nodePriority() >= eNode->nodePriority())
        {
            isError = processOneTreeLevel(values, operators);
        }
        if (!isError)
        {
            // No error, so push the operator onto the operator stack.
            TableFieldBinaryTreeEvalNode* bNode = new TableFieldBinaryTreeEvalNode(headNode);
            bNode->setNode(eNode->clone(bNode));
            operators.push(bNode);
        }
      }
  }

  if (!isError)
  {
    if (!operators.isEmpty())
    {
      isError = true;
      qDebug(qPrintable(tr("Unprocessed Operators left in the stack after processing")));
    }
    else if (values.size() != 1)
    {
      isError = true;
      qDebug(qPrintable(tr("There should be only one value left after processing, not %1").arg(values.size())));
    }
    else
    {
        // tree parent node should already be null.
        // Perform a shallow copy of the top node into the head node.
        TableFieldBinaryTreeEvalNode* topNode = values.top();

        // Clone the node so that the parent / owner is properly set.
        headNode->m_node = topNode->m_node->clone(headNode);
        for (int i=0; i<topNode->m_children.size(); ++i)
        {
            headNode->addChild(topNode->m_children.at(i));
        }

        delete topNode;
        return headNode;
    }
  }
  if (isError)
  {
      // All of the created nodes are a child of the head node.
      delete headNode;
  }
  return nullptr;
}
Example #21
0
QVector<QVector<QString> > Structure::Graph::findCycleBase()
{
	QMap<QString, QSet<QString>> used;
	QMap<QString, QString> parent;
	QStack<QString> stack;
	QVector<QVector<QString>> cycles;

	for (Node* root_node : nodes) {
		QString root = root_node->mID;
		// Loop over the connected
		// components of the graph.
		if (parent.contains(root)) {
			continue;
		}
		// Free some memory in case of
		// multiple connected components.
		used.clear();
		// Prepare to walk the spanning tree.
		parent[root] = root;
		used[root] = QSet<QString>();
		stack.push(root);
		// Do the walk. It is a BFS with
		// a LIFO instead of the usual
		// FIFO. Thus it is easier to 
		// find the cycles in the tree.
		while (!stack.isEmpty()) {
			QString current = stack.pop();
			QSet<QString> currentUsed = used[current];
			for (Link* e : getLinks(current)) {
				QString neighbor = e->getNodeOther(current)->mID;
				if (!used.contains(neighbor)) {
					// found a new node
					parent[neighbor] = current;
					QSet<QString> neighbourUsed;
					neighbourUsed << current;
					used[neighbor] = neighbourUsed;
					stack.push(neighbor);
				}
				else if (neighbor == current) {
					// found a self loop
					QVector<QString> cycle;
					cycle << current;
					cycles << cycle;
				}
				else if (!currentUsed.contains(neighbor)) {
					// found a cycle
					QSet<QString>& neighbourUsed = used[neighbor];
					QVector<QString> cycle;
					cycle << neighbor;
					cycle << current;
					QString p = parent[current];
					while (!neighbourUsed.contains(p)) {
						cycle << p;
						p = parent[p];
					}
					cycle << p;
					cycles << cycle;
					neighbourUsed << current;
				}
			}
		}
	}
	return cycles;
}
bool TableFieldBinaryTreeEvalNode::processOneTreeLevel(QStack<TableFieldBinaryTreeEvalNode*>& values, QStack<TableFieldBinaryTreeEvalNode*>& operators)
{
  if (operators.isEmpty())
  {
    qDebug(qPrintable(tr("Operator stack is prematurely empty")));
    return true;
  }
  TableFieldBinaryTreeEvalNode* opNode = operators.pop();
  //qDebug(qPrintable(tr("processOneTreeLevel Op Node value(%1) type(%2) priority(%3)").arg(opNode->nodeValue()).arg(opNode->nodeType()).arg(opNode->nodePriority())));
  if (opNode->m_node->isInfix())
  {
    // Two operands
    if (values.size() < 2)
    {
        qDebug(qPrintable(tr("Found an INFIX operator that requires two values, and have %1 value(s).").arg(values.size())));
        return true;
    }
    else
    {
        TableFieldBinaryTreeEvalNode* child2 = values.pop();
        TableFieldBinaryTreeEvalNode* child1 = values.pop();
        if (child1->nodeType() == opNode->nodeType())
        {
            // First child has the same operator type,
            // So, we can use a single node (faster processing and fewer nodes).
            if (child2->nodeType() == opNode->nodeType())
            {
                // So does child 2, so copy the children.
                for (int i=0; i<child2->m_children.size(); ++i)
                {
                    child1->addChild(child2->m_children.at(i));
                }
                delete child2;
            }
            else
            {
                child1->addChild(child2);
                values.push(child1);
            }
            delete opNode;
        }
        else if (child2->nodeType() == opNode->nodeType())
        {
            // Make child1 the first child of child two.
            child2->m_children.insert(0, child1);
            child1->setTreeParent(child2);
            delete opNode;
        }
        else
        {
            opNode->addChild(child1);
            opNode->addChild(child2);
            values.push(opNode);
        }
    }
  }
  else if (opNode->m_node->isSuffixOrPrefix())
  {
      // Need one value.
      if (values.isEmpty())
      {
          qDebug(qPrintable(tr("Found a PREFIX or SUFFIX operator with an empty value list.")));
          return true;
      }
      else
      {
          TableFieldBinaryTreeEvalNode* child1 = values.pop();
          // I suppose if the value is boolean...
          if (child1->isValue())
          {
            qDebug(qPrintable(tr("Cannot take the NOT of a value.")));
            return true;
          }
          // make the value a child of the NOT operator and push the NOT operator
          // into the values stack.
          opNode->addChild(child1);
          values.push(opNode);
      }
  }
  else
  {
      qDebug(qPrintable(tr("Found an operator node with an unknown type.")));
      return true;
  }
  return false;
}
Example #23
0
void GameRule::onPhaseChange(ServerPlayer *player) const{
    Room *room = player->getRoom();
    switch(player->getPhase()){
    case Player::Start: {
            player->setMark("SlashCount", 0);
            break;
        }
    case Player::Judge: {
            QStack<const DelayedTrick *> tricks = player->delayedTricks();
            while(!tricks.isEmpty() && player->isAlive()){
                const DelayedTrick *trick = tricks.pop();
                bool on_effect = room->cardEffect(trick, NULL, player);
                if(!on_effect)
                    trick->onNullified(player);
            }

            break;
        }
    case Player::Draw: {
            QVariant num = 2;
            room->getThread()->trigger(DrawNCards, player, num);
            int n = num.toInt();
            if(n > 0)
                player->drawCards(n, false);
            break;
        }

    case Player::Play: {
            while(player->isAlive()){
                CardUseStruct card_use;
                room->activate(player, card_use);
                if(card_use.isValid())
                    room->useCard(card_use);
                else
                    break;
            }
            break;
        }

    case Player::Discard:{
            int discard_num = player->getHandcardNum() - player->getMaxCards();
            if(player->hasFlag("jilei")){
                QList<const Card *> jilei_cards;
                QList<const Card *> handcards = player->getHandcards();
                foreach(const Card *card, handcards){
                    if(card->inherits("BasicCard")){
                        if(player->hasFlag("jileiB"))
                            jilei_cards << card;
                    }else if(card->inherits("EquipCard")){
                        if(player->hasFlag("jileiE"))
                            jilei_cards << card;
                    }else if(card->inherits("TrickCard")){
                        if(player->hasFlag("jileiT"))
                            jilei_cards << card;
                    }
                }

                if(jilei_cards.length() > player->getMaxCards()){
                    // show all his cards
                    QStringList handcards_str;
                    foreach(const Card *card, handcards)
                        handcards_str << QString::number(card->getId());
                    QString gongxin_str = QString("%1!:%2").arg(player->objectName()).arg(handcards_str.join("+"));
                    room->broadcastInvoke("doGongxin", gongxin_str, player);

                    QList<const Card *> other_cards = handcards.toSet().subtract(jilei_cards.toSet()).toList();
                    foreach(const Card *card, other_cards){
                        room->throwCard(card);
                    }

                    return;
                }
            }
Example #24
0
void DebugTreeModel::stop(){

    if( _stopped ) return;

    _stopped=true;

    QStandardItem *root=invisibleRootItem();

    //build callstack...
    //
    DebugItem *func=0;
    int n_funcs=0,n_vars=0;

    QStack<DebugItem*> objs;

    for(;;){

        QString text=_proc->readLine( 1 );
        if( text.isEmpty() ) break;

        if( text.startsWith( "+" ) ){
            if( func ) func->setRowCount( n_vars );
            func=dynamic_cast<DebugItem*>( root->child( n_funcs++ ) );
            if( !func ){
                func=new DebugItem;
                root->appendRow( func );
            }
            func->update( text );
            n_vars=0;
        }else if( func ){
            DebugItem *item=dynamic_cast<DebugItem*>( func->child( n_vars++ ) );
            if( !item ){
                item=new DebugItem;
                func->appendRow( item );
            }
            item->update( text );

            if( item->type()==3 && item->address()!=0 && item->expanded() ){
                objs.push( item );
            }else{
                item->setRowCount(0);
            }
        }
    }

    if( func ) func->setRowCount( n_vars );

    root->setRowCount( n_funcs );

    while( !objs.isEmpty() ){

        DebugItem *item=objs.pop();

        _proc->writeLine( QString("@")+QString::number( (qulonglong)item->address(),16 ) );

        int n_vars=0;

        for(;;){

            QString text=_proc->readLine( 1 );
            if( text.isEmpty() ) break;

            DebugItem *child=dynamic_cast<DebugItem*>( item->child( n_vars++ ) );
            if( !child ){
                child=new DebugItem;
                item->appendRow( child );
            }

            child->update( text );

            if( child->type()==2 && child->address()!=0 && child->expanded() ){
                objs.push( child );
            }else{
                child->setRowCount(0);
            }
        }
        item->setRowCount( n_vars );
    }
}
Example #25
0
bool PreprocessContext::process(const QString &in, QString *out, QString *errorMessage)
{
    out->clear();
    if (in.isEmpty())
        return true;

    out->reserve(in.size());
    reset();

    const QChar newLine = QLatin1Char('\n');
    const QStringList lines = in.split(newLine, QString::KeepEmptyParts);
    const int lineCount = lines.size();
    bool first = true;
    for (int l = 0; l < lineCount; l++) {
        // Check for element of the stack (be it dummy, else something is wrong).
        if (m_sectionStack.isEmpty()) {
            if (errorMessage)
                *errorMessage = msgEmptyStack(l);
            return false;
        }
        QString expression;
        bool expressionValue = false;
        PreprocessStackEntry &top = m_sectionStack.back();

        switch (preprocessorLine(lines.at(l), &expression)) {
        case IfSection:
            // '@If': Push new section
            if (top.condition) {
                if (!TemplateEngine::evaluateBooleanJavaScriptExpression(m_scriptEngine, expression,
                                                                         &expressionValue, errorMessage)) {
                    if (errorMessage)
                        *errorMessage = QString::fromLatin1("Error in @if at %1: %2")
                            .arg(l + 1).arg(*errorMessage);
                    return false;
                }
            }
            m_sectionStack.push(PreprocessStackEntry(IfSection,
                                                     top.condition, expressionValue, expressionValue));
            break;
        case ElsifSection: // '@elsif': Check condition.
            if (top.section != IfSection && top.section != ElsifSection) {
                if (errorMessage)
                    *errorMessage = QString::fromLatin1("No preceding @if found for @elsif at %1")
                        .arg(l + 1);
                return false;
            }
            if (top.parentEnabled) {
                if (!TemplateEngine::evaluateBooleanJavaScriptExpression(m_scriptEngine, expression,
                                                                         &expressionValue, errorMessage)) {
                    if (errorMessage)
                        *errorMessage = QString::fromLatin1("Error in @elsif at %1: %2")
                            .arg(l + 1).arg(*errorMessage);
                    return false;
                }
            }
            top.section = ElsifSection;
            // ignore consecutive '@elsifs' once something matched
            if (top.anyIfClauseMatched) {
                top.condition = false;
            } else {
                if ( (top.condition = expressionValue) )
                    top.anyIfClauseMatched = true;
            }
            break;
        case ElseSection: // '@else': Check condition.
            if (top.section != IfSection && top.section != ElsifSection) {
                if (errorMessage)
                    *errorMessage = QString::fromLatin1("No preceding @if/@elsif found for @else at %1")
                        .arg(l + 1);
                return false;
            }
            expressionValue = top.parentEnabled && !top.anyIfClauseMatched;
            top.section = ElseSection;
            top.condition = expressionValue;
            break;
        case EndifSection: // '@endif': Discard section.
            m_sectionStack.pop();
            break;
        case OtherSection: // Rest: Append according to current condition.
            if (top.condition) {
                if (first)
                    first = false;
                else
                    out->append(newLine);
                out->append(lines.at(l));
            }
            break;
        } // switch section

    } // for lines
    return true;
}
Example #26
0
static void parse( Translator *tor )
{
    QString text;
    QString com;
    QString extracomment;

    yyCh = getChar();

    yyTok = getToken();
    while ( yyTok != Tok_Eof ) {
        switch ( yyTok ) {
        case Tok_class:
            yyTok = getToken();
            if(yyTok == Tok_Ident) {
                yyScope.push(new Scope(yyIdent, Scope::Clazz, yyLineNo));
            }
            else {
                yyMsg() << qPrintable(LU::tr("'class' must be followed by a class name.\n"));
                break;
            }
            while (!match(Tok_LeftBrace)) {
                yyTok = getToken();
            }
            break;

        case Tok_tr:
            yyTok = getToken();
            if ( match(Tok_LeftParen) && matchString(text) ) {
                com.clear();
                bool plural = false;

                if ( match(Tok_RightParen) ) {
                    // no comment
                } else if (match(Tok_Comma) && matchStringOrNull(com)) {   //comment
                    if ( match(Tok_RightParen)) {
                        // ok,
                    } else if (match(Tok_Comma)) {
                        plural = true;
                    }
                }
                if (!text.isEmpty())
                    recordMessage(tor, context(), text, com, extracomment, plural);
            }
            break;
        case Tok_translate:
            {
                QString contextOverride;
                yyTok = getToken();
                if ( match(Tok_LeftParen) &&
                     matchString(contextOverride) &&
                     match(Tok_Comma) &&
                     matchString(text) ) {

                    com.clear();
                    bool plural = false;
                    if (!match(Tok_RightParen)) {
                        // look for comment
                        if ( match(Tok_Comma) && matchStringOrNull(com)) {
                            if (!match(Tok_RightParen)) {
                                if (match(Tok_Comma) && matchExpression() && match(Tok_RightParen)) {
                                    plural = true;
                                } else {
                                    break;
                                }
                            }
                        } else {
                            break;
                        }
                    }
                    if (!text.isEmpty())
                        recordMessage(tor, contextOverride, text, com, extracomment, plural);
                }
            }
            break;

        case Tok_Ident:
            yyTok = getToken();
            break;

        case Tok_Comment:
            if (yyComment.startsWith(QLatin1Char(':'))) {
                yyComment.remove(0, 1);
                extracomment.append(yyComment);
            }
            yyTok = getToken();
            break;

        case Tok_RightBrace:
            if ( yyScope.isEmpty() ) {
                yyMsg() << qPrintable(LU::tr("Excess closing brace.\n"));
            }
            else
                delete (yyScope.pop());
            extracomment.clear();
            yyTok = getToken();
            break;

         case Tok_LeftBrace:
            yyScope.push(new Scope(QString(), Scope::Other, yyLineNo));
            yyTok = getToken();
            break;

        case Tok_Semicolon:
            extracomment.clear();
            yyTok = getToken();
            break;

        case Tok_Package:
            yyTok = getToken();
            while(!match(Tok_Semicolon)) {
                switch(yyTok) {
                    case Tok_Ident:
                        yyPackage.append(yyIdent);
                        break;
                    case Tok_Dot:
                        yyPackage.append(QLatin1String("."));
                        break;
                    default:
                         yyMsg() << qPrintable(LU::tr("'package' must be followed by package name.\n"));
                         break;
                }
                yyTok = getToken();
            }
            break;

        default:
            yyTok = getToken();
        }
    }

    if ( !yyScope.isEmpty() )
        yyMsg(yyScope.top()->line) << qPrintable(LU::tr("Unbalanced opening brace.\n"));
    else if ( yyParenDepth != 0 )
        yyMsg(yyParenLineNo) << qPrintable(LU::tr("Unbalanced opening parenthesis.\n"));
}
bool QQuickStyledTextPrivate::parseCloseTag(const QChar *&ch, const QString &textIn, QString &textOut)
{
    skipSpace(ch);

    int tagStart = ch - textIn.constData();
    int tagLength = 0;
    while (!ch->isNull()) {
        if (*ch == greaterThan) {
            if (tagLength == 0)
                return false;
            QStringRef tag(&textIn, tagStart, tagLength);
            const QChar char0 = tag.at(0);
            hasNewLine = false;
            if (char0 == QLatin1Char('b')) {
                if (tagLength == 1)
                    return true;
                else if (tag.at(1) == QLatin1Char('r') && tagLength == 2)
                    return false;
            } else if (char0 == QLatin1Char('i')) {
                if (tagLength == 1)
                    return true;
            } else if (char0 == QLatin1Char('a')) {
                if (tagLength == 1)
                    return true;
            } else if (char0 == QLatin1Char('p')) {
                if (tagLength == 1) {
                    textOut.append(QChar::LineSeparator);
                    hasNewLine = true;
                    hasSpace = true;
                    return false;
                } else if (tag == QLatin1String("pre")) {
                    preFormat = false;
                    if (!hasNewLine)
                        textOut.append(QChar::LineSeparator);
                    hasNewLine = true;
                    hasSpace = true;
                    return true;
                }
            } else if (char0 == QLatin1Char('u')) {
                if (tagLength == 1)
                    return true;
                else if (tag == QLatin1String("ul")) {
                    if (!listStack.isEmpty()) {
                        listStack.pop();
                        if (!listStack.count())
                            textOut.append(QChar::LineSeparator);
                    }
                    return false;
                }
            } else if (char0 == QLatin1Char('h') && tagLength == 2) {
                textOut.append(QChar::LineSeparator);
                hasNewLine = true;
                hasSpace = true;
                return true;
            } else if (tag == QLatin1String("font")) {
                return true;
            } else if (tag == QLatin1String("strong")) {
                return true;
            } else if (tag == QLatin1String("ol")) {
                if (!listStack.isEmpty()) {
                    listStack.pop();
                    if (!listStack.count())
                        textOut.append(QChar::LineSeparator);
                }
                return false;
            } else if (tag == QLatin1String("li")) {
                return false;
            }
            return false;
        } else if (!ch->isSpace()){
            tagLength++;
        }
        ++ch;
    }

    return false;
}
Example #28
0
void TraceLoader::parseTrace()
{
    QList<ApiTraceFrame*> frames;
    ApiTraceFrame *currentFrame = 0;
    int frameCount = 0;
    QStack<ApiTraceCall*> groups;
    QVector<ApiTraceCall*> topLevelItems;
    QVector<ApiTraceCall*> allCalls;
    quint64 binaryDataSize = 0;

    int lastPercentReport = 0;

    trace::Call *call = m_parser.parse_call();
    while (call) {
        //std::cout << *call;
        if (!currentFrame) {
            currentFrame = new ApiTraceFrame();
            currentFrame->number = frameCount;
            ++frameCount;
        }
        ApiTraceCall *apiCall =
            apiCallFromTraceCall(call, m_helpHash, currentFrame, groups.isEmpty() ? 0 : groups.top(), this);
        allCalls.append(apiCall);
        if (groups.count() == 0) {
            topLevelItems.append(apiCall);
        }
        if (call->flags & trace::CALL_FLAG_MARKER_PUSH) {
            groups.push(apiCall);
        } else if (call->flags & trace::CALL_FLAG_MARKER_POP) {
            groups.top()->finishedAddingChildren();
            groups.pop();
        }
        if (!groups.isEmpty()) {
            groups.top()->addChild(apiCall);
        }
        if (apiCall->hasBinaryData()) {
            QByteArray data =
                apiCall->arguments()[apiCall->binaryDataIndex()].toByteArray();
            binaryDataSize += data.size();
        }
        if (call->flags & trace::CALL_FLAG_END_FRAME) {
            allCalls.squeeze();
            topLevelItems.squeeze();
            if (topLevelItems.count() == allCalls.count()) {
                currentFrame->setCalls(allCalls, allCalls, binaryDataSize);
            } else {
                currentFrame->setCalls(topLevelItems, allCalls, binaryDataSize);
            }
            allCalls.clear();
            groups.clear();
            topLevelItems.clear();
            frames.append(currentFrame);
            currentFrame = 0;
            binaryDataSize = 0;
            if (frames.count() >= FRAMES_TO_CACHE) {
                emit framesLoaded(frames);
                frames.clear();
            }
            if (m_parser.percentRead() - lastPercentReport >= 5) {
                emit parsed(m_parser.percentRead());
                lastPercentReport = m_parser.percentRead();
            }
        }
        delete call;
        call = m_parser.parse_call();
    }

    //last frames won't have markers
    //  it's just a bunch of Delete calls for every object
    //  after the last SwapBuffers
    if (currentFrame) {
        allCalls.squeeze();
        if (topLevelItems.count() == allCalls.count()) {
            currentFrame->setCalls(allCalls, allCalls, binaryDataSize);
        } else {
            currentFrame->setCalls(topLevelItems, allCalls, binaryDataSize);
        }
        frames.append(currentFrame);
        currentFrame = 0;
    }
    if (frames.count()) {
        emit framesLoaded(frames);
    }
}