Esempio n. 1
0
void dspDetailedInventoryHistoryByLotSerial::sFillList()
{
  QString trace;
  _invhist->clear();

  if (_dateGroup->isChecked())
  {
    if (!_dates->startDate().isValid())
    {
      QMessageBox::critical( this, tr("Enter Start Date"),
                             tr("Please enter a valid Start Date.") );
      _dates->setFocus();
      return;
    }

    if (!_dates->endDate().isValid())
    {
      QMessageBox::critical( this, tr("Enter End Date"),
                             tr("Please enter a valid End Date.") );
      _dates->setFocus();
      return;
    }
  }


  if ( ((_selected->isChecked() && _lotSerial->number().trimmed().length() == 0)
     || (_pattern->isChecked() && _lotSerialPattern->text().trimmed().length() == 0))
     && (!_item->isValid()) )
  {
    QMessageBox::warning( this, tr("Enter Lot/Serial #"),
                          tr("<p>You must enter a Lot/Serial or Item criteria to view Inventory "
			     "Detail by Lot/Serial #.</p>") );
    _lotSerial->setFocus();
    return;
  }


  if (_traceGroup->isChecked())
  {
    if (_forward->isChecked())
      trace="F";
    else
      trace="B";
  }
  else
    trace="N";

  q.prepare( "SELECT * FROM lshist(:itemid,:warehouseid,:lotserial,:pattern,:transType,:startDate,:endDate,:trace,1); ");
  _dates->bindValue(q);
  if (_item->isValid())
    q.bindValue(":itemid", _item->id());
  if (_warehouse->isSelected())
    q.bindValue(":warehouseid", _warehouse->id());
  if (_selected->isChecked())
  {
    if (_lotSerial->number().trimmed().length() > 0)
      q.bindValue(":lotserial", _lotSerial->number().trimmed());
    q.bindValue(":pattern", FALSE);
  }
  else
  {   
    q.bindValue(":lotserial", _lotSerialPattern->text().trimmed());
    q.bindValue(":pattern", TRUE);
  }
  q.bindValue(":transType", _transType->id());
  q.bindValue(":trace", trace);
  q.exec();

  QStack<XTreeWidgetItem*> parent;
  XTreeWidgetItem *last = 0;
  int level = 1;
  while (q.next())
  {
    while(q.value("lshist_level").toInt() < level)
    {
      level--;
      last = parent.pop();
    }
    
    while(q.value("lshist_level").toInt() > level)
    {
      level++;
      parent.push(last);
      last = 0;
    }
    
    if(!parent.isEmpty() && parent.top())
      last = new XTreeWidgetItem(parent.top(), last, q.value("lshist_id").toInt(),
                             q.value("lshist_warehous_code"),
			     q.value("lshist_transdate"), q.value("lshist_transtype"),
			     q.value("lshist_ordernumber"), q.value("lshist_item_number"),
			     q.value("lshist_locationname"), q.value("lshist_lotserial"),
			     q.value("lshist_invuom"), q.value("lshist_transqty") );
    else
      last = new XTreeWidgetItem(_invhist, last, q.value("lshist_id").toInt(),
                             q.value("lshist_warehous_code"),
			     q.value("lshist_transdate"), q.value("lshist_transtype"),
			     q.value("lshist_ordernumber"), q.value("lshist_item_number"),
			     q.value("lshist_locationname"), q.value("lshist_lotserial"),
			     q.value("lshist_invuom"), q.value("lshist_transqty") );
                             
    if (q.value("lshist_posted").toBool())
    {
      last->setText(9, q.value("lshist_qty_before").toString());
      last->setText(10, q.value("lshist_qty_after").toString());
    }
    else
      last->setTextColor("orange");
  }
  _invhist->expandAll();
}
namespace KWin
{

// Convert QRegion to XserverRegion. All code uses XserverRegion
// only when really necessary as the shared implementation uses
// QRegion.
XserverRegion toXserverRegion(QRegion region)
{
    QVector< QRect > rects = region.rects();
    XRectangle* xr = new XRectangle[ rects.count()];
    for (int i = 0;
            i < rects.count();
            ++i) {
        xr[ i ].x = rects[ i ].x();
        xr[ i ].y = rects[ i ].y();
        xr[ i ].width = rects[ i ].width();
        xr[ i ].height = rects[ i ].height();
    }
    XserverRegion ret = XFixesCreateRegion(display(), xr, rects.count());
    delete[] xr;
    return ret;
}

// adapted from Qt, because this really sucks ;)
XRenderColor preMultiply(const QColor &c, float opacity)
{
    XRenderColor color;
    const uint A = c.alpha() * opacity,
               R = c.red(),
               G = c.green(),
               B = c.blue();
    color.alpha = (A | A << 8);
    color.red   = (R | R << 8) * color.alpha / 0x10000;
    color.green = (G | G << 8) * color.alpha / 0x10000;
    color.blue  = (B | B << 8) * color.alpha / 0x10000;
    return color;
}

XRenderPicture xRenderFill(const XRenderColor *xc)
{
    Pixmap pixmap = XCreatePixmap(display(), rootWindow(), 1, 1, 32);
    XRenderPictureAttributes pa; pa.repeat = True;
    XRenderPicture fill(pixmap, 32);
    XFreePixmap(display(), pixmap);
    XRenderChangePicture(display(), fill, CPRepeat, &pa);
    XRenderFillRectangle(display(), PictOpSrc, fill, xc, 0, 0, 1, 1);
    return fill;
}

XRenderPicture xRenderFill(const QColor &c)
{
    XRenderColor xc = preMultiply(c);
    return xRenderFill(&xc);
}

static XRenderPicture _blendPicture = X::None;
static XRenderColor _blendColor;
XRenderPicture xRenderBlendPicture(double opacity)
{
    _blendColor.alpha = ushort(opacity * 0xffff);
    if (_blendPicture == X::None)
        _blendPicture = xRenderFill(&_blendColor);
    else
        XRenderFillRectangle(display(), PictOpSrc, _blendPicture, &_blendColor, 0, 0, 1, 1);
    return _blendPicture;
}


static XRenderPicture *_circle[4] = {NULL, NULL, NULL, NULL};

#define DUMP_CNR(_SECT_, _W_, _H_, _XOFF_, _YOFF_)\
    dump = QPixmap(_W_, _H_);\
    dump.fill(Qt::transparent);\
    p.begin(&dump);\
    p.drawPixmap( 0, 0, tmp, _XOFF_, _YOFF_, _W_, _H_ );\
    p.end();\
    _circle[_SECT_] = new XRenderPicture(dump);

#define CS 8

static XRenderPicture *circle(int i)
{
    if (!_circle[0]) {
        QPixmap tmp(2 * CS, 2 * CS);
        tmp.fill(Qt::transparent);
        QPainter p(&tmp);
        p.setRenderHint(QPainter::Antialiasing);
        p.setPen(Qt::NoPen); p.setBrush(Qt::black);
        p.drawEllipse(tmp.rect());
        p.end();
        QPixmap dump;
        DUMP_CNR(0, CS, CS, 0, 0);
        DUMP_CNR(1, CS, CS, CS, 0);
        DUMP_CNR(2, CS, CS, CS, CS);
        DUMP_CNR(3, CS, CS, 0, CS);
    }
    return _circle[i];
}

void xRenderRoundBox(Picture pict, const QRect &rect, int , const QColor &c)
{
    XRenderPicture fill = xRenderFill(c);
    int op = c.alpha() == 255 ? PictOpSrc : PictOpOver;
    // TODO: implement second paramenter "roundness"
    // so rather use ?? XRenderCompositeTriFan (dpy, op, src, dst, maskFormat, xSrc, ySrc,
    //XPointFixed *points, npoint);
    // this will require "points on a circle" calculation, however...

    int s = qMin(CS, qMin(rect.height() / 2, rect.width() / 2));
    int x, y, b, r;
    rect.getCoords(&x, &y, &r, &b);
    r -= (s - 1);
    b -= (s - 1);
    XRenderComposite(display(), PictOpOver, fill, *circle(0), pict, 0, 0, 0, 0, x, y, CS, CS);
    XRenderComposite(display(), PictOpOver, fill, *circle(1), pict, 0, 0, CS - s, 0, r, y, s, s);
    XRenderComposite(display(), PictOpOver, fill, *circle(2), pict, 0, 0, CS - s, CS - s, r, b, s, s);
    XRenderComposite(display(), PictOpOver, fill, *circle(3), pict, 0, 0, 0, CS - s, x, b, s, s);
    XRenderComposite(display(), op, fill, 0, pict, 0, 0, 0, 0, x + s, y, rect.width() - 2 * s, s);
    XRenderComposite(display(), op, fill, 0, pict, 0, 0, 0, 0, x, y + s, rect.width(), rect.height() - 2 * s);
    XRenderComposite(display(), op, fill, 0, pict, 0, 0, 0, 0, x + s, b, rect.width() - 2 * s, s);
}

#undef CS
#undef DUMP_CNR

// XRenderFind(Standard)Format() is a roundtrip, so cache the results
static XRenderPictFormat* renderformats[ 33 ];

static Picture createPicture(Pixmap pix, int depth)
{
    if (pix == None)
        return None;
    if (renderformats[ depth ] == NULL) {
        switch(depth) {
        case 1:
            renderformats[ 1 ] = XRenderFindStandardFormat(display(), PictStandardA1);
            break;
        case 8:
            renderformats[ 8 ] = XRenderFindStandardFormat(display(), PictStandardA8);
            break;
        case 24:
            renderformats[ 24 ] = XRenderFindStandardFormat(display(), PictStandardRGB24);
            break;
        case 32:
            renderformats[ 32 ] = XRenderFindStandardFormat(display(), PictStandardARGB32);
            break;
        default: {
            XRenderPictFormat req;
            long mask = PictFormatType | PictFormatDepth;
            req.type = PictTypeDirect;
            req.depth = depth;
            renderformats[ depth ] = XRenderFindFormat(display(), mask, &req, 0);
            break;
        }
        }
        if (renderformats[ depth ] == NULL) {
            kWarning(1212) << "Could not find XRender format for depth" << depth;
            return None;
        }
    }
    return XRenderCreatePicture(display(), pix, renderformats[ depth ], 0, NULL);
}

XRenderPicture::XRenderPicture(QPixmap pix)
{
    if (Extensions::nonNativePixmaps()) {
        Pixmap xPix = XCreatePixmap(display(), rootWindow(), pix.width(), pix.height(), pix.depth());
        QPixmap tempPix = QPixmap::fromX11Pixmap(xPix, QPixmap::ExplicitlyShared);
        tempPix.fill(Qt::transparent);
        QPainter p(&tempPix);
        p.drawPixmap(QPoint(0, 0), pix);
        p.end();
        d = new XRenderPictureData(createPicture(tempPix.handle(), tempPix.depth()));
        XFreePixmap(display(), xPix);
    } else {
        d = new XRenderPictureData(createPicture(pix.handle(), pix.depth()));
    }
}

XRenderPicture::XRenderPicture(Pixmap pix, int depth)
    : d(new XRenderPictureData(createPicture(pix, depth)))
{
}

static QPixmap *s_offscreenTarget = 0;
static QStack<XRenderPicture*> s_scene_offscreenTargetStack;
static int s_renderOffscreen = 0;

void scene_setXRenderOffscreenTarget(QPixmap *pix)
{
    s_offscreenTarget = pix;
}

XRenderPicture *scene_xRenderOffscreenTarget()
{
    return s_scene_offscreenTargetStack.isEmpty() ? 0 : s_scene_offscreenTargetStack.top();
}

void setXRenderOffscreen(bool b)
{
    b ? ++s_renderOffscreen : --s_renderOffscreen;
    if (s_renderOffscreen < 0) {
        s_renderOffscreen = 0;
        qWarning("*** SOMETHING IS MESSED UP WITH YOUR setXRenderOffscreen() USAGE ***");
    }
}

void xRenderPushTarget(XRenderPicture *pic)
{
    s_scene_offscreenTargetStack.push(pic);
    ++s_renderOffscreen;
}

void xRenderPopTarget()
{
    s_scene_offscreenTargetStack.pop();
    --s_renderOffscreen;
    if (s_renderOffscreen < 0) {
        s_renderOffscreen = 0;
        qWarning("*** SOMETHING IS MESSED UP WITH YOUR xRenderPopTarget() USAGE ***");
    }
}

bool xRenderOffscreen()
{
    return s_renderOffscreen;
}

QPixmap *xRenderOffscreenTarget()
{
    return s_offscreenTarget;
}

} // namespace
Esempio n. 3
0
static void parse( Translator *tor )
{
    QString text;
    QString com;
    QString extracomment;

    yyCh = getChar();

    yyTok = getToken();
    while ( yyTok != Tok_Eof ) {
        switch ( yyTok ) {
        case Tok_class:
            yyTok = getToken();
            if(yyTok == Tok_Ident) {
                yyScope.push(new Scope(yyIdent, Scope::Clazz, yyLineNo));
            }
            else {
                qFatal( "%s:%d: Class must be followed by a classname",
                                          qPrintable(yyFileName), yyLineNo );
            }
            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() ) {
                qFatal( "%s:%d: Unbalanced right brace in Java code\n",
                        qPrintable(yyFileName), yyLineNo );
            }
            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:
                         qFatal( "%s:%d: Package keyword should be followed by com.package.name;",
                                          qPrintable(yyFileName), yyLineNo );
                         break;
                }
                yyTok = getToken();
            }
            break;

        default:
            yyTok = getToken();
        }
    }

    if ( !yyScope.isEmpty() )
        qFatal( "%s:%d: Unbalanced braces in Java code\n",
                 qPrintable(yyFileName), yyScope.top()->line );
    else if ( yyParenDepth != 0 )
        qFatal( "%s:%d: Unbalanced parentheses in Java code\n",
                 qPrintable(yyFileName), yyParenLineNo );
}
Esempio n. 4
0
void FlatTextarea::parseLinks() { // some code is duplicated in text.cpp!
	LinkRanges newLinks;

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

	initLinkSets();

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

		int32 domainOffset = m.capturedStart();

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

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

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

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

	if (newLinks != _links) {
		_links = newLinks;
		emit linksChanged();
	}
}
XRenderPicture *scene_xRenderOffscreenTarget()
{
    return s_scene_offscreenTargetStack.isEmpty() ? 0 : s_scene_offscreenTargetStack.top();
}
Esempio n. 6
0
XLIFFHandler::XliffContext XLIFFHandler::currentContext() const
{
    if (!m_contextStack.isEmpty())
        return (XliffContext)m_contextStack.top();
    return XC_xliff;
}
Esempio n. 7
0
bool KoEnhancedPathFormula::compile( const TokenList & tokens )
{
    // sanity check
    if( tokens.count() == 0 )
        return false;

    FormulaTokenStack syntaxStack;
    QStack<int> argStack;
    unsigned argCount = 1;

    for( int i = 0; i <= tokens.count(); i++ )
    {
        // helper token: InvalidOp is end-of-formula
        FormulaToken token =  ( i < tokens.count() ) ? tokens[i] : FormulaToken( FormulaToken::TypeOperator );
        FormulaToken::Type tokenType = token.type();

        // unknown token is invalid
        if( tokenType == FormulaToken::TypeUnknown )
            break;

        // for constants, push immediately to stack
        // generate code to load from a constant
        if( tokenType == FormulaToken::TypeNumber )
        {
            syntaxStack.push( token );
            m_constants.append( QVariant( token.asNumber() ) );
            m_codes.append( Opcode( Opcode::Load, m_constants.count()-1 ) );
        }
        // for identifier, push immediately to stack
        // generate code to load from reference
        if( tokenType == FormulaToken::TypeFunction || tokenType == FormulaToken::TypeReference )
        {
            syntaxStack.push( token );
            m_constants.append( QVariant( token.text() ) );
            m_codes.append( Opcode( Opcode::Ref, m_constants.count()-1 ) );
        }
        // are we entering a function ?
        // if token is operator, and stack already has: id ( arg
        if( tokenType == FormulaToken::TypeOperator && syntaxStack.itemCount() >= 3 )
        {
            FormulaToken arg = syntaxStack.top();
            FormulaToken par = syntaxStack.top( 1 );
            FormulaToken id = syntaxStack.top( 2 );
            if( !arg.isOperator() &&
                 par.asOperator() == FormulaToken::OperatorLeftPar &&
                 id.isFunction() )
            {
                argStack.push( argCount );
                argCount = 1;
            }
        }
        // for any other operator, try to apply all parsing rules
        if( tokenType == FormulaToken::TypeOperator )
        {
            // repeat until no more rule applies
            for( ; ; )
            {
                bool ruleFound = false;

                // rule for function arguments, if token is , or )
                // id ( arg1 , arg2 -> id ( arg
                if( !ruleFound )
                if( syntaxStack.itemCount() >= 5 )
                if( ( token.asOperator() == FormulaToken::OperatorRightPar ) ||
                    ( token.asOperator() == FormulaToken::OperatorComma ) )
                {
                    FormulaToken arg2 = syntaxStack.top();
                    FormulaToken sep = syntaxStack.top( 1 );
                    FormulaToken arg1 = syntaxStack.top( 2 );
                    FormulaToken par = syntaxStack.top( 3 );
                    FormulaToken id = syntaxStack.top( 4 );
                    if( !arg2.isOperator() )
                    if( sep.asOperator() == FormulaToken::OperatorComma )
                    if( !arg1.isOperator() )
                    if( par.asOperator() == FormulaToken::OperatorLeftPar )
                    if( id.isFunction() )
                    {
                        ruleFound = true;
                        syntaxStack.pop();
                        syntaxStack.pop();
                        argCount++;
                    }
                }
                // rule for function last argument:
                //  id ( arg ) -> arg
                if( !ruleFound )
                if( syntaxStack.itemCount() >= 4 )
                {
                    FormulaToken par2 = syntaxStack.top();
                    FormulaToken arg = syntaxStack.top( 1 );
                    FormulaToken par1 = syntaxStack.top( 2 );
                    FormulaToken id = syntaxStack.top( 3 );
                    if( par2.asOperator() == FormulaToken::OperatorRightPar )
                    if( !arg.isOperator() )
                    if( par1.asOperator() == FormulaToken::OperatorLeftPar )
                    if( id.isFunction() )
                    {
                        ruleFound = true;
                        syntaxStack.pop();
                        syntaxStack.pop();
                        syntaxStack.pop();
                        syntaxStack.pop();
                        syntaxStack.push( arg );
                        m_codes.append( Opcode( Opcode::Function, argCount ) );
                        argCount = argStack.empty() ? 0 : argStack.pop();
                    }
                }

                // rule for parenthesis:  ( Y ) -> Y
                if( !ruleFound )
                if( syntaxStack.itemCount() >= 3 )
                {
                    FormulaToken right = syntaxStack.top();
                    FormulaToken y = syntaxStack.top( 1 );
                    FormulaToken left = syntaxStack.top( 2 );
                    if( right.isOperator() )
                    if( !y.isOperator() )
                    if( left.isOperator() )
                    if( right.asOperator() == FormulaToken::OperatorRightPar )
                    if( left.asOperator() == FormulaToken::OperatorLeftPar )
                    {
                        ruleFound = true;
                        syntaxStack.pop();
                        syntaxStack.pop();
                        syntaxStack.pop();
                        syntaxStack.push( y );
                    }
                }

                // rule for binary operator:  A (op) B -> A
                // conditions: precedence of op >= precedence of token
                // action: push (op) to result
                // e.g. "A * B" becomes 'A' if token is operator '+'
                if( !ruleFound )
                if( syntaxStack.itemCount() >= 3 )
                {
                    FormulaToken b = syntaxStack.top();
                    FormulaToken op = syntaxStack.top( 1 );
                    FormulaToken a = syntaxStack.top( 2 );
                    if( !a.isOperator() )
                    if( !b.isOperator() )
                    if( op.isOperator() )
                    if( token.asOperator() != FormulaToken::OperatorLeftPar )
                    if( opPrecedence( op.asOperator() ) >= opPrecedence( token.asOperator() ) )
                    {
                        ruleFound = true;
                        syntaxStack.pop();
                        syntaxStack.pop();
                        syntaxStack.pop();
                        syntaxStack.push( b );
                        switch( op.asOperator() )
                        {
                            // simple binary operations
                            case FormulaToken::OperatorAdd: m_codes.append( Opcode::Add ); break;
                            case FormulaToken::OperatorSub: m_codes.append( Opcode::Sub ); break;
                            case FormulaToken::OperatorMul: m_codes.append( Opcode::Mul ); break;
                            case FormulaToken::OperatorDiv: m_codes.append( Opcode::Div ); break;
                            default: break;
                        };
                    }
                }

                // rule for unary operator:  (op1) (op2) X -> (op1) X
                // conditions: op2 is unary, token is not '('
                // action: push (op2) to result
                // e.g.  "* - 2" becomes '*'
                if( !ruleFound )
                if( token.asOperator() != FormulaToken::OperatorLeftPar )
                if( syntaxStack.itemCount() >= 3 )
                {
                    FormulaToken x = syntaxStack.top();
                    FormulaToken op2 = syntaxStack.top( 1 );
                    FormulaToken op1 = syntaxStack.top( 2 );
                    if( !x.isOperator() )
                    if( op1.isOperator() )
                    if( op2.isOperator() )
                    if( ( op2.asOperator() == FormulaToken::OperatorAdd ) ||
                    ( op2.asOperator() == FormulaToken::OperatorSub ) )
                    {
                        ruleFound = true;
                        syntaxStack.pop();
                        syntaxStack.pop();
                        syntaxStack.push( x );
                        if( op2.asOperator() == FormulaToken::OperatorSub )
                            m_codes.append( Opcode( Opcode::Neg ) );
                    }
                }

                // auxiliary rule for unary operator:  (op) X -> X
                // conditions: op is unary, op is first in syntax stack, token is not '('
                // action: push (op) to result
                if( !ruleFound )
                if( token.asOperator() != FormulaToken::OperatorLeftPar )
                if( syntaxStack.itemCount() == 2 )
                {
                    FormulaToken x = syntaxStack.top();
                    FormulaToken op = syntaxStack.top( 1 );
                    if( !x.isOperator() )
                    if( op.isOperator() )
                    if( ( op.asOperator() == FormulaToken::OperatorAdd ) ||
                    ( op.asOperator() == FormulaToken::OperatorSub ) )
                    {
                        ruleFound = true;
                        syntaxStack.pop();
                        syntaxStack.pop();
                        syntaxStack.push( x );
                        if( op.asOperator() == FormulaToken::OperatorSub )
                            m_codes.append( Opcode( Opcode::Neg ) );
                    }
                }

                if( !ruleFound )
                    break;
            }

            syntaxStack.push( token );
        }
    }

    // syntaxStack must left only one operand and end-of-formula (i.e. InvalidOp)
    m_valid = false;
    if( syntaxStack.itemCount() == 2 )
    if( syntaxStack.top().isOperator() )
    if( syntaxStack.top().asOperator() == FormulaToken::OperatorInvalid )
    if( !syntaxStack.top(1).isOperator() )
        m_valid = true;

    // bad parsing ? clean-up everything
    if( ! m_valid )
    {
        m_constants.clear();
        m_codes.clear();
        kWarning() << "compiling of "<< m_text << " failed";
    }

    return m_valid;
}
void EditStringCell::setPreviewText()
{
    ui.stringPreview->clear();

    // text is white by default + stupid HTML with its newlines and spaces
    QString text = colorStrings.at(1) + ui.stringEdit->toPlainText().replace('<', "&lt;").replace('>', "&gt;").replace('\n', "<br>");
    int emptyMatchIndex;
    QRegExp emptyRe(" {2,}");
    while ((emptyMatchIndex = emptyRe.indexIn(text)) != -1)
    {
        int matchedLength = emptyRe.matchedLength();
        text.replace(emptyMatchIndex, matchedLength, QString("&nbsp;").repeated(matchedLength));
    }

    if (ui.reversePreviewTextCheckBox->isChecked())
    {
        QList<QPair<int, int> > colorStringsIndeces; // <index_of_color_string_in_array, position_in_string>
        for (int i = 0; i < colors.size(); i++)
        {
            QString colorString = colorStrings.at(i + 1);
            int occurencesCount = text.count(colorString), position = 0, length = colorString.length();
            for (int j = 0; j < occurencesCount; j++, position += length)
            {
                position = text.indexOf(colorString, position);
                colorStringsIndeces.append(qMakePair(i + 1, position));
            }
        }

        // sort colorStringsIndeces by position in ascending order
        qSort(colorStringsIndeces.begin(), colorStringsIndeces.end(), colorStringsIndecesLessThan);

        QStack<QString> colorStringsStack;
        for (int i = 0, colorsNumberInString = colorStringsIndeces.size(); i < colorsNumberInString; i++)
        {
            int index = colorStringsIndeces.at(i).first;
            int position = colorStringsIndeces.at(i).second + colorStrings.at(index).length(); // skip colorString
            QString coloredText = text.mid(position, i != colorsNumberInString - 1 ? colorStringsIndeces.at(i + 1).second - position : -1);

            QStringList lines = coloredText.split("<br>");
            std::reverse(lines.begin(), lines.end());
            QString reversedText = lines.join("<br>");
            if (!reversedText.isEmpty())
                colorStringsStack.push(QString("<font color = \"%1\">%2</font>").arg(colorHexString(colors.at(index - 1)), reversedText));
        }

        // empty the stack
        while (!colorStringsStack.isEmpty())
            ui.stringPreview->insertHtml(colorStringsStack.pop());
    }
    else
    {
        for (int i = 0; i < colors.size(); i++) // replace color codes with their hex values for HTML
            text.replace(colorStrings.at(i + 1), QString("</font><font color = \"%1\">").arg(colorHexString(colors.at(i))));
        ui.stringPreview->setHtml(text);
    }

    int length = ui.stringPreview->toPlainText().length();
    ui.charsPreviewCountLabel->setText(QString::number(length));

	// show warning only once
	static bool showWarning = true;
	if (showWarning)
	{
		showWarning = false;

        const int kMaxLengthPatch110 = 255;
		if (length > kMaxLengthPatch110)
			emit maxLengthExceededFor110(tr("Patch 1.10 has limitation of %1 characters per string").arg(kMaxLengthPatch110));
	}
}
Esempio n. 9
0
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();

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

    /* 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.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 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;
            }

            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
                // these 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);
    }
Esempio n. 10
0
bool OsmAnd::RoutingConfiguration::parseConfiguration( QIODevice* data, RoutingConfiguration& outConfig )
{
    QXmlStreamReader xmlReader(data);

    std::shared_ptr<RoutingProfile> routingProfile;
    auto rulesetType = RoutingRuleset::Type::Invalid;
    QStack< std::shared_ptr<RoutingRule> > ruleset;
    while (!xmlReader.atEnd() && !xmlReader.hasError())
    {
        xmlReader.readNext();
        const auto tagName = xmlReader.name();
        if (xmlReader.isStartElement())
        {
            if (tagName == "osmand_routing_config")
            {
                outConfig._defaultRoutingProfileName = xmlReader.attributes().value("defaultProfile").toString();
            }
            else if (tagName == "routingProfile")
            {
                routingProfile.reset(new RoutingProfile());
                parseRoutingProfile(&xmlReader, routingProfile.get());
                if(routingProfile->_name == outConfig._defaultRoutingProfileName)
                    outConfig._defaultRoutingProfile = routingProfile;
                outConfig._routingProfiles.insert(routingProfile->_name, routingProfile);
            }
            else if (tagName == "attribute")
            {
                auto name = xmlReader.attributes().value("name").toString();
                auto value = xmlReader.attributes().value("value").toString();
                if(routingProfile)
                    routingProfile->addAttribute(name, value);
                else
                    outConfig._attributes.insert(name, value);
            }
            else if (tagName == "parameter")
            {
                if(!routingProfile)
                {
                    LogPrintf(LogSeverityLevel::Warning, "<parameter> is not inside <routingProfile> (%d, %d)", xmlReader.lineNumber(), xmlReader.columnNumber());
                    return false;
                }
                parseRoutingParameter(&xmlReader, routingProfile.get());
            }
            else if (tagName == "point" || tagName == "way")
            {
                assert(rulesetType == RoutingRuleset::Type::Invalid);
                auto attributeName = xmlReader.attributes().value("attribute");
                if (attributeName == "priority")
                    rulesetType = RoutingRuleset::Type::RoadPriorities;
                else if (attributeName == "speed")
                    rulesetType = RoutingRuleset::Type::RoadSpeed;
                else if (attributeName == "access")
                    rulesetType = RoutingRuleset::Type::Access;
                else if (attributeName == "obstacle_time")
                    rulesetType = RoutingRuleset::Type::Obstacles;
                else if (attributeName == "obstacle")
                    rulesetType = RoutingRuleset::Type::RoutingObstacles;
                else if (attributeName == "oneway")
                    rulesetType = RoutingRuleset::Type::OneWay;

                OSMAND_ASSERT(rulesetType != RoutingRuleset::Type::Invalid, QString("Route data object attribute '%1' is unknown").arg(attributeName.toString()));
            }
            else if(rulesetType != RoutingRuleset::Type::Invalid)
            {
                if(isConditionTag(tagName))
                    parseRoutingRuleset(&xmlReader, routingProfile.get(), rulesetType, ruleset);
            }
        }
        else if (xmlReader.isEndElement())
        {
            if(tagName == "routingProfile")
            {
                routingProfile.reset();
            }
            else if (tagName == "point" || tagName == "way")
            {
                rulesetType = RoutingRuleset::Type::Invalid;
            }
            else if(isConditionTag(tagName))
            {
                ruleset.pop();
            }
        }
    }
    if(xmlReader.hasError())
    {
        LogPrintf(LogSeverityLevel::Warning, "XML error: %s (%d, %d)", qPrintable(xmlReader.errorString()), xmlReader.lineNumber(), xmlReader.columnNumber());
        return false;
    }

    return true;
}
Esempio n. 11
0
// 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;
}
Esempio n. 12
0
LensDialog::LensDialog(QWidget* parent, ScribusDoc *doc) : QDialog(parent)
{
	setupUi(this);
	buttonRemove->setEnabled(false);
	setModal(true);
	buttonZoomOut->setIcon(QIcon(loadIcon("16/zoom-out.png")));
	buttonZoomI->setIcon(QIcon(loadIcon("16/zoom-in.png")));

	PageItem *currItem;
	double gx, gy, gh, gw;
	doc->m_Selection->setGroupRect();
	doc->m_Selection->getGroupRect(&gx, &gy, &gw, &gh);
	uint selectedItemCount = doc->m_Selection->count();
	QStack<PageItem*> groupStack;
	QStack<QGraphicsPathItem*> groupStack2;
	QStack<PageItem*> groupStack3;
	groupStack2.push(0);
	for (uint i = 0; i < selectedItemCount; ++i)
	{
		currItem = doc->m_Selection->itemAt(i);
		FPointArray path = currItem->PoLine;
		QPainterPath pp;
		if (currItem->itemType() == PageItem::PolyLine)
			pp = path.toQPainterPath(false);
		else
			pp = path.toQPainterPath(true);
		origPath.append(pp);
		QGraphicsPathItem* pItem = new QGraphicsPathItem(pp, groupStack2.top());
		if (groupStack2.top() == 0)
		{
			scene.addItem(pItem);
			pItem->setPos(currItem->xPos() - gx, currItem->yPos() - gy);
			pItem->rotate(currItem->rotation());
		}
		else
		{
			PageItem* parent = groupStack3.top();
			QMatrix mm;
			mm.rotate(-parent->rotation());
			mm.translate(-parent->xPos(), -parent->yPos());
			pItem->setPos(mm.map(QPointF(currItem->xPos(), currItem->yPos())));
		}
		pItem->setZValue(i);
		origPathItem.append(pItem);
		if (((currItem->fillColor() == CommonStrings::None) && (currItem->GrType == 0)) || (currItem->controlsGroup()))
			pItem->setBrush(Qt::NoBrush);
		else
		{
			if (currItem->GrType != 0)
			{
				if (currItem->GrType != 8)
				{
					QGradient pat;
					double x1 = currItem->GrStartX;
					double y1 = currItem->GrStartY;
					double x2 = currItem->GrEndX;
					double y2 = currItem->GrEndY;
					switch (currItem->GrType)
					{
						case 1:
						case 2:
						case 3:
						case 4:
						case 6:
							pat = QLinearGradient(x1, y1,  x2, y2);
							break;
						case 5:
						case 7:
							pat = QRadialGradient(x1, y1, sqrt(pow(x2 - x1, 2) + pow(y2 - y1,2)), x1, y1);
							break;
					}
					QList<VColorStop*> colorStops = currItem->fill_gradient.colorStops();
					QColor qStopColor;
					for( int offset = 0 ; offset < colorStops.count() ; offset++ )
					{
						qStopColor = colorStops[ offset ]->color;
						int h, s, v, sneu, vneu;
						int shad = colorStops[offset]->shade;
						qStopColor.getHsv(&h, &s, &v);
						sneu = s * shad / 100;
						vneu = 255 - ((255 - v) * shad / 100);
						qStopColor.setHsv(h, sneu, vneu);
						qStopColor.setAlphaF(colorStops[offset]->opacity);
						pat.setColorAt(colorStops[ offset ]->rampPoint, qStopColor);
					}
					pItem->setBrush(pat);
				}
				else if ((currItem->GrType == 8) && (!currItem->pattern().isEmpty()) && (doc->docPatterns.contains(currItem->pattern())))
				{
					double patternScaleX, patternScaleY, patternOffsetX, patternOffsetY, patternRotation;
					currItem->patternTransform(patternScaleX, patternScaleY, patternOffsetX, patternOffsetY, patternRotation);
					QMatrix qmatrix;
					qmatrix.translate(patternOffsetX, patternOffsetY);
					qmatrix.rotate(patternRotation);
					qmatrix.scale(patternScaleX / 100.0, patternScaleY / 100.0);
					QImage pat = *doc->docPatterns[currItem->pattern()].getPattern();
					QBrush brush = QBrush(pat);
					brush.setMatrix(qmatrix);
					pItem->setBrush(brush);
				}
			}
			else
			{
				QColor paint = ScColorEngine::getShadeColorProof(doc->PageColors[currItem->fillColor()], doc, currItem->fillShade());
				paint.setAlphaF(1.0 - currItem->fillTransparency());
				pItem->setBrush(paint);
			}
		}
		if ((currItem->lineColor() == CommonStrings::None) || (currItem->controlsGroup()))
			pItem->setPen(Qt::NoPen);
		else
		{
			QColor paint = ScColorEngine::getShadeColorProof(doc->PageColors[currItem->lineColor()], doc, currItem->lineShade());
			paint.setAlphaF(1.0 - currItem->lineTransparency());
			pItem->setPen(QPen(paint, currItem->lineWidth(), currItem->lineStyle(), currItem->lineEnd(), currItem->lineJoin()));
		}
		if (currItem->controlsGroup())
		{
			groupStack.push(currItem->groupsLastItem);
			groupStack2.push(pItem);
			groupStack3.push(currItem);
			pItem->setFlags(QGraphicsItem::ItemClipsChildrenToShape);
		}
		if (groupStack.count() != 0)
		{
			while (currItem == groupStack.top())
			{
				groupStack3.pop();
				groupStack2.pop();
				groupStack.pop();
				if (groupStack.count() == 0)
					break;
			}
		}
	}

	previewWidget->setRenderHint(QPainter::Antialiasing);
	previewWidget->setScene(&scene);
	isFirst = true;
	addLens();
	connect(spinXPos, SIGNAL(valueChanged(double)), this, SLOT(setNewLensX(double)));
	connect(spinYPos, SIGNAL(valueChanged(double)), this, SLOT(setNewLensY(double)));
	connect(spinRadius, SIGNAL(valueChanged(double)), this, SLOT(setNewLensRadius(double)));
	connect(spinStrength, SIGNAL(valueChanged(double)), this, SLOT(setNewLensStrength(double)));
	connect(buttonAdd, SIGNAL(clicked()), this, SLOT(addLens()));
	connect(buttonRemove, SIGNAL(clicked()), this, SLOT(removeLens()));
	connect(buttonMagnify, SIGNAL(toggled(bool)), this, SLOT(changeLens()));
	connect(buttonZoomI, SIGNAL(clicked()), this, SLOT(doZoomIn()));
	connect(buttonZoomOut, SIGNAL(clicked()), this, SLOT(doZoomOut()));
	connect(buttonBox, SIGNAL(accepted()), this, SLOT(accept()));
	connect(buttonBox, SIGNAL(rejected()), this, SLOT(reject()));
	connect(&scene, SIGNAL(selectionChanged()), this, SLOT(selectionHasChanged()));
}
Esempio n. 13
0
Profile::Ptr ProfileManager::loadProfile(const QString& shortPath)
{
    // the fallback profile has a 'special' path name, "FALLBACK/"
    if (shortPath == _fallbackProfile->path())
        return _fallbackProfile;

    QString path = shortPath;

    // add a suggested suffix and relative prefix if missing
    QFileInfo fileInfo(path);

    if (fileInfo.isDir())
        return Profile::Ptr();

    if (fileInfo.suffix() != QLatin1String("profile"))
        path.append(".profile");
    if (fileInfo.path().isEmpty() || fileInfo.path() == QLatin1String("."))
        path.prepend(QLatin1String("konsole") + QDir::separator());

    // if the file is not an absolute path, look it up
    if (!fileInfo.isAbsolute())
        path = QStandardPaths::locate(QStandardPaths::GenericDataLocation, path);

    // if the file is not found, return immediately
    if (path.isEmpty()) {
        return Profile::Ptr();
    }

    // check that we have not already loaded this profile
    foreach(const Profile::Ptr& profile, _profiles) {
        if (profile->path() == path)
            return profile;
    }

    // guard to prevent problems if a profile specifies itself as its parent
    // or if there is recursion in the "inheritance" chain
    // (eg. two profiles, A and B, specifying each other as their parents)
    static QStack<QString> recursionGuard;
    PopStackOnExit<QString> popGuardOnExit(recursionGuard);

    if (recursionGuard.contains(path)) {
        qWarning() << "Ignoring attempt to load profile recursively from" << path;
        return _fallbackProfile;
    } else {
        recursionGuard.push(path);
    }

    // load the profile
    ProfileReader* reader = new KDE4ProfileReader;

    Profile::Ptr newProfile = Profile::Ptr(new Profile(fallbackProfile()));
    newProfile->setProperty(Profile::Path, path);

    QString parentProfilePath;
    bool result = reader->readProfile(path, newProfile, parentProfilePath);

    if (!parentProfilePath.isEmpty()) {
        Profile::Ptr parentProfile = loadProfile(parentProfilePath);
        newProfile->setParent(parentProfile);
    }

    delete reader;

    if (!result) {
        qWarning() << "Could not load profile from " << path;
        return Profile::Ptr();
    } else {
        addProfile(newProfile);
        return newProfile;
    }
}
Esempio n. 14
0
void MessageLinksParser::parse() {
	const auto &textWithTags = _field->getTextWithTags();
	const auto &text = textWithTags.text;
	const auto &tags = textWithTags.tags;
	const auto &markdownTags = _field->getMarkdownTags();
	if (text.isEmpty()) {
		_list = QStringList();
		return;
	}

	auto ranges = QVector<LinkRange>();

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

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

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

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

		auto domainOffset = m.capturedStart();

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

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

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

	apply(text, ranges);
}
Esempio n. 15
0
void Highlighter::iterateThroughRules(const QString &text,
                                      const int length,
                                      ProgressData *progress,
                                      const bool childRule,
                                      const QList<QSharedPointer<Rule> > &rules)
{
    typedef QList<QSharedPointer<Rule> >::const_iterator RuleIterator;

    bool contextChanged = false;
    bool atLeastOneMatch = false;

    RuleIterator it = rules.begin();
    RuleIterator endIt = rules.end();
    bool detlaDeptn = false;
    while (it != endIt && progress->offset() < length) {
        int startOffset = progress->offset();
        const QSharedPointer<Rule> &rule = *it;

        if (rule->itemData() == "String" ||
                rule->itemData() == "Comment") {
            m_stringOrComment = true;
        } else {
            m_stringOrComment = false;
        }

        if (rule->matchSucceed(text, length, progress)) {
            atLeastOneMatch = true;
            if (!m_stringOrComment) {
                if (!rule->beginRegion().isEmpty()) {
                    QChar ch = text.at(startOffset);
                    if (ch == '{' || ch == '(' || ch == '[' ) {
                        blockData(currentBlockUserData())->appendParenthese(Parenthesis(Parenthesis::Opened,ch,startOffset));
                    }
                }
                if (!rule->endRegion().isEmpty()) {
                    QChar ch = text.at(startOffset);
                    if (ch == '}' || ch == ')' || ch == ']' ) {
                        blockData(currentBlockUserData())->appendParenthese(Parenthesis(Parenthesis::Closed,ch,startOffset));
                    }
                }
            }

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

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

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

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

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

    if (!childRule && !atLeastOneMatch) {
        if (m_currentContext->isFallthrough()) {
            handleContextChange(m_currentContext->fallthroughContext(),
                                m_currentContext->definition());
            iterateThroughRules(text, length, progress, false, m_currentContext->rules());
        } else {
            applyFormat(progress->offset(), 1, m_currentContext->itemData(),
                        m_currentContext->definition());
            if (progress->isOnlySpacesSoFar() && !text.at(progress->offset()).isSpace())
                progress->setOnlySpacesSoFar(false);
            progress->incrementOffset();
        }
    }
    if (detlaDeptn && m_lastRegionDepth == m_regionDepth) {
        blockData(currentBlockUserData())->m_foldingIndentDelta--;
    }
}
Esempio n. 16
0
void ScCodeEditor::indent( const QTextCursor & selection, EditBlockMode editBlockMode )
{
    if (selection.isNull())
        return;

    QTextCursor cursor(selection);

    if (editBlockMode == NewEditBlock)
        cursor.beginEditBlock();
    else
        cursor.joinPreviousEditBlock();

    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 global_level = 0;
    int blockNum = 0;
    bool in_string = false;
    QTextBlock block = QPlainTextEdit::document()->begin();
    while (block.isValid())
    {
        int initialStackSize = stack.size();
        int level = 0;
        bool block_start_in_string = in_string;

        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;
                    break;

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

                case Token::StringMark:
                    in_string = !in_string;
                    break;

                default:
                    break;
                }
            }
        }

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

        if(blockNum == endBlockNum)
            break;

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

        if (level) {
            global_level += level;
            stack.push(global_level);
        }
    }

    cursor.endEditBlock();
}
Esempio n. 17
0
void XLIFFHandler::pushContext(XliffContext ctx)
{
    m_contextStack.push_back(ctx);
}
void RecursiveDirJobHelper::recursiveCpDir(const QString & sourcePath, const QString & destPath,
                                            RecursiveDirJob::CopyOptions options)
{
    QDir source(sourcePath);
    if ( !source.exists() ) {
        emit errorOccured(Error(Error::NoSuchFileOrDirectory, sourcePath));
        return;
    }

    QDir dest(destPath);
    if ( dest.exists() ) {
        if ( options & RecursiveDirJob::RemoveDestination ) {
            //in case the destination is a symlink to another directory, we remove first
            //the symlink target (returned by dest.canonicalPath()) and then the symlink itself.
            recursiveRmDir(dest.canonicalPath());
            if ( QFileInfo(destPath).isSymLink() ) {
                QFile::remove(destPath);
            }
        } else if ( !(options & RecursiveDirJob::OverWrite) ) {
            emit errorOccured(Error(Error::FileOrDirectoryExists, destPath));
            return;
        }
    }

    if ( dest.mkdir(dest.absolutePath()) ) {
        QFile::setPermissions(destPath, QFile::permissions(sourcePath));
    }

    QFileInfoList currentList = source.entryInfoList(dirFilters);
    QFileInfo currentItem;
    QStack<QFileInfoList> stack;
    QString currentName;
    quint64 bytesCopied = 0;

    if ( m_reportProgress ) {
        quint64 dirSize = calculateDirSize(sourcePath);
        emit setLabelText(tr("Copying files from \"%1\" to \"%2\"...").arg(sourcePath).arg(destPath));
        if (dirSize > 0) {
            emit setMaximum(dirSize);
            //the directory special file is already (almost) copied in dest.mkdir() above
            bytesCopied += stat_size(sourcePath);
            emit setValue(bytesCopied);
        } else {
            //no files to be copied, so set the progressbar to 100%
            emit setMaximum(1);
            emit setValue(1);
        }
    }

    while(1)
    {
        if ( !currentList.isEmpty() )
        {
            currentItem = currentList.takeFirst();
            currentName = currentItem.fileName();

            if ( currentItem.isSymLink() )
            {
                if ( options & RecursiveDirJob::OverWrite ) {
                    if ( !QFile::remove(dest.absoluteFilePath(currentName)) )
                        emit errorOccured(Error(Error::RmFail, dest.absoluteFilePath(currentName)));
                }
                if ( !QFile::link( DirOperations::relativeSymLinkTarget(source.absoluteFilePath(currentName)),
                                    dest.absoluteFilePath(currentName) ) )
                    emit errorOccured(Error(Error::CopyFail, source.absoluteFilePath(currentName)));
            }
            else if ( currentItem.isDir() )
            {
                bool ok = false;
                QFile::Permissions sourcePermissions = QFile::permissions(source.absoluteFilePath(currentName));

                if ( !(ok = source.cd(currentName)) ) {
                    emit errorOccured(Error(Error::AccessDenied, source.absoluteFilePath(currentName)));
                }
                if ( ok && !dest.cd(currentName) ) {
                    //if the target dir doesn't exist, create it and try again.
                    if ( !dest.mkdir(currentName) ) {
                        emit errorOccured(Error(Error::MkdirFail, dest.absoluteFilePath(currentName)));
                    }

                    //preserve permissions of the directory
                    QFile::setPermissions(dest.absoluteFilePath(currentName), sourcePermissions);

                    if ( !dest.cd(currentName) ) {
                         //quite impossible to happen
                        emit errorOccured(Error(Error::AccessDenied, dest.absoluteFilePath(currentName)));
                        ok = false;
                        source.cdUp(); //revert the state of source, as we are not going to copy this dir.
                    }
                }

                if (ok) {
                    stack.push(currentList);
                    currentList = source.entryInfoList(dirFilters);
                }
            }
            else if ( currentItem.isFile() )
            {
                if ( options & RecursiveDirJob::OverWrite ) {
                    if ( !QFile::remove(dest.absoluteFilePath(currentName)) )
                        emit errorOccured(Error(Error::RmFail, dest.absoluteFilePath(currentName)));
                }
                if ( !internal_copy( source.absoluteFilePath(currentName), dest.absoluteFilePath(currentName),
                                        options & RecursiveDirJob::ReplaceKde4InFiles ) )
                    emit errorOccured(Error(Error::CopyFail, source.absoluteFilePath(currentName)));
            }
            else
            {
                if ( currentItem.exists() ) {
                    qDebug() << "Ignoring special file" << source.absoluteFilePath(currentName);
                } else {
                    //this can happen with filename encoding bugs
                    emit errorOccured(Error(Error::NoSuchFileOrDirectory, source.absoluteFilePath(currentName)));
                }
            }

            if ( m_reportProgress ) {
                bytesCopied += stat_size(currentItem.absoluteFilePath());
                emit setValue(bytesCopied);
            }
        }
        else // list is empty
        {
            if ( !stack.isEmpty() )
            {
                currentList = stack.pop();
                source.cdUp();
                dest.cdUp();
            }
            else
                break;
        }
    }
}
Esempio n. 19
0
qreal KoEnhancedPathFormula::evaluate()
{
    // shortcut
    if( m_error != ErrorNone )
        return 0.0;

    // lazy evaluation
    if( ! m_compiled )
    {
        TokenList tokens = scan( m_text );
        if( m_error != ErrorNone )
            debugTokens( tokens );
        if( ! compile( tokens ) )
        {
            debugOpcodes();
            m_error = ErrorCompile;
            return false;
        }
        m_compiled = true;
    }

    QStack<QVariant> stack;
    int index = 0;

    if( ! m_valid )
    {
        m_error = ErrorParse;
        return 0.0;
    }

    for( int pc = 0; pc < m_codes.count(); pc++ )
    {
        QVariant ret;   // for the function caller
        Opcode& opcode = m_codes[pc];
        index = opcode.index;
        switch( opcode.type )
        {
            // no operation
            case Opcode::Nop:
            break;

            // load a constant, push to stack
            case Opcode::Load:
                stack.push( m_constants[index] );
            break;

            // unary operation
            case Opcode::Neg:
            {
                bool success = false;
                qreal value = stack.pop().toDouble( &success );
                if( success ) // do nothing if we got an error
                    value *= -1.0;
                stack.push( QVariant( value ) );
            }
            break;

            // binary operation: take two values from stack, do the operation,
            // push the result to stack
            case Opcode::Add:
            {
                qreal val2 = stack.pop().toDouble();
                qreal val1 = stack.pop().toDouble();
                stack.push( QVariant( val1 + val2 ) );
            }
            break;

            case Opcode::Sub:
            {
                qreal val2 = stack.pop().toDouble();
                qreal val1 = stack.pop().toDouble();
                stack.push( QVariant( val1 - val2 ) );
            }
            break;

            case Opcode::Mul:
            {
                qreal val2 = stack.pop().toDouble();
                qreal val1 = stack.pop().toDouble();
                stack.push( QVariant( val1 * val2 ) );
            }
            break;

            case Opcode::Div:
            {
                qreal val2 = stack.pop().toDouble();
                qreal val1 = stack.pop().toDouble();
                stack.push( QVariant( val1 / val2 ) );
            }
            break;

        case Opcode::Ref:
        {
            QString reference = m_constants[index].toString();
            // push function name if it is a function, else push evaluated reference
            Function function = matchFunction( reference );
            if( FunctionUnknown == function )
                stack.push( QVariant( m_parent->evaluateReference( reference ) ) );
            else
                stack.push( function );
        }
        break;

        // calling function
        case Opcode::Function:
        {
            // sanity check, this should not happen unless opcode is wrong
            // (i.e. there's a bug in the compile() function)
            if( stack.count() < index )
            {
                kWarning() << "not enough arguments for function " << m_text;
                m_error = ErrorValue; // not enough arguments
                return 0.0;
            }

            /// prepare function arguments
            QList<qreal> args;
            for( ; index; index-- )
            {
                qreal value = stack.pop().toDouble();
                args.push_front( value );
            }

            // function identifier as int value
            int function = stack.pop().toInt();
            stack.push( QVariant( evaluateFunction( (Function)function, args ) ) );
        }
        break;

        default:
        break;
        }
    }

    // more than one value in stack ? unsuccessful execution...
    if( stack.count() != 1 )
    {
        m_error = ErrorValue;
        return 0.0;
    }

    return stack.pop().toDouble();
}
void RecursiveDirJobHelper::recursiveRmDir(const QString & dir)
{
    QDir currentDir(dir);
    if ( !currentDir.exists() ) {
        qWarning() << "recursiveRmDir: trying to remove non-existent directory" << dir;
        if (m_reportProgress) {
            //no files to be removed, so set the progressbar to 100%
            emit setMaximum(1);
            emit setValue(1);
        }
        return; // directory gone, no work to do
    }

    QFileInfoList currentList = currentDir.entryInfoList(dirFilters);
    QFileInfo currentItem;
    QStack<QFileInfoList> stack;
    quint64 bytesRemoved = 0;

    if (m_reportProgress) {
        quint64 dirSize = calculateDirSize(dir);
        emit setLabelText(tr("Removing directory \"%1\"...").arg(dir));
        if (dirSize > 0) {
            emit setMaximum(dirSize);
            //start with the size of the directory to be removed.
            //we do this before starting removing files, because on some filesystems
            //(like reiserfs) the directory size is variable and will be smaller
            //when all files have been removed
            bytesRemoved += stat_size(dir);
            emit setValue(bytesRemoved);
        } else {
            //no files to be removed, so set the progressbar to 100%
            emit setMaximum(1);
            emit setValue(1);
        }
    }

    while(1)
    {
        if ( !currentList.isEmpty() ){
            currentItem = currentList.takeFirst();

            if ( m_reportProgress ) {
                bytesRemoved += stat_size(currentItem.absoluteFilePath());
                emit setValue(bytesRemoved);
            }

            if ( currentItem.isDir() && !currentItem.isSymLink() )
            {
                if ( !currentDir.cd(currentItem.fileName()) ) {
                    emit errorOccured(Error(Error::AccessDenied, currentItem.absoluteFilePath()));
                } else {
                    stack.push(currentList);
                    currentList = currentDir.entryInfoList(dirFilters);
                }
            }
            else
            {
                if ( !currentDir.remove(currentItem.fileName()) )
                    emit errorOccured(Error(Error::RmFail, currentItem.absoluteFilePath()));
            }
        }
        else // list is empty
        {
            bool quit = false;
            if ( !stack.isEmpty() )
                currentList = stack.pop();
            else
                quit = true;

            //if quit == true, we remove the original dir itself, now that it is empty for sure...
            QString tmpname = currentDir.dirName();
            currentDir.cdUp();

            if ( !currentDir.rmdir(tmpname) )
                emit errorOccured(Error(Error::RmFail, currentDir.absoluteFilePath(tmpname)));

            if ( quit )
                break;
        }
    }
}
void QmlProfilerEventsModelProxy::loadData(qint64 rangeStart, qint64 rangeEnd)
{
    clear();

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

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

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

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

    for (int i = 0; i < eventList.size(); ++i) {
        const QmlProfilerDataModel::QmlEventData *event = &eventList[i];

        if (!d->acceptedTypes.contains((QmlDebug::QmlEventType)event->eventType))
            continue;

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

        // put event in hash
        QString hash = QmlProfilerDataModel::getHashString(*event);
        if (!d->data.contains(hash)) {
            QmlEventStats stats = {
                event->displayName,
                hash,
                event->data.join(QLatin1String(" ")),
                event->location,
                event->eventType,
                event->bindingType,
                event->duration,
                1, //calls
                event->duration, //minTime
                event->duration, // maxTime
                0, //timePerCall
                0, //percentOfTime
                0, //medianTime
                false //isBindingLoop
            };

            d->data.insert(hash, stats);

            // for median computing
            durations.insert(hash, QVector<qint64>());
            durations[hash].append(event->duration);
        } else {
            // update stats
            QmlEventStats *stats = &d->data[hash];

            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[hash].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().second;
        while (potentialParent
               && !(potentialParent->startTime + potentialParent->duration > event->startTime)) {
            callStack.pop();
            potentialParent = callStack.top().second;
        }

        // check whether event is already in stack
        bool inLoop = false;
        for (int ii = 1; ii < callStack.size(); ++ii) {
            if (callStack.at(ii).first == hash)
                inLoop = true;
            if (inLoop)
                d->eventsInBindingLoop.insert(hash);
        }


        CallStackEntry newEntry(hash, event);
        callStack.push(newEntry);

        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;
    foreach (const QString &hash, d->data.keys()) {
        QmlEventStats* stats = &d->data[hash];
        if (stats->calls > 0)
            stats->timePerCall = stats->duration / (double)stats->calls;

        QVector<qint64> eventDurations = durations.value(hash);
        if (!eventDurations.isEmpty()) {
            qSort(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 (const QString &eventHash, d->eventsInBindingLoop)
        d->data[eventHash].isBindingLoop = true;

    QString rootEventName = tr("<program>");
    QmlDebug::QmlEventLocation rootEventLocation(rootEventName, 1, 1);

    // insert root event
    QmlEventStats rootEvent = {
        rootEventName, //event.displayName,
        rootEventName, // hash
        tr("Main Program"), //event.details,
        rootEventLocation, // location
        (int)QmlDebug::Binding, // event type
        0, // binding type
        qmlTime + 1,
        1, //calls
        qmlTime + 1, //minTime
        qmlTime + 1, // maxTime
        qmlTime + 1, //timePerCall
        100.0, //percentOfTime
        qmlTime + 1, //medianTime;
        false
    };

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

    d->modelManager->modelProxyCountUpdated(d->modelId, 1, 1);
    emit dataAvailable();
}
Esempio n. 22
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();
    }
}
Esempio n. 23
0
void stackShow::In2Post(QStringList &phrase)
{
    static QStack <QString> stack;
    static QStringList result;
    QString r , q;


    QString l[6]={"+" , "-" , "*" , "/" , "(" , ")"};

    for (int i=0 ; i<phrase.size()  ; i++)
        for (int j=0 ; j<6 ; j++)
        {
            if ( phrase.at(i)!=l[j] && j==5 )
            {
                result.append(phrase.at(i));
                ui->lneRes->insert(phrase.at(i) + " ");
                phrase.removeFirst();
                r = phrase.join(" ");
                ui->lneExp->setText(r);
                return;
            }

            else if (phrase.at(i)==l[j])
            {

                if (stack.isEmpty() || phrase.at(i)=="(" || bozorgtarAz( phrase.at(i) , stack.top() ) )
                {
                    stack.push(phrase.at(i));
                    ui->lneStack->insert(phrase.at(i) + " ");
                    phrase.removeFirst();
                    r = phrase.join(" ");
                    ui->lneExp->setText(r);
                    return;
                }

                else if (phrase.at(i)==")")
                {
                    while (stack.top()!="(")
                    {
                        q=stack.pop();
                        result.append(q);
                        ui->lneRes->insert(q + " ");
                        q=ui->lneStack->text();
                        q.remove(q.size()-2,2);
                        ui->lneStack->setText(q);
                        return;
                    }

                    stack.pop();
                    q=ui->lneStack->text();
                    q.remove(q.size()-2,2);
                    ui->lneStack->setText(q);
                    phrase.removeFirst();
                    QString r = phrase.join(" ");
                    ui->lneExp->setText(r);
                    return;
                }

                else
                {
                    while (!stack.isEmpty() && !bozorgtarAz( phrase.at(i) , stack.top() ))
                    {
                        q=stack.pop();
                        result.append(q);
                        ui->lneRes->insert(q + " ");
                        q=ui->lneStack->text();
                        q.remove(q.size()-2,2);
                        ui->lneStack->setText(q);
                        return;
                    }
                }
                break;
            }
        }

    while (! stack.isEmpty())
    {
        q=stack.pop();
        result.append(q);
        ui->lneRes->insert(q + " ");
        q=ui->lneStack->text();
        q.remove(q.size()-2,2);
        ui->lneStack->setText(q);
        return;
    }

    ui->btnGo->setText("Close");
}
Esempio n. 24
0
 bool XMLContentHandler::startDocument()
 {
     status_stack.push(TOPLEVEL);
     return true;
 }
Esempio n. 25
0
void xRenderPushTarget(XRenderPicture *pic)
{
    s_scene_offscreenTargetStack.push(pic);
    ++s_renderOffscreen;
}
Esempio n. 26
0
 bool XMLContentHandler::endDocument()
 {
     status_stack.pop();
     return true;
 }
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();
}
Esempio n. 28
0
 bool XMLContentHandler::startElement(const QString &, const QString & localName, const QString &,
                                     const QXmlAttributes & )
 {
     tmp = "";
     switch (status_stack.top())
     {
     case TOPLEVEL:
         // from toplevel we can only go to root
         if (localName == "root")
             status_stack.push(ROOT);
         else
             return false;
         break;
     case ROOT:
         // from the root we can go to device or specVersion
         // we are not interested in the specVersion
         if (localName == "device")
             status_stack.push(DEVICE);
         else
             status_stack.push(OTHER);
         break;
     case DEVICE:
         // see if it is a field we are interested in
         if (interestingDeviceField(localName))
             status_stack.push(FIELD);
         else
             status_stack.push(OTHER);
         break;
     case SERVICE:
         if (interestingServiceField(localName))
             status_stack.push(FIELD);
         else
             status_stack.push(OTHER);
         break;
     case OTHER:
         if (localName == "service")
             status_stack.push(SERVICE);
         else if (localName == "device")
             status_stack.push(DEVICE);
         else
             status_stack.push(OTHER);
         break;
     case FIELD:
         break;
     }
     return true;
 }
void filterNetworkAccessModule::consolodateStacks()
{
    if(this->TopLevel.isEmpty())
    {
        //there is an erros, and it needs to be addressed.
        std::cerr << "ERROR: XML Parser: TopLevel not set" << std::endl;
        exit(1);
    }
    else
    {
        //strip the top level, consolodate text to its corrosponding name type

        //these stacks are used for stripping... after done, swap them back
        QStack<QXmlStreamReader::TokenType> tempTypeStack;
        QStack<QString> tempQnStack;
        QStack<QString> tempTextStack;

        //parse!
        while(!this->parseTypeStack.isEmpty())
        {
            QXmlStreamReader::TokenType tempType = this->parseTypeStack.pop();
            QString tempQn = this->parseQnStack.pop();
            QString tempText = this->parseTextStack.pop();

            //strip out everything we don't want, then consolodate text fields
            switch(tempType)
            {
            //strip out everything we don't want
            case QXmlStreamReader::EndElement:
            case QXmlStreamReader::Invalid:
            case QXmlStreamReader::StartDocument:
            case QXmlStreamReader::EndDocument:
                break;

                //handle the text cases
            case QXmlStreamReader::Characters:
                //process characters
                // std::cout << "Characters..." << std::endl;

                //this assumes that the first element is NOT a character element
                if(tempTextStack.isEmpty())
                {
                    //TODO: We will want to gracefully handle this in future so PV wont crash
                    std::cerr << "ERROR: While parsing XML, found ill-formed Character field" << std::endl;
                    exit(EXIT_FAILURE);
                }
                else
                {

                    //take off the previous
                    //   std::cout << "Poping off blank text from previous tag" << std::endl;
                    tempTextStack.pop();
                    tempTextStack.push(tempText);
                }

                break;

                //keep everything that we want
            default:
                // std::cout << "Everything else..." << std::endl;
                if(tempQn != this->TopLevel)
                {
                    //put everything (except the top level)
                    //TODO: see if we need to eliminate everythin UP TO and INCLUDING the toplevel
                    tempTypeStack.push(tempType);
                    tempQnStack.push(tempQn);
                    tempTextStack.push(tempText);
                }
                break;
            }

        }

        //let us swap the stacks
        this->parseQnStack.swap(tempQnStack);
        this->parseTypeStack.swap(tempTypeStack);
        this->parseTextStack.swap(tempTextStack);

        //remember the stack is upside down at this point

//        std::cout << "Parsing complete to stacks" << std::endl;
    }
}
	_class * readFromXML(QString fileXml) {
		_class *root = NULL;

		// init xml stream
		QFile file(fileXml);
		QXmlStreamReader xmlReader;
	
		//QString line;
		if ( !file.open(QIODevice::ReadOnly) )
			return false;
	
		{
			QTextStream t( &file );
			// stream.setCodec("CP-866");
			xmlReader.addData(t.readAll());
		}	
	
		// start reading
		QStack<_specXMLElement *> stackElements;
		while(!xmlReader.atEnd()) 
		{
			if(xmlReader.isCharacters() && stackElements.count() != 0)
			{
				_specXMLElement *pElemTop = stackElements.top();
				if(pElemTop->hasBody())
				  pElemTop->setBody(xmlReader.readElementText());
			}
		
			if(xmlReader.isStartElement())
			{ 
				QString strName = xmlReader.name().toString();
				_specXMLElement *elem = createElement(strName);
			
				_specXMLElement *parentElem = (stackElements.count() != 0) ? stackElements.top() : NULL;

				if(stackElements.count() == 0)
					root = (_class *)elem;
								
				if(parentElem != NULL)
					parentElem->addChildElement(strName,elem);

				stackElements.push(elem);
			
				for(int i = 0;  i < xmlReader.attributes().count(); i++)
				{
					QXmlStreamAttribute attr = xmlReader.attributes().at(i);
					elem->setAttribute(attr.name().toString(), attr.value().toString());
				}
			}
		
			if(xmlReader.isEndElement())
			{
				stackElements.pop();
			}
			xmlReader.readNext();		

		};
	
		if(xmlReader.hasError())
		{
			return NULL;
			// std::cout << xmlReader.errorString().toStdString();
		}
	
		return root;
	};