コード例 #1
0
ファイル: typeparser.cpp プロジェクト: FrankLIKE/qtd
TypeParser::Info TypeParser::parse(const QString &str)
{
    Scanner scanner(str);

    Info info;
    QStack<Info *> stack;
    stack.push(&info);

    bool colon_prefix = false;
    bool in_array = false;
    QString array;

    Scanner::Token tok = scanner.nextToken();
    while (tok != Scanner::NoToken) {

//         switch (tok) {
//         case Scanner::StarToken: printf(" - *\n"); break;
//         case Scanner::AmpersandToken: printf(" - &\n"); break;
//         case Scanner::LessThanToken: printf(" - <\n"); break;
//         case Scanner::GreaterThanToken: printf(" - >\n"); break;
//         case Scanner::ColonToken: printf(" - ::\n"); break;
//         case Scanner::CommaToken: printf(" - ,\n"); break;
//         case Scanner::ConstToken: printf(" - const\n"); break;
//         case Scanner::SquareBegin: printf(" - [\n"); break;
//         case Scanner::SquareEnd: printf(" - ]\n"); break;
//         case Scanner::Identifier: printf(" - '%s'\n", qPrintable(scanner.identifier())); break;
//         default:
//             break;
//         }

        switch (tok) {

        case Scanner::StarToken:
            ++stack.top()->indirections;
            break;

        case Scanner::AmpersandToken:
            stack.top()->is_reference = true;
            break;

        case Scanner::LessThanToken:
            stack.top()->template_instantiations << Info();
            stack.push(&stack.top()->template_instantiations.last());
            break;

        case Scanner::CommaToken:
            stack.pop();
            stack.top()->template_instantiations << Info();
            stack.push(&stack.top()->template_instantiations.last());
            break;

        case Scanner::GreaterThanToken:
            stack.pop();
            break;

        case Scanner::ColonToken:
            colon_prefix = true;
            break;

        case Scanner::ConstToken:
            stack.top()->is_constant = true;
            break;

        case Scanner::OpenParenToken: // function pointers not supported
        case Scanner::CloseParenToken:
            {
                Info i;
                i.is_busted = true;
                return i;
            }


        case Scanner::Identifier:
            if (in_array) {
                array = scanner.identifier();
            } else if (colon_prefix || stack.top()->qualified_name.isEmpty()) {
                stack.top()->qualified_name << scanner.identifier();
                colon_prefix = false;
            } else {
                stack.top()->qualified_name.last().append(" " + scanner.identifier());
            }
            break;

        case Scanner::SquareBegin:
            in_array = true;
            break;

        case Scanner::SquareEnd:
            in_array = false;
            stack.top()->arrays += array;
            break;


        default:
            break;
        }

        tok = scanner.nextToken();
    }

    return info;
}
コード例 #2
0
ファイル: flattextarea.cpp プロジェクト: neuroidss/tdesktop
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();
    }
}
コード例 #3
0
void QtVideoSinkDelegate::changePainter(const BufferFormat & format)
{
    if (m_painter) {
        m_painter->cleanup();
        if (G_UNLIKELY(!m_painter->supportsFormat(format.videoFormat()))) {
            destroyPainter();
        }
    }

    QStack<PainterType> possiblePainters;
    if (GenericSurfacePainter::supportedPixelFormats().contains(format.videoFormat())) {
        possiblePainters.push(Generic);
    }

#ifndef GST_QT_VIDEO_SINK_NO_OPENGL
    if (OpenGLSurfacePainter::supportedPixelFormats().contains(format.videoFormat())) {
        if (m_supportedPainters & ArbFp) {
            possiblePainters.push(ArbFp);
        }

        if (m_supportedPainters & Glsl) {
            possiblePainters.push(Glsl);
        }
    }
#endif

    while (!possiblePainters.isEmpty()) {
        if (!m_painter) {
            PainterType type = possiblePainters.pop();
            switch(type) {
#ifndef GST_QT_VIDEO_SINK_NO_OPENGL
            case Glsl:
                GST_LOG_OBJECT(m_sink, "Creating GLSL painter");
                m_painter = new GlslSurfacePainter;
                break;
# ifndef QT_OPENGL_ES
            case ArbFp:
                GST_LOG_OBJECT(m_sink, "Creating ARB Fragment Shader painter");
                m_painter = new ArbFpSurfacePainter;
                break;
# endif
#endif
            case Generic:
                GST_LOG_OBJECT(m_sink, "Creating Generic painter");
                m_painter = new GenericSurfacePainter;
                break;
            default:
                Q_ASSERT(false);
            }
        }

        try {
            m_painter->init(format);
            return;
        } catch (const QString & error) {
            GST_ELEMENT_WARNING(m_sink, RESOURCE, FAILED,
                    ("Failed to start painter"), ("%s", error.toUtf8().constData()));
            delete m_painter;
            m_painter = 0;
        }
    }

    GST_ELEMENT_ERROR(m_sink, RESOURCE, FAILED,
            ("Failed to create a painter for the given format"), (NULL));
}
コード例 #4
0
ファイル: qmimetypeparser.cpp プロジェクト: G-shadow/trojita
bool QMimeTypeParserBase::parse(QIODevice *dev, const QString &fileName, QString *errorMessage)
{
    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;
}
コード例 #5
0
ファイル: pTreeComboBox.cpp プロジェクト: pasnox/fresh
void pTreeComboBox::calculPopupGeometry()
{
    if ( !mView ) {
        return;
    }
    
    QStyle * const style = this->style();

    // set current item and select it
    view()->selectionModel()->setCurrentIndex( mCurrentIndex, QItemSelectionModel::ClearAndSelect | QItemSelectionModel::Rows );
    QFrame* container = mFrame;
    QStyleOptionComboBox opt;
    initStyleOption( &opt );
    QRect listRect( style->subControlRect( QStyle::CC_ComboBox, &opt, QStyle::SC_ComboBoxListBoxPopup, this ) );
    QRect screen = popupGeometry( QApplication::desktop()->screenNumber( this ) );
    QPoint below = mapToGlobal( listRect.bottomLeft() );
    int belowHeight = screen.bottom() -below.y();
    QPoint above = mapToGlobal( listRect.topLeft() );
    int aboveHeight = above.y() -screen.y();
    bool boundToScreen = !window()->testAttribute( Qt::WA_DontShowOnScreen );
    
    listRect.moveTopLeft( mapToGlobal( rect().bottomLeft() ) );
    listRect.setSize( QSize( 
        qMax( qMax( view()->viewport()->width(), mFrame->width() ), width() )
        ,
        qMax( view()->viewport()->height(), mFrame->height() )
    ) );

    const bool usePopup = style->styleHint( QStyle::SH_ComboBox_Popup, &opt, this );
    {
        int listHeight = 0;
        int count = 0;
        QStack<QModelIndex> toCheck;
        toCheck.push( view()->rootIndex() );
#ifndef QT_NO_TREEVIEW
        QTreeView* treeView = qobject_cast<QTreeView*>( view() );
        if ( treeView && treeView->header() && !treeView->header()->isHidden() )
            listHeight += treeView->header()->height();
#endif
        while ( !toCheck.isEmpty() ) {
            QModelIndex parent = toCheck.pop();
            for ( int i = 0; i < model()->rowCount( parent ); ++i ) {
                QModelIndex idx = model()->index( i, mModelColumn, parent );
                if ( !idx.isValid() )
                    continue;
                listHeight += view()->visualRect( idx ).height();
#ifndef QT_NO_TREEVIEW
                if ( model()->hasChildren( idx ) && treeView && treeView->isExpanded( idx ) )
                    toCheck.push( idx );
#endif
                ++count;
                if ( !usePopup && count > mMaxVisibleItems ) {
                    toCheck.clear();
                    break;
                }
            }
        }
        listRect.setHeight( listHeight );
    }

    {
        // add the spacing for the grid on the top and the bottom;
        int heightMargin = 0;

        // add the frame of the container
        int marginTop, marginBottom;
        container->getContentsMargins( 0, &marginTop, 0, &marginBottom );
        heightMargin += marginTop +marginBottom;

        //add the frame of the view
        view()->getContentsMargins( 0, &marginTop, 0, &marginBottom );
        marginTop += 0/*static_cast<QAbstractScrollAreaPrivate *>(QObjectPrivate::get(view()))->top*/;
        marginBottom += 0/*static_cast<QAbstractScrollAreaPrivate *>(QObjectPrivate::get(view()))->bottom*/;
        heightMargin += marginTop +marginBottom;

        listRect.setHeight( listRect.height() +heightMargin );
    }

    // Add space for margin at top and bottom if the style wants it.
    if ( usePopup )
        listRect.setHeight( listRect.height() +style->pixelMetric( QStyle::PM_MenuVMargin, &opt, this ) *2 );

    // Make sure the popup is wide enough to display its contents.
    if ( usePopup ) {
        const int diff = sizeHint().width() /*d->computeWidthHint()*/ -width();
        if ( diff > 0 )
            listRect.setWidth( listRect.width() +diff );
    }

    //we need to activate the layout to make sure the min/maximum size are set when the widget was not yet show
    container->layout()->activate();
    //takes account of the minimum/maximum size of the container
    listRect.setSize( listRect.size().expandedTo(container->minimumSize())
                      .boundedTo(container->maximumSize()));

    // make sure the widget fits on screen
    if (boundToScreen) {
        if (listRect.width() > screen.width() )
            listRect.setWidth(screen.width());
        if (/*mapToGlobal(*/listRect/*.bottomRight())*/.x() > screen.right()) {
            below.setX(screen.x() + screen.width() - listRect.width());
            above.setX(screen.x() + screen.width() - listRect.width());
        }
        if (/*mapToGlobal(*/listRect/*.topLeft())*/.x() < screen.x() ) {
            below.setX(screen.x());
            above.setX(screen.x());
        }
    }

    if ( usePopup ) {
        // Position horizontally.
        listRect.moveLeft( above.x() );

        // Position vertically so the curently selected item lines up
        // with the combo box.
        /*const QRect currentItemRect = view()->visualRect( view()->currentIndex() );
        const int offset = listRect.top() -currentItemRect.top();
        listRect.moveTop( above.y() +offset -listRect.top() );*/

        // Clamp the listRect height and vertical position so we don't expand outside the
        // available screen geometry.This may override the vertical position, but it is more
        // important to show as much as possible of the popup.
        const int height = !boundToScreen ? listRect.height() : qMin(listRect.height(), screen.height());
        listRect.setHeight(height);
        if (boundToScreen) {
            if (listRect.top() < screen.top())
                listRect.moveTop(screen.top());
            if (listRect.bottom() > screen.bottom())
                listRect.moveBottom(screen.bottom());
        }
    } else if (!boundToScreen || listRect.height() <= belowHeight) {
        listRect.moveTopLeft(below);
    } else if (listRect.height() <= aboveHeight) {
        listRect.moveBottomLeft(above);
    } else if (belowHeight >= aboveHeight) {
        listRect.setHeight(belowHeight);
        listRect.moveTopLeft(below);
    } else {
        listRect.setHeight(aboveHeight);
        listRect.moveBottomLeft(above);
    }

#if QT_VERSION < QT_VERSION_CHECK(5, 0, 0)
#ifndef QT_NO_IM
    if ( QInputContext *qic = inputContext() )
        qic->reset();
#endif
#endif
    QScrollBar* sb = view()->horizontalScrollBar();
    Qt::ScrollBarPolicy policy = view()->horizontalScrollBarPolicy();
    bool needHorizontalScrollBar = ( policy == Qt::ScrollBarAsNeeded || policy == Qt::ScrollBarAlwaysOn ) && sb->minimum() < sb->maximum();
    if ( needHorizontalScrollBar ) {
        listRect.adjust( 0, 0, 0, sb->height() );
    }
    
    container->setGeometry( listRect );

#ifndef Q_WS_MAC
    const bool updatesEnabled = container->updatesEnabled();
#endif

#if defined( Q_WS_WIN ) && !defined( QT_NO_EFFECTS )
// FIXME Fix me ASAP
    /*bool scrollDown = ( listRect.topLeft() == below );
    if ( QApplication::isEffectEnabled( Qt::UI_AnimateCombo ) 
        && !style->styleHint( QStyle::SH_ComboBox_Popup, &opt, this ) && !window()->testAttribute( Qt::WA_DontShowOnScreen ) )
        qScrollEffect( container, scrollDown ? QEffects::DownScroll : QEffects::UpScroll, 150 );*/
#endif

// Don't disable updates on Mac OS X. Windows are displayed immediately on this platform,
// which means that the window will be visible before the call to container->show() returns.
// If updates are disabled at this point we'll miss our chance at painting the popup 
// menu before it's shown, causing flicker since the window then displays the standard gray 
// background.
#ifndef Q_WS_MAC
    container->setUpdatesEnabled( false );
#endif

    container->raise();
    container->show();
    //container->updateScrollers();
    view()->setFocus();

    view()->scrollTo( view()->currentIndex(), style->styleHint( QStyle::SH_ComboBox_Popup, &opt, this ) ? QAbstractItemView::PositionAtCenter : QAbstractItemView::EnsureVisible );

#ifndef Q_WS_MAC
    container->setUpdatesEnabled( updatesEnabled );
#endif

    container->update();
#ifdef QT_KEYPAD_NAVIGATION
    if ( QApplication::keypadNavigationEnabled() )
        view()->setEditFocus( true );
#endif
}
コード例 #6
0
ファイル: fractin.cpp プロジェクト: TinyCreation/Calculator-
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=='(')){
               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!='('){
                text="格式不支持!";
                ui->show->setText(text);
                return;
            }
            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);


}
コード例 #7
0
ファイル: owncloudpropagator.cpp プロジェクト: sebasje/mirall
void OwncloudPropagator::start(const SyncFileItemVector& items)
{
    Q_ASSERT(std::is_sorted(items.begin(), items.end()));

    /* Check and log the transmission checksum type */
    ConfigFile cfg;
    const QString checksumType = cfg.transmissionChecksum().toUpper();

    /* if the checksum type is empty, it is not send. No error */
    if( !checksumType.isEmpty() ) {
        if( checksumType == checkSumAdlerUpperC ||
                checksumType == checkSumMD5C    ||
                checksumType == checkSumSHA1C ) {
            qDebug() << "Client sends and expects transmission checksum type" << checksumType;
        } else {
            qWarning() << "Unknown transmission checksum type from config" << checksumType;
        }
    }

    /* This builds all the job needed for the propagation.
     * Each directories is a PropagateDirectory job, which contains the files in it.
     * In order to do that we loop over the items. (which are sorted by destination)
     * When we enter adirectory, we can create the directory job and push it on the stack. */

    _rootJob.reset(new PropagateDirectory(this));
    QStack<QPair<QString /* directory name */, PropagateDirectory* /* job */> > directories;
    directories.push(qMakePair(QString(), _rootJob.data()));
    QVector<PropagatorJob*> directoriesToRemove;
    QString removedDirectory;
    foreach(const SyncFileItemPtr &item, items) {

        if (!removedDirectory.isEmpty() && item->_file.startsWith(removedDirectory)) {
            // this is an item in a directory which is going to be removed.
            PropagateDirectory *delDirJob = dynamic_cast<PropagateDirectory*>(directoriesToRemove.last());

            if (item->_instruction == CSYNC_INSTRUCTION_REMOVE) {
                //already taken care of.  (by the removal of the parent directory)

                // increase the number of subjobs that would be there.
                if( delDirJob ) {
                    delDirJob->increaseAffectedCount();
                }
                continue;
            } else if (item->_instruction == CSYNC_INSTRUCTION_NEW && item->_isDirectory) {
                // create a new directory within a deleted directory? That can happen if the directory
                // etag were not fetched properly on the previous sync because the sync was aborted
                // while uploading this directory (which is now removed).  We can ignore it.
                if( delDirJob ) {
                    delDirJob->increaseAffectedCount();
                }
                continue;
            } else if (item->_instruction == CSYNC_INSTRUCTION_IGNORE) {
                continue;
            }

            qWarning() << "WARNING:  Job within a removed directory?  This should not happen!"
                       << item->_file << item->_instruction;
        }

        while (!item->destination().startsWith(directories.top().first)) {
            directories.pop();
        }

        if (item->_isDirectory) {
            PropagateDirectory *dir = new PropagateDirectory(this, item);
            dir->_firstJob.reset(createJob(item));
            if (item->_instruction == CSYNC_INSTRUCTION_REMOVE) {
                //We do the removal of directories at the end, because there might be moves from
                // this directories that will happen later.
                directoriesToRemove.append(dir);
                removedDirectory = item->_file + "/";

                // We should not update the etag of parent directories of the removed directory
                // since it would be done before the actual remove (issue #1845)
                // NOTE: Currently this means that we don't update those etag at all in this sync,
                //       but it should not be a problem, they will be updated in the next sync.
                for (int i = 0; i < directories.size(); ++i) {
                    directories[i].second->_item->_should_update_metadata = false;
                }
            } else {
                PropagateDirectory* currentDirJob = directories.top().second;
                currentDirJob->append(dir);
            }
            directories.push(qMakePair(item->destination() + "/" , dir));
        } else if (PropagateItemJob* current = createJob(item)) {
            directories.top().second->append(current);
        }
    }

    foreach(PropagatorJob* it, directoriesToRemove) {
        _rootJob->append(it);
    }
コード例 #8
0
void QDeclarativeListModelParser::setCustomData(QObject *obj, const QByteArray &d)
{
    QDeclarativeListModel *rv = static_cast<QDeclarativeListModel *>(obj);

    ModelNode *root = new ModelNode(rv->m_nested);
    rv->m_nested->_root = root;
    QStack<ModelNode *> nodes;
    nodes << root;

    bool processingSet = false;

    const ListModelData *lmd = (const ListModelData *)d.constData();
    const char *data = ((const char *)lmd) + lmd->dataOffset;

    for (int ii = 0; ii < lmd->instrCount; ++ii) {
        const ListInstruction &instr = lmd->instructions()[ii];

        switch(instr.type) {
        case ListInstruction::Push:
        {
            ModelNode *n = nodes.top();
            ModelNode *n2 = new ModelNode(rv->m_nested);
            n->values << QVariant::fromValue(n2);
            nodes.push(n2);
            if (processingSet)
                n->isArray = true;
        }
        break;

        case ListInstruction::Pop:
            nodes.pop();
            break;

        case ListInstruction::Value:
        {
            ModelNode *n = nodes.top();
            switch (QDeclarativeParser::Variant::Type(data[instr.dataIdx])) {
            case QDeclarativeParser::Variant::Invalid:
                n->isArray = true;
                break;
            case QDeclarativeParser::Variant::Boolean:
                n->values.append(bool(data[1 + instr.dataIdx]));
                break;
            case QDeclarativeParser::Variant::Number:
                n->values.append(QByteArray(data + 1 + instr.dataIdx).toDouble());
                break;
            case QDeclarativeParser::Variant::String:
                n->values.append(QString::fromUtf8(data + 1 + instr.dataIdx));
                break;
            default:
                Q_ASSERT("Format error in ListInstruction");
            }

            processingSet = false;
        }
        break;

        case ListInstruction::Set:
        {
            ModelNode *n = nodes.top();
            ModelNode *n2 = new ModelNode(rv->m_nested);
            n->properties.insert(QString::fromUtf8(data + instr.dataIdx), n2);
            nodes.push(n2);
            processingSet = true;
        }
        break;
        }
    }

    ModelNode *rootNode = rv->m_nested->_root;
    for (int i=0; i<rootNode->values.count(); ++i) {
        ModelNode *node = qvariant_cast<ModelNode *>(rootNode->values[i]);
        node->listIndex = i;
        node->updateListIndexes();
    }
}
コード例 #9
0
void QmlProfilerEventsModelProxy::loadData(qint64 rangeStart, qint64 rangeEnd)
{
    clear();

    qint64 qmlTime = 0;
    qint64 lastEndTime = 0;
    QHash <int, QVector<qint64> > durations;

    const bool checkRanges = (rangeStart != -1) && (rangeEnd != -1);

    const QVector<QmlProfilerDataModel::QmlEventData> &eventList
            = d->modelManager->qmlModel()->getEvents();
    const QVector<QmlProfilerDataModel::QmlEventTypeData> &typesList
            = d->modelManager->qmlModel()->getEventTypes();

    // used by binding loop detection
    QStack<const QmlProfilerDataModel::QmlEventData*> callStack;
    callStack.push(0); // artificial root

    for (int i = 0; i < eventList.size(); ++i) {
        const QmlProfilerDataModel::QmlEventData *event = &eventList[i];
        const QmlProfilerDataModel::QmlEventTypeData *type = &typesList[event->typeIndex];

        if (!d->acceptedTypes.contains(type->rangeType))
            continue;

        if (checkRanges) {
            if ((event->startTime + event->duration < rangeStart)
                    || (event->startTime > rangeEnd))
                continue;
        }

        // update stats
        QmlEventStats *stats = &d->data[event->typeIndex];

        stats->duration += event->duration;
        if (event->duration < stats->minTime)
            stats->minTime = event->duration;
        if (event->duration > stats->maxTime)
            stats->maxTime = event->duration;
        stats->calls++;

        // for median computing
        durations[event->typeIndex].append(event->duration);

        // qml time computation
        if (event->startTime > lastEndTime) { // assume parent event if starts before last end
            qmlTime += event->duration;
            lastEndTime = event->startTime + event->duration;
        }


        //
        // binding loop detection
        //
        const QmlProfilerDataModel::QmlEventData *potentialParent = callStack.top();
        while (potentialParent
               && !(potentialParent->startTime + potentialParent->duration > event->startTime)) {
            callStack.pop();
            potentialParent = callStack.top();
        }

        // check whether event is already in stack
        for (int ii = 1; ii < callStack.size(); ++ii) {
            if (callStack.at(ii)->typeIndex == event->typeIndex) {
                d->eventsInBindingLoop.insert(event->typeIndex);
                break;
            }
        }

        callStack.push(event);

        d->modelManager->modelProxyCountUpdated(d->modelId, i, eventList.count()*2);
    }

    // post-process: calc mean time, median time, percentoftime
    int i = d->data.size();
    int total = i * 2;

    for (QHash<int, QmlEventStats>::iterator it = d->data.begin(); it != d->data.end(); ++it) {
        QmlEventStats* stats = &it.value();
        if (stats->calls > 0)
            stats->timePerCall = stats->duration / (double)stats->calls;

        QVector<qint64> eventDurations = durations[it.key()];
        if (!eventDurations.isEmpty()) {
            Utils::sort(eventDurations);
            stats->medianTime = eventDurations.at(eventDurations.count()/2);
        }

        stats->percentOfTime = stats->duration * 100.0 / qmlTime;
        d->modelManager->modelProxyCountUpdated(d->modelId, i++, total);
    }

    // set binding loop flag
    foreach (int typeIndex, d->eventsInBindingLoop)
        d->data[typeIndex].isBindingLoop = true;

    // insert root event
    QmlEventStats rootEvent;
    rootEvent.duration = rootEvent.minTime = rootEvent.maxTime = rootEvent.timePerCall
                       = rootEvent.medianTime = qmlTime + 1;
    rootEvent.calls = 1;
    rootEvent.percentOfTime = 100.0;

    d->data.insert(-1, rootEvent);

    d->modelManager->modelProxyCountUpdated(d->modelId, 1, 1);
    emit dataAvailable();
}
コード例 #10
0
ファイル: java.cpp プロジェクト: kuailexs/symbiandump-mw3
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"));
}
コード例 #11
0
ファイル: MapStyle_P.cpp プロジェクト: Congle/OsmAnd-core
bool OsmAnd::MapStyle_P::parse( QXmlStreamReader& xmlReader )
{
    auto rulesetType = MapStyleRulesetType::Invalid;

    struct Lexeme
    {
        enum Type
        {
            Rule,
            Group,
        };

        Lexeme(Type type_, MapStyle_P* style_)
            : type(type_)
            , style(style_)
        {}

        const Type type;
        MapStyle_P* const style;
    };

    struct Rule : public Lexeme
    {
        Rule(std::shared_ptr<MapStyleRule> rule_, MapStyle_P* style_)
            : Lexeme(Lexeme::Rule, style_)
            , rule(rule_)
        {}

        const std::shared_ptr<MapStyleRule> rule;
    };

    struct Group : public Lexeme
    {
        Group(MapStyle_P* const style_)
            : Lexeme(Lexeme::Group, style_)
        {}

        QHash< QString, QString > attributes;
        QList< std::shared_ptr<MapStyleRule> > children;
        QList< std::shared_ptr<Lexeme> > subgroups;

        void addGroupFilter(const std::shared_ptr<MapStyleRule>& rule)
        {
            for(auto itChild = children.cbegin(); itChild != children.cend(); ++itChild)
            {
                auto child = *itChild;

                child->_d->_ifChildren.push_back(rule);
            }

            for(auto itSubgroup = subgroups.cbegin(); itSubgroup != subgroups.cend(); ++itSubgroup)
            {
                auto subgroup = *itSubgroup;

                assert(subgroup->type == Lexeme::Group);
                std::static_pointer_cast<Group>(subgroup)->addGroupFilter(rule);
            }
        }

        bool registerGlobalRules(const MapStyleRulesetType type)
        {
            for(auto itChild = children.cbegin(); itChild != children.cend(); ++itChild)
            {
                auto child = *itChild;

                if(!style->registerRule(type, child))
                    return false;
            }

            for(auto itSubgroup = subgroups.cbegin(); itSubgroup != subgroups.cend(); ++itSubgroup)
            {
                auto subgroup = *itSubgroup;

                assert(subgroup->type == Lexeme::Group);
                if(!std::static_pointer_cast<Group>(subgroup)->registerGlobalRules(type))
                    return false;
            }

            return true;
        }
    };

    QStack< std::shared_ptr<Lexeme> > stack;

    while (!xmlReader.atEnd() && !xmlReader.hasError())
    {
        xmlReader.readNext();
        const auto tagName = xmlReader.name();
        if (xmlReader.isStartElement())
        {
            if(tagName == QLatin1String("renderingStyle"))
            {
                // We have already parsed metadata and resolved dependencies, so here we don't need to do anything
            }
            else if(tagName == QLatin1String("renderingConstant"))
            {
                const auto& attribs = xmlReader.attributes();

                auto name = attribs.value(QLatin1String("name")).toString();
                auto value = attribs.value(QLatin1String("value")).toString();
                _parsetimeConstants.insert(name, value);
            }
            else if(tagName == QLatin1String("renderingProperty"))
            {
                MapStyleConfigurableInputValue* inputValue = nullptr;

                const auto& attribs = xmlReader.attributes();
                auto name = obtainValue(attribs.value(QLatin1String("attr")).toString());
                auto type = obtainValue(attribs.value(QLatin1String("type")).toString());
                auto title = obtainValue(attribs.value(QLatin1String("name")).toString());
                auto description = attribs.value(QLatin1String("description")).toString();
                auto encodedPossibleValues = attribs.value(QLatin1String("possibleValues"));
                QStringList possibleValues;
                if(!encodedPossibleValues.isEmpty())
                    possibleValues = encodedPossibleValues.toString().split(',', QString::SkipEmptyParts);
                for(auto itPossibleValue = possibleValues.begin(); itPossibleValue != possibleValues.end(); ++itPossibleValue)
                {
                    auto& possibleValue = *itPossibleValue;
                    possibleValue = obtainValue(possibleValue);
                }
                if(type == QLatin1String("string"))
                {
                    inputValue = new MapStyleConfigurableInputValue(
                        MapStyleValueDataType::String,
                        name,
                        title,
                        description,
                        possibleValues);
                }
                else if(type == QLatin1String("boolean"))
                {
                    inputValue = new MapStyleConfigurableInputValue(
                        MapStyleValueDataType::Boolean,
                        name,
                        title,
                        description,
                        possibleValues);
                }
                else // treat as integer
                {
                    inputValue = new MapStyleConfigurableInputValue(
                        MapStyleValueDataType::Integer,
                        name,
                        title,
                        description,
                        possibleValues);
                }

                registerValue(inputValue);
            }
            else if(tagName == QLatin1String("renderingAttribute"))
            {
                const auto& attribs = xmlReader.attributes();

                auto name = obtainValue(attribs.value(QLatin1String("name")).toString());

                std::shared_ptr<MapStyleRule> attribute(new MapStyleRule(owner, QHash< QString, QString >()));
                _attributes.insert(name, attribute);

                std::shared_ptr<Lexeme> selector(new Rule(attribute, this));
                stack.push(qMove(selector));
            }
            else if(tagName == QLatin1String("filter"))
            {
                QHash< QString, QString > ruleAttributes;

                if(!stack.isEmpty())
                {
                    auto lexeme = stack.top();

                    if(lexeme->type == Lexeme::Group)
                        ruleAttributes.unite(std::static_pointer_cast<Group>(lexeme)->attributes);
                }

                const auto& attribs = xmlReader.attributes();
                for(auto itXmlAttrib = attribs.cbegin(); itXmlAttrib != attribs.cend(); ++itXmlAttrib)
                {
                    const auto& xmlAttrib = *itXmlAttrib;

                    const auto tag = xmlAttrib.name().toString();
                    const auto value = obtainValue(xmlAttrib.value().toString());
                    ruleAttributes.insert(qMove(tag), qMove(value));
                }

                const std::shared_ptr<MapStyleRule> rule(new MapStyleRule(owner, ruleAttributes));

                if(!stack.isEmpty())
                {
                    auto lexeme = stack.top();

                    if(lexeme->type == Lexeme::Group)
                    {
                        std::static_pointer_cast<Group>(lexeme)->children.push_back(rule);
                    }
                    else if(lexeme->type == Lexeme::Rule)
                    {
                        std::static_pointer_cast<Rule>(lexeme)->rule->_d->_ifElseChildren.push_back(rule);
                    }
                }
                else
                {
                    if(!registerRule(rulesetType, rule))
                        return false;
                }

                stack.push(qMove(std::shared_ptr<Lexeme>(new Rule(rule, this))));
            }
            else if(tagName == QLatin1String("groupFilter"))
            {
                QHash< QString, QString > attributes;

                const auto& attribs = xmlReader.attributes();
                for(auto itXmlAttrib = attribs.cbegin(); itXmlAttrib != attribs.cend(); ++itXmlAttrib)
                {
                    const auto& xmlAttrib = *itXmlAttrib;

                    const auto tag = xmlAttrib.name().toString();
                    const auto value = obtainValue(xmlAttrib.value().toString());
                    attributes.insert(qMove(tag), qMove(value));
                }

                std::shared_ptr<MapStyleRule> rule(new MapStyleRule(owner, attributes));

                if(stack.isEmpty())
                {
                    OsmAnd::LogPrintf(OsmAnd::LogSeverityLevel::Error, "Group filter without parent");
                    return false;
                }

                auto lexeme = stack.top();
                if(lexeme->type == Lexeme::Group)
                {
                    std::static_pointer_cast<Group>(lexeme)->addGroupFilter(rule);
                }
                else if(lexeme->type == Lexeme::Rule)
                {
                    std::static_pointer_cast<Rule>(lexeme)->rule->_d->_ifChildren.push_back(rule);
                }

                stack.push(qMove(std::shared_ptr<Lexeme>(new Rule(rule, this))));
            }
            else if(tagName == QLatin1String("group"))
            {
                const auto group = new Group(this);
                if(!stack.isEmpty())
                {
                    auto lexeme = stack.top();
                    if(lexeme->type == Lexeme::Group)
                        group->attributes.unite(std::static_pointer_cast<Group>(lexeme)->attributes);
                }

                const auto& attribs = xmlReader.attributes();
                for(auto itXmlAttrib = attribs.cbegin(); itXmlAttrib != attribs.cend(); ++itXmlAttrib)
                {
                    const auto& xmlAttrib = *itXmlAttrib;

                    const auto tag = xmlAttrib.name().toString();
                    const auto value = obtainValue(xmlAttrib.value().toString());
                    group->attributes.insert(qMove(tag), qMove(value));
                }

                stack.push(qMove(std::shared_ptr<Lexeme>(group)));
            }
            else if(tagName == QLatin1String("order"))
            {
                rulesetType = MapStyleRulesetType::Order;
            }
            else if(tagName == QLatin1String("text"))
            {
                rulesetType = MapStyleRulesetType::Text;
            }
            else if(tagName == QLatin1String("point"))
            {
                rulesetType = MapStyleRulesetType::Point;
            }
            else if(tagName == QLatin1String("line"))
            {
                rulesetType = MapStyleRulesetType::Polyline;
            }
            else if(tagName == QLatin1String("polygon"))
            {
                rulesetType = MapStyleRulesetType::Polygon;
            } 
        }
        else if(xmlReader.isEndElement())
        {
            if(tagName == QLatin1String("filter"))
            {
                stack.pop();
            }
            else if(tagName == QLatin1String("group"))
            {
                const auto lexeme = stack.pop();

                if (stack.isEmpty())
                {
                    assert(lexeme->type == Lexeme::Group);
                    if(!std::static_pointer_cast<Group>(lexeme)->registerGlobalRules(rulesetType))
                        return false;
                }
                else
                {
                    const auto group = stack.top();
                    if(group->type == Lexeme::Group)
                        std::static_pointer_cast<Group>(group)->subgroups.push_back(qMove(lexeme));
                }
            }
            else if(tagName == QLatin1String("groupFilter"))
            {
                stack.pop();
            }
            else if(tagName == QLatin1String("renderingAttribute"))
            {
                stack.pop();
            }
        }
    }
    if(xmlReader.hasError())
    {
        std::cerr << qPrintable(xmlReader.errorString()) << "(" << xmlReader.lineNumber() << ", " << xmlReader.columnNumber() << ")" << std::endl;
        return false;
    }

    return true;
}
コード例 #12
0
ファイル: sc_editor.cpp プロジェクト: acamari/supercollider
void ScCodeEditor::indent( const QTextCursor & selection )
{
    if (selection.isNull())
        return;

    QTextCursor cursor(selection);

    cursor.beginEditBlock();

    QTextDocument *doc = QPlainTextEdit::document();
    int startBlockNum = doc->findBlock(cursor.selectionStart()).blockNumber();
    int endBlockNum = cursor.hasSelection() ?
        doc->findBlock(cursor.selectionEnd()).blockNumber() : startBlockNum;

    QStack<int> stack;
    int level = 0;
    int blockNum = 0;
    QTextBlock block = QPlainTextEdit::document()->begin();
    while (block.isValid())
    {
        if (level > 0) {
            stack.push(level);
            level = 0;
        }

        int initialStackSize = stack.size();

        TextBlockData *data = static_cast<TextBlockData*>(block.userData());
        if (data)
        {
            int count = data->tokens.size();
            for (int idx = 0; idx < count; ++idx)
            {
                const Token & token = data->tokens[idx];
                switch (token.type)
                {
                case Token::OpeningBracket:
                    if (token.character != '(' || stack.size() || token.positionInBlock)
                        level += 1;
                    break;

                case Token::ClosingBracket:
                    if (level)
                        level -= 1;
                    else if(!stack.isEmpty()) {
                        stack.top() -= 1;
                        if (stack.top() <= 0)
                            stack.pop();
                    }
                    break;

                default:
                    ;
                }
            }
        }

        if(blockNum >= startBlockNum) {
            int indentLevel;
            if (data && data->tokens.size() && data->tokens[0].type == Token::ClosingBracket)
                indentLevel = stack.size();
            else
                indentLevel = initialStackSize;
            block = indent(block, indentLevel);
        }

        if(blockNum == endBlockNum)
            break;

        block = block.next();
        ++blockNum;
    }

    cursor.endEditBlock();
}
コード例 #13
0
void AccelTree::copyNodeTo(const QXmlNodeModelIndex &node,
                           QAbstractXmlReceiver *const receiver,
                           const NodeCopySettings &settings) const
{
    /* This code piece can be seen as a customized version of
     * QAbstractXmlReceiver::item/sendAsNode(). */
    Q_ASSERT(receiver);
    Q_ASSERT(!node.isNull());

    typedef QHash<QXmlName::PrefixCode, QXmlName::NamespaceCode> Binding;
    QStack<Binding> outputted;

    switch(node.kind())
    {
        case QXmlNodeModelIndex::Element:
        {
            outputted.push(Binding());

            /* Add the namespace for our element name. */
            const QXmlName elementName(node.name());

            receiver->startElement(elementName);

            if(!settings.testFlag(InheritNamespaces))
                receiver->namespaceBinding(QXmlName(StandardNamespaces::StopNamespaceInheritance, 0,
                                                    StandardPrefixes::StopNamespaceInheritance));

            if(settings.testFlag(PreserveNamespaces))
                node.sendNamespaces(receiver);
            else
            {
                /* Find the namespaces that we actually use and add them to outputted. These are drawn
                 * from the element name, and the node's attributes. */
                outputted.top().insert(elementName.prefix(), elementName.namespaceURI());

                const QXmlNodeModelIndex::Iterator::Ptr attributes(iterate(node, QXmlNodeModelIndex::AxisAttribute));
                QXmlNodeModelIndex attr(attributes->next());

                while(!attr.isNull())
                {
                    const QXmlName &attrName = attr.name();
                    outputted.top().insert(attrName.prefix(), attrName.namespaceURI());
                    attr = attributes->next();
                }

                Binding::const_iterator it(outputted.top().constBegin());
                const Binding::const_iterator end(outputted.top().constEnd());

                for(; it != end; ++it)
                    receiver->namespaceBinding(QXmlName(it.value(), 0, it.key()));
            }

            /* Send the attributes of the element. */
            {
                QXmlNodeModelIndex::Iterator::Ptr attributes(node.iterate(QXmlNodeModelIndex::AxisAttribute));
                QXmlNodeModelIndex attribute(attributes->next());

                while(!attribute.isNull())
                {
                    const QString &v = attribute.stringValue();
                    receiver->attribute(attribute.name(), QStringRef(&v));
                    attribute = attributes->next();
                }
            }

            /* Send the children of the element. */
            copyChildren(node, receiver, settings);

            receiver->endElement();
            outputted.pop();
            break;
        }
        case QXmlNodeModelIndex::Document:
        {
            /* We need to intercept and grab the elements of the document node, such
             * that we preserve/inherit preference applies to them. */
            receiver->startDocument();
            copyChildren(node, receiver, settings);
            receiver->endDocument();
            break;
        }
        default:
            receiver->item(node);
    }

}
コード例 #14
0
QPolygonF QwtWeedingCurveFitter::simplify( const QPolygonF &points ) const
{
    const double toleranceSqr = d_data->tolerance * d_data->tolerance;

    QStack<Line> stack;
    stack.reserve( 500 );

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

    QVector<bool> usePoint( nPoints, false );

    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 maxDistSqr = 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();

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

                const double s = toVecX * ( -unitVecX ) + toVecY * ( -unitVecY );
                if ( s < 0.0 )
                {
                    distToSegmentSqr = toVecLength;
                }
                else
                {
                    distToSegmentSqr = qFabs( toVecLength - s * s );
                }
            }

            if ( maxDistSqr < distToSegmentSqr )
            {
                maxDistSqr = distToSegmentSqr;
                nVertexIndexMaxDistance = i;
            }
        }
        if ( maxDistSqr <= toleranceSqr )
        {
            usePoint[r.from] = true;
            usePoint[r.to] = true;
        }
        else
        {
            stack.push( Line( r.from, nVertexIndexMaxDistance ) );
            stack.push( Line( nVertexIndexMaxDistance, r.to ) );
        }
    }

    QPolygonF stripped;
    for ( int i = 0; i < nPoints; i++ )
    {
        if ( usePoint[i] )
            stripped += p[i];
    }

    return stripped;
}
コード例 #15
0
void QHelpContentProvider::run()
{
    QString title;
    QString link;
    int depth = 0;
    QHelpContentItem *item = 0;

    m_mutex.lock();
    m_rootItem = new QHelpContentItem(QString(), QString(), 0);
    m_rootItems.enqueue(m_rootItem);
    QStringList atts = m_filterAttributes;
    const QStringList fileNames = m_helpEngine->orderedFileNameList;
    m_mutex.unlock();

    foreach (QString dbFileName, fileNames) {
        m_mutex.lock();
        if (m_abort) {
            m_abort = false;
            m_mutex.unlock();
            break;
        }
        m_mutex.unlock();
        QHelpDBReader reader(dbFileName,
            QHelpGlobal::uniquifyConnectionName(dbFileName +
            QLatin1String("FromQHelpContentProvider"),
            QThread::currentThread()), 0);
        if (!reader.init())
            continue;
        foreach (const QByteArray& ba, reader.contentsForFilter(atts)) {
            if (ba.size() < 1)
                continue;

            int _depth = 0;
            bool _root = false;
            QStack<QHelpContentItem*> stack;

            QDataStream s(ba);
            for (;;) {
                s >> depth;
                s >> link;
                s >> title;
                if (title.isEmpty())
                    break;
CHECK_DEPTH:
                if (depth == 0) {
                    m_mutex.lock();
                    item = new QHelpContentItem(title, link,
                        m_helpEngine->fileNameReaderMap.value(dbFileName), m_rootItem);
                    m_rootItem->appendChild(item);
                    m_mutex.unlock();
                    stack.push(item);
                    _depth = 1;
                    _root = true;
                } else {
                    if (depth > _depth && _root) {
                        _depth = depth;
                        stack.push(item);
                    }
                    if (depth == _depth) {
                        item = new QHelpContentItem(title, link,
                            m_helpEngine->fileNameReaderMap.value(dbFileName), stack.top());
                        stack.top()->appendChild(item);
                    } else if (depth < _depth) {
                        stack.pop();
                        --_depth;
                        goto CHECK_DEPTH;
                    }
                }
            }
        }
    }
コード例 #16
0
ファイル: tree.cpp プロジェクト: Ellyster/qgo
/*
 *	Returns: true  - son of current move was found
 *           false - 
 */
bool Tree::insertStone(Move *node)
{
	if (root == NULL)
	{
		qFatal("Error: No root!");
		return false;
	}
	else
	{
		if (current == NULL)
		{
			qFatal("Error: No current node!");
			return false;
		}

		// current node has no son?
		if (current->son == NULL)
		{
			if(current == node)
			{
				qDebug("Attempting to add move as its own son!");
				return false;
			}

			current->son = node;
			node->parent = current;
			node->setTimeinfo(false);
            current = node;
			node->getMatrix()->insertStone(node->getX(), node->getY(), node->getColor());
			
			return false;
		}
		// A son found
		else
		{
			
			//we insert node between current and current->son
			node->parent = current;
			node->son = current->son;
			current->son->parent = node;
			current->son = node;

			//update all brothers to enable switching between them
			Move *t = node->son->brother;
			while (t != NULL) 
			{
				t->parent = node;
				t = t->brother;
			}
			current->parent->marker = current;
			node->marker = NULL;

			node->setTimeinfo(false);
            current = node;
			node->getMatrix()->insertStone(node->getX(), node->getY(), node->getColor());

			//update son - it is exclude from traverse search because we cannot update brothers of node->son
			node->son->setMoveNumber(node->son->getMoveNumber()+1);
			node->son->getMatrix()->insertStone(node->getX(), node->getY(), node->getColor());

			if (node->son->son != NULL)
			{
				// Traverse the tree and update every node (matrix and moveNum)
				QStack<Move*> stack;
				Move *t = NULL;
				stack.push(node->son->son);

				while (!stack.isEmpty())
				{
					t = stack.pop();
					if (t != NULL)
					{
						if (t->brother != NULL)
							stack.push(t->brother);
						if (t->son != NULL)
							stack.push(t->son);
						t->setMoveNumber(t->getMoveNumber()+1);
						t->getMatrix()->insertStone(node->getX(), node->getY(), node->getColor());
					}
				}
			}
			return true;
		}
	}
}
コード例 #17
0
ファイル: LoadingModel.cpp プロジェクト: KDE/android-qt
void Loader::load()
{
    QFile in(QLatin1String("tree.xml"));

    /* LoadingModel::m_result will be null, signalling failure. */
    if(!in.open(QIODevice::ReadOnly))
        return;

    QXmlStreamReader reader(&in);
    while(!reader.atEnd())
    {
        reader.readNext();

        switch(reader.tokenType())
        {
            case QXmlStreamReader::StartDocument:
            /* Fallthrough. */
            case QXmlStreamReader::StartElement:
            {
                QXmlName name;
                if(reader.tokenType() == QXmlStreamReader::StartElement)
                {
                    name = QXmlName(m_namePool,
                                    reader.name().toString(),
                                    reader.namespaceUri().toString(),
                                    reader.prefix().toString());
                }
                /* Else, the name is null. */

                LoadingModel::Node *const tmp = new LoadingModel::Node(reader.tokenType() == QXmlStreamReader::StartElement
                                                                       ? QXmlNodeModelIndex::Element
                                                                       : QXmlNodeModelIndex::Document,
                                                                       m_parentStack.top(),
                                                                       QString(),
                                                                       name);
                m_result.append(tmp);

                if(m_currentNode)
                {
                    if(m_currentNode->parent == m_parentStack.top())
                        m_currentNode->followingSibling = tmp;
                }

                const QXmlStreamAttributes attributes(reader.attributes());
                const int len = attributes.count();

                for(int i = 0; i < len; ++i)
                {
                    const QXmlStreamAttribute &attr = attributes.at(i);
                    const LoadingModel::Node *const a = new LoadingModel::Node(QXmlNodeModelIndex::Attribute,
                                                                               m_parentStack.top(),
                                                                               attr.value().toString(),
                                                                               QXmlName(m_namePool,
                                                                                       attr.name().toString(),
                                                                                       attr.namespaceUri().toString(),
                                                                                       attr.prefix().toString()));
                    /* We add it also to m_result such that compareOrder() is correct
                     * for attributes. m_result owns a. */
                    tmp->attributes.append(a);
                    m_result.append(a);
                }

                adjustSiblings(tmp);
                m_parentStack.push(m_currentNode);
                break;
            }
            case QXmlStreamReader::EndDocument:
            /* Fallthrough. */
            case QXmlStreamReader::EndElement:
            {
                m_currentNode->followingSibling = 0;
                m_currentNode = m_parentStack.pop();

                if(reader.tokenType() == QXmlStreamReader::EndDocument)
                    const_cast<LoadingModel::Node *>(m_result.first())->followingSibling = 0;

                break;
            }
            case QXmlStreamReader::Characters:
            {
                LoadingModel::Node *const tmp = new LoadingModel::Node(QXmlNodeModelIndex::Text, m_parentStack.top(), reader.text().toString());
                m_result.append(tmp);
                adjustSiblings(tmp);
                break;
            }
            case QXmlStreamReader::ProcessingInstruction:
            {
                LoadingModel::Node *const tmp = new LoadingModel::Node(QXmlNodeModelIndex::ProcessingInstruction,
                                                                       m_parentStack.top(),
                                                                       reader.processingInstructionData().toString(),
                                                                       QXmlName(m_namePool, reader.processingInstructionTarget().toString()));
                m_result.append(tmp);
                adjustSiblings(tmp);
                break;
            }
            case QXmlStreamReader::Comment:
            {
                LoadingModel::Node *const tmp = new LoadingModel::Node(QXmlNodeModelIndex::Comment, m_parentStack.top(), reader.text().toString());
                m_result.append(tmp);
                adjustSiblings(tmp);
                break;
            }
            case QXmlStreamReader::DTD:
                qFatal("%s: QXmlStreamReader::DTD token is not supported", Q_FUNC_INFO);
                break;
            case QXmlStreamReader::EntityReference:
                qFatal("%s: QXmlStreamReader::EntityReference token is not supported", Q_FUNC_INFO);
                break;
            case QXmlStreamReader::NoToken:
            /* Fallthrough. */
            case QXmlStreamReader::Invalid:
            {
                qWarning("%s", qPrintable(reader.errorString()));
                m_result.clear();
                return;
            }
        }
    }

    if(reader.hasError())
    {
        qWarning("%s", qPrintable(reader.errorString()));
        m_result.clear();
    }
}
コード例 #18
0
QPair<int, double> WorkbookParserPrivate::calculateInfix(int start, QStringList items) {
    int i = start;
    bool ok;
    qreal d, n1, n2;
    QStack<qreal> values;
    QStack<OperatorBase<qreal>*> operators;
    QPair<int, double> result;

    // TODO add in errors ie unbalanced brackets wrong number
    // of values or operators
    // TODO handle cell references and ranges.

    while(i < items.size()) {
        QString s = items.at(i);

        if (s == ")") {
            result.first = i + 1;
            result.second = values.pop();
            return result;
        }

        if (s == "(") {
            i++;
            result = calculateInfix(i, items); // Recurse.
            i = result.first;
            values.push(result.second);
            continue;
        }

        d = s.toDouble(&ok);
        if (ok) {
            values.insert(i++, d);
            continue;
        }
        // turns constants into their actual value in the list.
        ConstantBase *constant = dynamic_cast<ConstantBase*>(pPluginStore->getConstant(s));
        if (constant) {
            values.insert(i++, constant->value());
            continue;
        }

        IFunction *func = dynamic_cast<IFunction*>(pPluginStore->getFunction(s));
        if (func) {
            result = calculateInfixFunction(func, i, items); // functioss should return a value.
            i = result.first;
            values.push(result.second);
            continue;
        }

        OperatorBase<qreal> *op1 = dynamic_cast<OperatorBase<qreal>*>(pPluginStore->getOperator(s));
        if (op1) {
            if (operators.size() == 0 || operators.top()->level() < op1->level()) {
                OperatorBase<qreal> *op2 = operators.pop();
                n1 = values.pop();
                n2 = values.pop();
                d = op2->calculate(n2, n1);
                values.push(d);
            }
            operators.push(op1);

            i++;
            continue;
        }

        // TODO string handling
//        OperatorBase<QString> *ops1 = dynamic_cast<OperatorBase<QString>*>(pPluginStore->getOperator(s));
//        if (op1) {
//            // convert numbers to strings if necessary
//        }

    }

    return result;
}
コード例 #19
0
void dspCostedIndentedBOM::sFillList()
{
  double totalCosts = 0;

  _bomitem->clear();

  if (_item->isValid())
  {
      QString sql( "SELECT 2 AS seqord, "
		           "       bomdata_bomwork_id, bomdata_item_id, bomdata_bomwork_parent_id,"
                   "       bomdata_bomwork_seqnumber, bomdata_item_number, bomdata_uom_name,"
                   "       bomdata_itemdescription,"
                   "       bomdata_qtyper,"
                   "       bomdata_scrap,"
                   "       bomdata_effective,"
                   "       bomdata_expires," );

     if (_useStandardCosts->isChecked())
       sql += " formatCost(bomdata_stdunitcost) AS f_unitcost,"
              " formatCost(bomdata_stdextendedcost) AS f_extendedcost,"
              " bomdata_stdextendedcost AS extendedcost, ";
     else if (_useActualCosts->isChecked())
       sql += " formatCost(bomdata_actunitcost) AS f_unitcost,"
              " formatCost(bomdata_actextendedcost) AS f_extendedcost,"
              " bomdata_actextendedcost AS extendedcost, ";

	 sql += "bomdata_bomwork_level "
		    "FROM indentedbom(:item_id,:revision_id,0,0) ";
      q.prepare(sql);
      q.bindValue(":item_id", _item->id());
      q.bindValue(":revision_id", _revision->id());
      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("bomwork_id").toInt(),
						q.value("bomdata_item_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"),
						q.value("f_unitcost"),
						q.value("f_extendedcost") );
	   }
       else
	   {
         if (q.value("bomdata_bomwork_parent_id").toInt() == -1)
         {
           if (q.value("bomdata_bomwork_id").toInt() == -1)
           {
             last = new XTreeWidgetItem( _bomitem,last, -1, -1,
                                      "", q.value("bomdata_item_number"),
                                      "", "", "", "", "" );
             last->setText(7, "");
             last->setText(8, q.value("f_unitcost").toString());
             last->setText(9, q.value("f_extendedcost").toString());
           }
           else
           {
             last = new XTreeWidgetItem( _bomitem, last, q.value("bomdata_bomwork_id").toInt(), q.value("bomdata_item_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"),
                                      q.value("f_unitcost"), q.value("f_extendedcost") );
           }
		 }
		 else
	     {
            last = new XTreeWidgetItem(_bomitem, last, q.value("bomwork_id").toInt(),
						q.value("bomdata_item_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"),
						q.value("f_unitcost"),
						q.value("f_extendedcost") );
         }
	     totalCosts += q.value("extendedcost").toDouble();
	  }
	}
    last = new XTreeWidgetItem(_bomitem, -1, -1);
    last->setText(1, tr("Total Cost"));
    last->setText(9, formatCost(totalCosts));

    q.prepare( "SELECT formatCost(actcost(:item_id)) AS actual,"
                 "       formatCost(stdcost(:item_id)) AS standard;" );
      q.bindValue(":item_id", _item->id());
      q.exec();
      if (q.first())
      {
        last = new XTreeWidgetItem(_bomitem, -1, -1);
        last->setText(1, tr("Actual Cost"));
        last->setText(9, q.value("actual").toString());

        last = new XTreeWidgetItem( _bomitem, -1, -1);
        last->setText(1, tr("Standard Cost"));
        last->setText(9, q.value("standard").toString());
      }
    _bomitem->expandAll();
  }
}
コード例 #20
0
ファイル: ctkTreeComboBox.cpp プロジェクト: 151706061/CTK
// -------------------------------------------------------------------------
void ctkTreeComboBox::resizePopup()
{
  // copied from QComboBox.cpp
  Q_D(ctkTreeComboBox);

  QStyle * const style = this->style();
  QWidget* container = qobject_cast<QWidget*>(this->view()->parent());

  QStyleOptionComboBox opt;
  this->initStyleOption(&opt);
  QRect listRect(style->subControlRect(QStyle::CC_ComboBox, &opt,
                                       QStyle::SC_ComboBoxListBoxPopup, this));
  QRect screen = QApplication::desktop()->availableGeometry(
    QApplication::desktop()->screenNumber(this));
  QPoint below = this->mapToGlobal(listRect.bottomLeft());
  int belowHeight = screen.bottom() - below.y();
  QPoint above = this->mapToGlobal(listRect.topLeft());
  int aboveHeight = above.y() - screen.y();
  bool boundToScreen = !this->window()->testAttribute(Qt::WA_DontShowOnScreen);

  const bool usePopup = style->styleHint(QStyle::SH_ComboBox_Popup, &opt, this);
    {
    int listHeight = 0;
    int count = 0;
    QStack<QModelIndex> toCheck;
    toCheck.push(this->view()->rootIndex());
#ifndef QT_NO_TREEVIEW
    QTreeView *treeView = qobject_cast<QTreeView*>(this->view());
    if (treeView && treeView->header() && !treeView->header()->isHidden())
      listHeight += treeView->header()->height();
#endif
    while (!toCheck.isEmpty())
      {
      QModelIndex parent = toCheck.pop();
      for (int i = 0; i < this->model()->rowCount(parent); ++i)
        {
        QModelIndex idx = this->model()->index(i, this->modelColumn(), parent);
        if (!idx.isValid())
          {
          continue;
          }
        listHeight += this->view()->visualRect(idx).height(); /* + container->spacing() */;
#ifndef QT_NO_TREEVIEW
        if (this->model()->hasChildren(idx) && treeView && treeView->isExpanded(idx))
          {
          toCheck.push(idx);
          }
#endif
        ++count;
        if (!usePopup && count > this->maxVisibleItems())
          {
          toCheck.clear();
          break;
          }
        }
      }
    listRect.setHeight(listHeight);
    }
      {
      // add the spacing for the grid on the top and the bottom;
      int heightMargin = 0;//2*container->spacing();

      // add the frame of the container
      int marginTop, marginBottom;
      container->getContentsMargins(0, &marginTop, 0, &marginBottom);
      heightMargin += marginTop + marginBottom;

      //add the frame of the view
      this->view()->getContentsMargins(0, &marginTop, 0, &marginBottom);
      //marginTop += static_cast<QAbstractScrollAreaPrivate *>(QObjectPrivate::get(this->view()))->top;
      //marginBottom += static_cast<QAbstractScrollAreaPrivate *>(QObjectPrivate::get(this->view()))->bottom;
      heightMargin += marginTop + marginBottom;

      listRect.setHeight(listRect.height() + heightMargin);
      }

      // Add space for margin at top and bottom if the style wants it.
      if (usePopup)
        {
        listRect.setHeight(listRect.height() + style->pixelMetric(QStyle::PM_MenuVMargin, &opt, this) * 2);
        }

      // Make sure the popup is wide enough to display its contents.
      if (usePopup)
        {
        const int diff = d->computeWidthHint() - this->width();
        if (diff > 0)
          {
          listRect.setWidth(listRect.width() + diff);
          }
        }

      //we need to activate the layout to make sure the min/maximum size are set when the widget was not yet show
      container->layout()->activate();
      //takes account of the minimum/maximum size of the container
      listRect.setSize( listRect.size().expandedTo(container->minimumSize())
                        .boundedTo(container->maximumSize()));

      // make sure the widget fits on screen
      if (boundToScreen)
        {
        if (listRect.width() > screen.width() )
          {
          listRect.setWidth(screen.width());
          }
        if (this->mapToGlobal(listRect.bottomRight()).x() > screen.right())
          {
          below.setX(screen.x() + screen.width() - listRect.width());
          above.setX(screen.x() + screen.width() - listRect.width());
          }
        if (this->mapToGlobal(listRect.topLeft()).x() < screen.x() )
          {
          below.setX(screen.x());
          above.setX(screen.x());
          }
        }

      if (usePopup)
        {
        // Position horizontally.
        listRect.moveLeft(above.x());

#ifndef Q_WS_S60
        // Position vertically so the curently selected item lines up
        // with the combo box.
        const QRect currentItemRect = this->view()->visualRect(this->view()->currentIndex());
        const int offset = listRect.top() - currentItemRect.top();
        listRect.moveTop(above.y() + offset - listRect.top());
#endif

      // Clamp the listRect height and vertical position so we don't expand outside the
      // available screen geometry.This may override the vertical position, but it is more
      // important to show as much as possible of the popup.
        const int height = !boundToScreen ? listRect.height() : qMin(listRect.height(), screen.height());
#ifdef Q_WS_S60
        //popup needs to be stretched with screen minimum dimension
        listRect.setHeight(qMin(screen.height(), screen.width()));
#else
        listRect.setHeight(height);
#endif

        if (boundToScreen)
          {
          if (listRect.top() < screen.top())
            {
            listRect.moveTop(screen.top());
            }
          if (listRect.bottom() > screen.bottom())
            {
            listRect.moveBottom(screen.bottom());
            }
          }
#ifdef Q_WS_S60
        if (screen.width() < screen.height())
          {
          // in portait, menu should be positioned above softkeys
          listRect.moveBottom(screen.bottom());
          }
        else
          {
          TRect staConTopRect = TRect();
          AknLayoutUtils::LayoutMetricsRect(AknLayoutUtils::EStaconTop, staConTopRect);
          listRect.setWidth(listRect.height());
          //by default popup is centered on screen in landscape
          listRect.moveCenter(screen.center());
          if (staConTopRect.IsEmpty())
            {
            // landscape without stacon, menu should be at the right
            (opt.direction == Qt::LeftToRight) ? listRect.setRight(screen.right()) :
              listRect.setLeft(screen.left());
            }
          }
#endif
        }
      else if (!boundToScreen || listRect.height() <= belowHeight)
        {
        listRect.moveTopLeft(below);
        }
      else if (listRect.height() <= aboveHeight)
        {
        listRect.moveBottomLeft(above);
        }
      else if (belowHeight >= aboveHeight)
        {
        listRect.setHeight(belowHeight);
        listRect.moveTopLeft(below);
        }
      else
        {
        listRect.setHeight(aboveHeight);
        listRect.moveBottomLeft(above);
        }

#if QT_VERSION < QT_VERSION_CHECK(5,0,0) && !defined QT_NO_IM
      if (QInputContext *qic = this->inputContext())
        {
        qic->reset();
        }
#endif
      QScrollBar *sb = this->view()->horizontalScrollBar();
      Qt::ScrollBarPolicy policy = this->view()->horizontalScrollBarPolicy();
      bool needHorizontalScrollBar =
        (policy == Qt::ScrollBarAsNeeded || policy == Qt::ScrollBarAlwaysOn)
        && sb->minimum() < sb->maximum();
      if (needHorizontalScrollBar)
        {
        listRect.adjust(0, 0, 0, sb->height());
        }
      container->setGeometry(listRect);
}
コード例 #21
0
void OwncloudPropagator::start(const SyncFileItemVector& items)
{
    Q_ASSERT(std::is_sorted(items.begin(), items.end()));

    /* This builds all the jobs needed for the propagation.
     * Each directory is a PropagateDirectory job, which contains the files in it.
     * In order to do that we loop over the items. (which are sorted by destination)
     * When we enter a directory, we can create the directory job and push it on the stack. */

    _rootJob.reset(new PropagateDirectory(this));
    QStack<QPair<QString /* directory name */, PropagateDirectory* /* job */> > directories;
    directories.push(qMakePair(QString(), _rootJob.data()));
    QVector<PropagatorJob*> directoriesToRemove;
    QString removedDirectory;
    foreach(const SyncFileItemPtr &item, items) {

        if (!removedDirectory.isEmpty() && item->_file.startsWith(removedDirectory)) {
            // this is an item in a directory which is going to be removed.
            PropagateDirectory *delDirJob = dynamic_cast<PropagateDirectory*>(directoriesToRemove.first());

            if (item->_instruction == CSYNC_INSTRUCTION_REMOVE) {
                // already taken care of. (by the removal of the parent directory)

                // increase the number of subjobs that would be there.
                if( delDirJob ) {
                    delDirJob->increaseAffectedCount();
                }
                continue;
            } else if (item->_isDirectory
                       && (item->_instruction == CSYNC_INSTRUCTION_NEW
                           || item->_instruction == CSYNC_INSTRUCTION_TYPE_CHANGE)) {
                // create a new directory within a deleted directory? That can happen if the directory
                // etag was not fetched properly on the previous sync because the sync was aborted
                // while uploading this directory (which is now removed).  We can ignore it.
                if( delDirJob ) {
                    delDirJob->increaseAffectedCount();
                }
                continue;
            } else if (item->_instruction == CSYNC_INSTRUCTION_IGNORE) {
                continue;
            } else if (item->_instruction == CSYNC_INSTRUCTION_RENAME) {
                // all is good, the rename will be executed before the directory deletion
            } else {
                qWarning() << "WARNING:  Job within a removed directory?  This should not happen!"
                           << item->_file << item->_instruction;
            }
        }

        while (!item->destination().startsWith(directories.top().first)) {
            directories.pop();
        }

        if (item->_isDirectory) {
            PropagateDirectory *dir = new PropagateDirectory(this, item);
            dir->_firstJob.reset(createJob(item));

            if (item->_instruction == CSYNC_INSTRUCTION_TYPE_CHANGE
                    && item->_direction == SyncFileItem::Up) {
                // Skip all potential uploads to the new folder.
                // Processing them now leads to problems with permissions:
                // checkForPermissions() has already run and used the permissions
                // of the file we're about to delete to decide whether uploading
                // to the new dir is ok...
                foreach(const SyncFileItemPtr &item2, items) {
                    if (item2->destination().startsWith(item->destination() + "/")) {
                        item2->_instruction = CSYNC_INSTRUCTION_NONE;
                        _anotherSyncNeeded = true;
                    }
                }
            }

            if (item->_instruction == CSYNC_INSTRUCTION_REMOVE) {
                // We do the removal of directories at the end, because there might be moves from
                // these directories that will happen later.
                directoriesToRemove.prepend(dir);
                removedDirectory = item->_file + "/";

                // We should not update the etag of parent directories of the removed directory
                // since it would be done before the actual remove (issue #1845)
                // NOTE: Currently this means that we don't update those etag at all in this sync,
                //       but it should not be a problem, they will be updated in the next sync.
                for (int i = 0; i < directories.size(); ++i) {
                    directories[i].second->_item->_should_update_metadata = false;
                }
            } else {
                PropagateDirectory* currentDirJob = directories.top().second;
                currentDirJob->append(dir);
            }
            directories.push(qMakePair(item->destination() + "/" , dir));
        } else if (PropagateItemJob* current = createJob(item)) {
コード例 #22
0
ファイル: qsciprinter.cpp プロジェクト: ChanJLee/ChanIDE
// Print a range of lines to a printer.
int QsciPrinter::printRange(QsciScintillaBase *qsb, int from, int to)
{
    // Sanity check.
    if (!qsb)
        return false;

    // Setup the printing area.
    QRect def_area;

    def_area.setX(0);
    def_area.setY(0);

    def_area.setWidth(width());
    def_area.setHeight(height());

    // Get the page range.
    int pgFrom, pgTo;

    pgFrom = fromPage();
    pgTo = toPage();

    // Find the position range.
    long startPos, endPos;

    endPos = qsb->SendScintilla(QsciScintillaBase::SCI_GETLENGTH);

    startPos = (from > 0 ? qsb -> SendScintilla(QsciScintillaBase::SCI_POSITIONFROMLINE,from) : 0);

    if (to >= 0)
    {
        long toPos = qsb -> SendScintilla(QsciScintillaBase::SCI_POSITIONFROMLINE,to + 1);

        if (endPos > toPos)
            endPos = toPos;
    }

    if (startPos >= endPos)
        return false;

    QPainter painter(this);
    bool reverse = (pageOrder() == LastPageFirst);
    bool needNewPage = false;

    qsb -> SendScintilla(QsciScintillaBase::SCI_SETPRINTMAGNIFICATION,mag);
    qsb -> SendScintilla(QsciScintillaBase::SCI_SETPRINTWRAPMODE,wrap);

    for (int i = 1; i <= numCopies(); ++i)
    {
        // If we are printing in reverse page order then remember the start
        // position of each page.
        QStack<long> pageStarts;

        int currPage = 1;
        long pos = startPos;

        while (pos < endPos)
        {
            // See if we have finished the requested page range.
            if (pgTo > 0 && pgTo < currPage)
                break;

            // See if we are going to render this page, or just see how much
            // would fit onto it.
            bool render = false;

            if (pgFrom == 0 || pgFrom <= currPage)
            {
                if (reverse)
                    pageStarts.push(pos);
                else
                {
                    render = true;

                    if (needNewPage)
                    {
                        if (!newPage())
                            return false;
                    }
                    else
                        needNewPage = true;
                }
            }

            QRect area = def_area;

            formatPage(painter,render,area,currPage);
            pos = qsb -> SendScintilla(QsciScintillaBase::SCI_FORMATRANGE,render,&painter,area,pos,endPos);

            ++currPage;
        }

        // All done if we are printing in normal page order.
        if (!reverse)
            continue;

        // Now go through each page on the stack and really print it.
        while (!pageStarts.isEmpty())
        {
            --currPage;

            long ePos = pos;
            pos = pageStarts.pop();

            if (needNewPage)
            {
                if (!newPage())
                    return false;
            }
            else
                needNewPage = true;

            QRect area = def_area;

            formatPage(painter,true,area,currPage);
            qsb->SendScintilla(QsciScintillaBase::SCI_FORMATRANGE,true,&painter,area,pos,ePos);
        }
    }

    return true;
}
コード例 #23
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,
                                                    child.isDir() ? RCCFileInfo::Directory : 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;
}
コード例 #24
0
ファイル: qscodemarker.cpp プロジェクト: Smarre/qtjambi
QList<Section> QsCodeMarker::sections( const InnerNode *inner, SynopsisStyle style, Status status )
{
    QList<Section> sections;

    if (inner->type() != Node::Class)
        return sections;

    const ClassNode *classe = static_cast<const ClassNode *>(inner);

    if ( style == Summary ) {
	FastSection enums(classe, "Enums", "", "enum", "enums");
	FastSection functions(classe, "Functions", "", "function", "functions");
	FastSection readOnlyProperties(classe, "", "Read-Only Properties", "property", "properties");
	FastSection signalz(classe, "Signals", "", "signal", "signals");
	FastSection writableProperties(classe, "", "Writable Properties", "property", "properties");

	QStack<const ClassNode *> stack;
	stack.push( classe );

	while ( !stack.isEmpty() ) {
	    const ClassNode *ancestorClass = stack.pop();

	    NodeList::ConstIterator c = ancestorClass->childNodes().begin();
	    while ( c != ancestorClass->childNodes().end() ) {
		if ( (*c)->access() == Node::Public ) {
		    if ( (*c)->type() == Node::Enum ) {
			insert( enums, *c, style, status );
		    } else if ( (*c)->type() == Node::Function ) {
			const FunctionNode *func = (const FunctionNode *) *c;
			if ( func->metaness() == FunctionNode::Signal ) {
			    insert( signalz, *c, style, status );
			} else {
			    insert( functions, *c, style, status );
			}
		    } else if ( (*c)->type() == Node::Property ) {
			const PropertyNode *property =
				(const PropertyNode *) *c;
			if ( property->setters().isEmpty() ) {
			    insert( readOnlyProperties, *c, style, status );
			} else {
			    insert( writableProperties, *c, style, status );
			}
		    }
		}
		++c;
	    }

	    QList<RelatedClass>::ConstIterator r = ancestorClass->baseClasses().begin();
	    while ( r != ancestorClass->baseClasses().end() ) {
		stack.prepend( (*r).node );
		++r;
	    }
	}
	append( sections, enums );
	append( sections, writableProperties );
	append( sections, readOnlyProperties );
	append( sections, functions );
	append( sections, signalz );
    } else if ( style == Detailed ) {
	FastSection enums( classe, "Enum Documentation", "", "member", "members");
	FastSection functionsAndSignals( classe, "Function and Signal Documentation", "", "member", "members");
	FastSection properties( classe, "Property Documentation", "", "member", "members");

	NodeList::ConstIterator c = classe->childNodes().begin();
	while ( c != classe->childNodes().end() ) {
	    if ( (*c)->access() == Node::Public ) {
		if ( (*c)->type() == Node::Enum ) {
		    insert( enums, *c, style, status );
		} else if ( (*c)->type() == Node::Function ) {
		    insert( functionsAndSignals, *c, style, status );
		} else if ( (*c)->type() == Node::Property ) {
		    insert( properties, *c, style, status );
		}
	    }
	    ++c;
	}
	append( sections, enums );
	append( sections, properties );
	append( sections, functionsAndSignals );
    } else { // ( style == SeparateList )
	FastSection all(classe, "", "", "member", "members");

	QStack<const ClassNode *> stack;
	stack.push( classe );

	while ( !stack.isEmpty() ) {
	    const ClassNode *ancestorClass = stack.pop();

	    NodeList::ConstIterator c = ancestorClass->childNodes().begin();
	    while ( c != ancestorClass->childNodes().end() ) {
		if ( (*c)->access() == Node::Public )
		    insert( all, *c, style, status );
		++c;
	    }

	    QList<RelatedClass>::ConstIterator r = ancestorClass->baseClasses().begin();
	    while ( r != ancestorClass->baseClasses().end() ) {
		stack.prepend( (*r).node );
		++r;
	    }
	}
	append( sections, all );
    }
    return sections;
}
コード例 #25
0
ファイル: fwe_editor.cpp プロジェクト: FoxWorks/FWE
////////////////////////////////////////////////////////////////////////////////
/// @brief
////////////////////////////////////////////////////////////////////////////////
void EditorWindow::loadObjectVariablesData() {
	//Create special mapping from materials databases
	QMap<QString,QString> special_mapping;
	
	//Parse out list of materials by class
	EVDS_VARIABLE* database;
	if (EVDS_System_GetDatabaseByName(system,"material",&database) == EVDS_OK) {
		SIMC_LIST* entries;
		EVDS_Variable_GetList(database,&entries);

		SIMC_LIST_ENTRY* entry = SIMC_List_GetFirst(entries);
		while (entry) {
			char name[256] = { 0 };
			char print_name[256] = { 0 };
			char class_str[256] = { 0 };
			EVDS_VARIABLE* attribute;
			EVDS_VARIABLE* material = (EVDS_VARIABLE*)SIMC_List_GetData(entries,entry);

			if (EVDS_Variable_GetAttribute(material,"name",&attribute) == EVDS_OK) {
				EVDS_Variable_GetString(attribute,name,255,0);
			}
			if (EVDS_Variable_GetAttribute(material,"print",&attribute) == EVDS_OK) {
				EVDS_Variable_GetString(attribute,print_name,255,0);
			}
			if (!print_name[0]) strcpy(print_name,name);

			//Add to list
			special_mapping["@materials._"] += QString(name) + "\n" + QString(print_name) + "\n";
			if (EVDS_Variable_GetAttribute(material,"class",&attribute) == EVDS_OK) {
				EVDS_Variable_GetString(attribute,class_str,255,0);
				if (class_str[0]) {
					special_mapping["@materials."+QString(class_str)] += QString(name) + "\n" + QString(print_name) + "\n";
				} else {
					//EVDS_BREAKPOINT();
				}
			}
			entry = SIMC_List_GetNext(entries,entry);
		}
	}

	//Load information about editable objects and properties
	QFile xml_file(":/evds.xml");
	if (!xml_file.open(QIODevice::ReadOnly)) {
		return;
	}

	QStack<QString> currentTag;
	QStack<QString> currentName;
	int variable_index = 0;

	QXmlStreamReader xml(&xml_file);
	while (!xml.atEnd()) {
		xml.readNext();
		if (xml.isStartElement()) {
			currentTag.push(xml.name().toString());
			currentName.push(xml.attributes().value("name").toString());
			//printf("[s] %s\n",xml.name().toAscii().data());
			if (currentTag.top() == "object_vars") {
				variable_index = 0;
			}
			if (currentTag.top() == "csection_vars") {
				variable_index = 0;
			}
		} else if (xml.isEndElement()) {
			if (currentTag.top() == "var") {
				variable_index++;
			}

			currentTag.pop();
			currentName.pop();
			//printf("[e] %s\n",xml.name().toAscii().data());
		} else if (xml.isCharacters() && !xml.isWhitespace()) {
			if (currentTag.value(currentTag.count()-3) == "object_vars") {
				QString objectType = currentName.value(currentName.count()-3);
				if (objectVariables[objectType].count() <= variable_index) {
					objectVariables[objectType].append(QMap<QString,QString>());
				}
				QString value = xml.text().toString();
				QMapIterator<QString, QString> i(special_mapping);
				while (i.hasNext()) {
					i.next();
					value.replace(i.key(),i.value());
				}

				objectVariables[objectType][variable_index][currentTag.top()] = value;
			}
			if (currentTag.value(currentTag.count()-3) == "csection_vars") {
				QString csectionType = currentName.value(currentName.count()-3);
				if (csectionVariables[csectionType].count() <= variable_index) {
					csectionVariables[csectionType].append(QMap<QString,QString>());
				}
				QString value = xml.text().toString();
				QMapIterator<QString, QString> i(special_mapping);
				while (i.hasNext()) {
					i.next();
					value.replace(i.key(),i.value());
				}

				csectionVariables[csectionType][variable_index][currentTag.top()] = value;
			}
		}
	}
}
コード例 #26
0
ファイル: shVarModel.cpp プロジェクト: 10110111/GLSL-Debugger
void ShVarModel::unsetItemWatched(const QModelIndex & i_qIndex)
{
	QStack<QModelIndex> stack;
	ShVarItem *item = NULL;

	if (i_qIndex.isValid()) {
		stack.push(m_qWatchProxy->mapToSource(i_qIndex));

		while (!stack.isEmpty()) {
			QModelIndex idx = stack.pop();
			item = static_cast<ShVarItem*>(idx.internalPointer());

			if (item != NULL) {
				item->setData(DF_WATCHED, false);
				if (item->childCount() > 0) {
					/* Item is root or inner node. */
					for (int i = 0; i < item->childCount(); i++) {
						// TODO: There is possible a more elegant solution to
						// get indices of the children, but I am no Qt expert
						// and this seems to work somehow.
						stack.push(idx.child(i, idx.column()));
					}
				} else {
					/* Item is leaf node. */
					if (item->getPixelBoxPointer() != NULL) {
						PixelBox *fb = item->getPixelBoxPointer();
						item->setPixelBoxPointer(NULL);
						delete fb;
					}
					if (item->getCurrentPointer() != NULL) {
						VertexBox *vb = item->getCurrentPointer();
						item->setCurrentPointer(NULL);
						delete vb;
					}
					if (item->getVertexBoxPointer() != NULL) {
						VertexBox *vb = item->getVertexBoxPointer();
						item->setVertexBoxPointer(NULL);
						delete vb;
					} /* end if (item->childCount() > 0) */

					m_qWatchListItems.removeAll(item);
				} /* end if (item->childCount() > 0) */
			} /* if (item != NULL) */
		} /* end while (!stack.isEmpty()) */
		/* 'item' should now be the item associated with 'i_qIndex'. */

		/*
		 * Remove parent recursively when all children have left the watch list.
		 * This must not be done for child nodes of 'item' as (i) these are
		 * guaranteed to be removed be the iterative tree traversal above and
		 * (ii) too many nodes will be removed if doing so because because the
		 * tree is reorganised as nodes are removed and the indices of removed
		 * nodes are reused under certain circumstances.
		 */
		if (item != NULL) {
			unsetRecursiveWatched(item);
		}

		/* used to update the whole tree,
		 * it seems just emiting the signal is not enough for qt 4.2.2 */
		m_qWatchProxy->setFilterRegExp(QRegExp("(true|1)"));

	} /* end if (i_qIndex.isValid()) */
}
コード例 #27
0
void registerCleanupFunction(CleanupFunction func)
{
    cleanupFunctionList.push(func);
}
コード例 #28
0
ファイル: karchive.cpp プロジェクト: parulina/parupaint
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;
}
コード例 #29
0
void EPSPlug::parseOutput(QString fn, bool eps)
{
	QString tmp, token, params, lasttoken, lastPath, currPath;
	int z, lcap, ljoin, dc, pagecount;
	int failedImages = 0;
	double dcp;
	bool fillRuleEvenOdd = true;
	PageItem* ite;
	QStack<PageItem*> groupStack;
	QStack< QList<PageItem*> > groupStackP;
	QStack<int>  gsStack;
	QStack<uint> gsStackMarks;
	QFile f(fn);
	lasttoken = "";
	pagecount = 1;
	if (f.open(QIODevice::ReadOnly))
	{
		int fProgress = 0;
		int fSize = (int) f.size();
		if (progressDialog) {
			progressDialog->setTotalSteps("GI", fSize);
			qApp->processEvents();
		}
		lastPath = "";
		currPath = "";
		LineW = 0;
		Opacity = 1;
		CurrColor = CommonStrings::None;
		JoinStyle = Qt::MiterJoin;
		CapStyle = Qt::FlatCap;
		DashPattern.clear();
		ScTextStream ts(&f);
		int line_cnt = 0;
		while (!ts.atEnd() && !cancel)
		{
			tmp = "";
			tmp = ts.readLine();
			if (progressDialog && (++line_cnt % 100 == 0)) {
				int fPos = f.pos();
				int progress = static_cast<int>(ceil(fPos / (double) fSize * 100));
				if (progress > fProgress)
				{
					progressDialog->setProgress("GI", fPos);
					qApp->processEvents();
					fProgress = progress;
				}
			}
			token = tmp.section(' ', 0, 0);
			params = tmp.section(' ', 1, -1, QString::SectionIncludeTrailingSep);
			if (lasttoken == "sp"  && !eps && token != "sp" ) //av: messes up anyway: && (!interactive))
			{
				m_Doc->addPage(pagecount);
				m_Doc->view()->addPage(pagecount, true);
				pagecount++;
			}
			if (token == "n")
			{
				Coords.resize(0);
				FirstM = true;
				WasM = false;
				ClosedPath = false;
			}
			else if (token == "m")
				WasM = true;
			else if (token == "c")
			{
				Curve(&Coords, params);
				currPath += params;
			}
			else if (token == "l")
			{
				LineTo(&Coords, params);
				currPath += params;
			}
			else if (token == "fill-winding")
			{
				fillRuleEvenOdd = false;
			}
			else if (token == "fill-evenodd")
			{
				fillRuleEvenOdd = true;
			}
			else if (token == "f")
			{
				//TODO: pattern -> Imageframe + Clip
				if (Coords.size() != 0)
				{
					if ((Elements.count() != 0) && (lastPath == currPath))
					{
						ite = Elements.at(Elements.count()-1);
						ite->setFillColor(CurrColor);
						ite->setFillTransparency(1.0 - Opacity);
						lastPath = "";
					}
					else
					{
						if (ClosedPath)
							z = m_Doc->itemAdd(PageItem::Polygon, PageItem::Unspecified, baseX, baseY, 10, 10, LineW, CurrColor, CommonStrings::None, true);
						else
							z = m_Doc->itemAdd(PageItem::PolyLine, PageItem::Unspecified, baseX, baseY, 10, 10, LineW, CurrColor, CommonStrings::None, true);
						ite = m_Doc->Items->at(z);
						ite->PoLine = Coords.copy();  //FIXME: try to avoid copy if FPointArray when properly shared
						ite->PoLine.translate(m_Doc->currentPage()->xOffset(), m_Doc->currentPage()->yOffset());
						ite->ClipEdited = true;
						ite->FrameType = 3;
						ite->fillRule = (fillRuleEvenOdd);
						FPoint wh = getMaxClipF(&ite->PoLine);
						ite->setWidthHeight(wh.x(),wh.y());
						ite->Clip = FlattenPath(ite->PoLine, ite->Segments);
						ite->setFillTransparency(1.0 - Opacity);
						ite->setTextFlowMode(PageItem::TextFlowDisabled);
						m_Doc->AdjustItemSize(ite);
						if (ite->itemType() == PageItem::Polygon)
							ite->ContourLine = ite->PoLine.copy();
						if ((groupStack.count() != 0) && (groupStackP.count() != 0))
							groupStackP.top().append(ite);
						Elements.append(ite);
						lastPath = currPath;
					}
					currPath = "";
				}
			}
			else if (token == "s")
			{
				if (Coords.size() != 0)
				{
				//	LineW = qMax(LineW, 0.01); // Set Linewidth to be a least 0.01 pts, a Stroke without a Linewidth makes no sense
					if ((Elements.count() != 0) && (lastPath == currPath))
					{
						ite = Elements.at(Elements.count()-1);
						ite->setLineColor(CurrColor);
						ite->setLineWidth(LineW);
						ite->PLineEnd = CapStyle;
						ite->PLineJoin = JoinStyle;
						ite->setLineTransparency(1.0 - Opacity);
						ite->DashOffset = DashOffset;
						ite->DashValues = DashPattern;
					}
					else
					{
						if (ClosedPath)
							z = m_Doc->itemAdd(PageItem::Polygon, PageItem::Unspecified, baseX, baseY, 10, 10, LineW, CommonStrings::None, CurrColor, true);
						else
							z = m_Doc->itemAdd(PageItem::PolyLine, PageItem::Unspecified, baseX, baseY, 10, 10, LineW, CommonStrings::None, CurrColor, true);
						ite = m_Doc->Items->at(z);
						ite->PoLine = Coords.copy(); //FIXME: try to avoid copy when FPointArray is properly shared
						ite->PoLine.translate(m_Doc->currentPage()->xOffset(), m_Doc->currentPage()->yOffset());
						ite->ClipEdited = true;
						ite->FrameType = 3;
						ite->PLineEnd = CapStyle;
						ite->PLineJoin = JoinStyle;
						ite->DashOffset = DashOffset;
						ite->DashValues = DashPattern;
						FPoint wh = getMaxClipF(&ite->PoLine);
						ite->setWidthHeight(wh.x(), wh.y());
						ite->Clip = FlattenPath(ite->PoLine, ite->Segments);
						ite->setLineTransparency(1.0 - Opacity);
						m_Doc->AdjustItemSize(ite);
						if (ite->itemType() == PageItem::Polygon)
							ite->ContourLine = ite->PoLine.copy();
						ite->setLineWidth(LineW);
						ite->setTextFlowMode(PageItem::TextFlowDisabled);
						if ((groupStack.count() != 0) && (groupStackP.count() != 0))
							groupStackP.top().append(ite);
						Elements.append(ite);
					}
					lastPath = "";
					currPath = "";
				}
			}
			else if (token == "co")
				CurrColor = parseColor(params, eps);
			else if (token == "corgb")
				CurrColor = parseColor(params, eps, colorModelRGB);
			else if (token == "ci")
			{
				if (Coords.size() != 0)
				{
					QString vers = QString(qVersion()).left(5);
					if (vers < "4.3.3")
					{
						clipCoords = Coords;
						z = m_Doc->itemAdd(PageItem::Group, PageItem::Rectangle, baseX, baseY, 10, 10, 0, CommonStrings::None, CommonStrings::None, true);
						ite = m_Doc->Items->at(z);
						ite->PoLine = Coords.copy();  //FIXME: try to avoid copy if FPointArray when properly shared
						ite->PoLine.translate(m_Doc->currentPage()->xOffset(), m_Doc->currentPage()->yOffset());
						ite->ClipEdited = true;
						ite->FrameType = 3;
						FPoint wh = getMaxClipF(&ite->PoLine);
						ite->setWidthHeight(wh.x(),wh.y());
						ite->Clip = FlattenPath(ite->PoLine, ite->Segments);
						m_Doc->AdjustItemSize(ite, true);
						ite->ContourLine = ite->PoLine.copy();
						ite->setItemName( tr("Group%1").arg(m_Doc->GroupCounter));
						ite->setTextFlowMode(PageItem::TextFlowDisabled);
						Elements.append(ite);
						if ((groupStack.count() != 0) && (groupStackP.count() != 0))
							groupStackP.top().append(ite);
						groupStack.push(ite);
						QList<PageItem*> gElements;
						groupStackP.push(gElements);
						gsStackMarks.push(gsStack.count());
						m_Doc->GroupCounter++;
					}
					else
					{
						QPainterPath tmpPath = Coords.toQPainterPath(true);
						tmpPath = boundingBoxRect.intersected(tmpPath);
						if ((tmpPath.boundingRect().width() != 0) && (tmpPath.boundingRect().height() != 0))
						{
							clipCoords.fromQPainterPath(tmpPath);
							z = m_Doc->itemAdd(PageItem::Group, PageItem::Rectangle, baseX, baseY, 10, 10, 0, CommonStrings::None, CommonStrings::None, true);
							ite = m_Doc->Items->at(z);
							ite->PoLine = clipCoords.copy();  //FIXME: try to avoid copy if FPointArray when properly shared
							ite->PoLine.translate(m_Doc->currentPage()->xOffset(), m_Doc->currentPage()->yOffset());
							ite->ClipEdited = true;
							ite->FrameType = 3;
							FPoint wh = getMaxClipF(&ite->PoLine);
							ite->setWidthHeight(wh.x(),wh.y());
							ite->Clip = FlattenPath(ite->PoLine, ite->Segments);
							m_Doc->AdjustItemSize(ite, true);
							ite->ContourLine = ite->PoLine.copy();
							ite->setItemName( tr("Group%1").arg(m_Doc->GroupCounter));
							ite->setTextFlowMode(PageItem::TextFlowDisabled);
							Elements.append(ite);
							if ((groupStack.count() != 0) && (groupStackP.count() != 0))
								groupStackP.top().append(ite);
							groupStack.push(ite);
							QList<PageItem*> gElements;
							groupStackP.push(gElements);
							gsStackMarks.push(gsStack.count());
							m_Doc->GroupCounter++;
						}
					}
				}
				Coords   = FPointArray(0);
				lastPath = "";
				currPath = "";
			}
			else if (token == "gs")
			{
				gsStack.push(1);
			}
			else if (token == "gr")
			{
				// #6834 : self defense against incorrectly balanced save/restore
				if (gsStack.count() > 0)
					gsStack.pop();
				if ((groupStack.count() != 0) && (groupStackP.count() != 0))
				{
					if (gsStack.count() < static_cast<int>(gsStackMarks.top()))
					{
						PageItem *ite = groupStack.pop();
						QList<PageItem*> gList = groupStackP.pop();
						for (int d = 0; d < gList.count(); d++)
						{
							Elements.removeAll(gList.at(d));
						}
						m_Doc->groupObjectsToItem(ite, gList);
						gsStackMarks.pop();
					}
				}
			}
			else if (token == "w")
			{
				ScTextStream Lw(&params, QIODevice::ReadOnly);
				Lw >> LineW;
			}
			else if (token == "ld")
コード例 #30
0
bool KArchiveDirectory::copyTo(const QString &dest, bool recursiveCopy) const
{
    QDir root;
    const QString destDir(QDir(dest).absolutePath()); // get directory path without any "." or ".."

    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(destDir);   // ... with given path
    do {
        const KArchiveDirectory *curDir = dirStack.pop();

        // extract only to specified folder if it is located within archive's extraction folder
        // otherwise put file under root position in extraction folder
        QString curDirName = dirNameStack.pop();
        if (!QDir(curDirName).absolutePath().startsWith(destDir)) {
            qCWarning(KArchiveLog) << "Attempted export into folder" << curDirName
                << "which is outside of the extraction root folder" << destDir << "."
                << "Changing export of contained files to extraction root folder.";
            curDirName = destDir;
        }

        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(QLatin1String(".lnk"))) {
                    linkName += QLatin1String(".lnk");
                }
#endif
                QFile symLinkTarget(curEntry->symLinkTarget());
                if (!symLinkTarget.link(linkName)) {
                    //qCDebug(KArchiveLog) << "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;
}