void QSvgTinyDocument::draw(QPainter *p, const QString &id, const QRectF &bounds) { QSvgNode *node = scopeNode(id); if (!node) { qDebug("Couldn't find node %s. Skipping rendering.", qPrintable(id)); return; } if (m_time.isNull()) { m_time.start(); } if (node->displayMode() == QSvgNode::NoneMode) return; p->save(); const QRectF elementBounds = node->transformedBounds(); mapSourceToTarget(p, bounds, elementBounds); QTransform originalTransform = p->worldTransform(); //XXX set default style on the painter QPen pen(Qt::NoBrush, 1, Qt::SolidLine, Qt::FlatCap, Qt::MiterJoin); pen.setMiterLimit(4); p->setPen(pen); p->setBrush(Qt::black); p->setRenderHint(QPainter::Antialiasing); p->setRenderHint(QPainter::SmoothPixmapTransform); QStack<QSvgNode*> parentApplyStack; QSvgNode *parent = node->parent(); while (parent) { parentApplyStack.push(parent); parent = parent->parent(); } for (int i = parentApplyStack.size() - 1; i >= 0; --i) parentApplyStack[i]->applyStyle(p, m_states); // Reset the world transform so that our parents don't affect // the position QTransform currentTransform = p->worldTransform(); p->setWorldTransform(originalTransform); node->draw(p, m_states); p->setWorldTransform(currentTransform); for (int i = 0; i < parentApplyStack.size(); ++i) parentApplyStack[i]->revertStyle(p, m_states); //p->fillRect(bounds.adjusted(-5, -5, 5, 5), QColor(0, 0, 255, 100)); p->restore(); }
int ScCodeEditor::indentationLevel(const QTextCursor & cursor) { QTextDocument *doc = QPlainTextEdit::document(); int startBlockNum = doc->findBlock(cursor.selectionStart()).blockNumber(); QStack<int> stack; int level = 0; int blockNum = 0; QTextBlock block = QPlainTextEdit::document()->begin(); while (block.isValid()) { if (level > 0) { stack.push(level); level = 0; } TextBlockData *data = static_cast<TextBlockData*>(block.userData()); if (data) { int count = data->tokens.size(); for (int idx = 0; idx < count; ++idx) { const Token & token = data->tokens[idx]; switch (token.type) { case Token::OpeningBracket: if (token.character != '(' || stack.size() || token.positionInBlock) level += 1; break; case Token::ClosingBracket: if (level) level -= 1; else if(!stack.isEmpty()) { stack.top() -= 1; if (stack.top() <= 0) stack.pop(); } break; default: ; } } } if (blockNum == startBlockNum) return stack.size(); block = block.next(); ++blockNum; } return -1; }
QString Calc(QString p) { QStack <QString> stack; QString temp , r1 , r2 , r3 ; QStringList phrase = p.split(" "); QString l[4]={"+" , "-" , "*" , "/" }; for (int i=0 ; i<phrase.size() ; i++) { for (int j=0 ; j<4 ; j++) { if (phrase.at(i)!= l[j] && j==3) stack.push(phrase.at(i)); else if (phrase.at(i)==l[j]) { if (stack.size()<2) return ""; r1=stack.pop(); r2=stack.pop(); stack.push(Ecal(r2 , r1 ,phrase.at(i))); break; } } } return stack.pop(); }
QString Post_to_Pre(QString p) { QStack <QString> stack; QStringList phrase=p.split(" "); QString r1,r2; QString l[4]={"+" , "-" , "*" , "/" }; for (int i=0; i<phrase.size(); i++) for (int j=0 ; j<4 ; j++) { if (phrase.at(i)!=l[j] && j==3) stack.push(phrase.at(i)); else if ( phrase.at(i)==l[j] ) { if (stack.size()<2) return ""; r1=stack.pop(); r2=stack.pop(); stack.push( phrase.at(i) + " " + r2 + " " + r1 ); break; } } return stack.top(); }
QRectF QSvgNode::transformedBounds() const { if (!m_cachedBounds.isEmpty()) return m_cachedBounds; QImage dummy(1, 1, QImage::Format_RGB32); QPainter p(&dummy); QSvgExtraStates states; QPen pen(Qt::NoBrush, 1, Qt::SolidLine, Qt::FlatCap, Qt::SvgMiterJoin); pen.setMiterLimit(4); p.setPen(pen); QStack<QSvgNode*> parentApplyStack; QSvgNode *parent = m_parent; while (parent) { parentApplyStack.push(parent); parent = parent->parent(); } for (int i = parentApplyStack.size() - 1; i >= 0; --i) parentApplyStack[i]->applyStyle(&p, states); p.setWorldTransform(QTransform()); m_cachedBounds = transformedBounds(&p, states); return m_cachedBounds; }
int ChannelsModel::getRowNumber(int find_channelid) const { if(m_rootchannelid == find_channelid) return 0; int row = 0; QStack<int> channels; channels.push(m_rootchannelid); while(channels.size()) { int channelid = channels.pop(); channels_t::const_iterator ite = m_channels.find(channelid); Q_ASSERT(ite != m_channels.end()); const subchannels_t& subs = ite.value(); subchannels_t::const_iterator sub_ite = subs.begin(); while(sub_ite != subs.end()) { row++; if(sub_ite->nChannelID == find_channelid) return row; channels.push(sub_ite->nChannelID); sub_ite++; } users_t::const_iterator p_ite = m_users.find(channelid); Q_ASSERT(p_ite != m_users.end()); const chanusers_t& users = p_ite.value(); row += users.size(); } return -1; }
void QmlProfilerRangeModel::findBindingLoops() { typedef QPair<int, int> CallStackEntry; QStack<CallStackEntry> callStack; for (int i = 0; i < count(); ++i) { int potentialParent = callStack.isEmpty() ? -1 : callStack.top().second; while (potentialParent != -1 && !(endTime(potentialParent) > startTime(i))) { callStack.pop(); potentialParent = callStack.isEmpty() ? -1 : callStack.top().second; } // check whether event is already in stack for (int ii = 0; ii < callStack.size(); ++ii) { if (callStack.at(ii).first == typeId(i)) { m_data[i].bindingLoopHead = callStack.at(ii).second; break; } } CallStackEntry newEntry(typeId(i), i); callStack.push(newEntry); } }
void PlotZoomer::zoom(int up) { // FIXME: Save the current zoom window in case it's been panned. int zoomIndex = zoomRectIndex(); if (zoomIndex > 0) { QStack<QRectF> stack = zoomStack(); if (zoomIndex < stack.size()) { QRectF r = scaleRect(); stack[zoomIndex] = r; setZoomStack(stack, zoomIndex); } } Super::zoom(up); if (zoomRectIndex() == 0) { if (QwtPlot *plotter = plot()) { plotter->setAxisAutoScale(AxisX); plotter->setAxisAutoScale(AxisY); plotter->updateAxes(); } } }
void Tree::equilibrar(string tree){ int qabre = 0; int qfecha = 0; QStack<char*> *verificador = new QStack<char*>(); char* abre = "("; char* fecha = ")"; for(int i; i < tree.length();i++){ if(tree[i] == '('){ qabre++; verificador->push(abre); } else if(tree[i] == ')'){ qfecha++; if(verificador->size() != 0){ if(verificador->top() == "("){ verificador->pop(); } else{ verificador->push(fecha); } } else{ verificador->push(fecha); } } } }
void Highlighter::validateCodeTreeModel(){ if( !_blocksDirty ) return; QStandardItem *root=_editor->_codeTreeModel->invisibleRootItem(); int row=0; QStandardItem *parent=root; QStack<int> rowStack; QStack<QStandardItem*> parentStack; int indent=0x7fff; for( QTextBlock block=_editor->document()->firstBlock();block.isValid();block=block.next() ){ BlockData *data=dynamic_cast<BlockData*>( block.userData() ); if( !data ) continue; if( !_blocks.contains( data ) ){ qDebug()<<"Highlighter::validateCodeTreeModel Block error!"; continue; } int level=0; if( data->indent()<=indent ){ indent=data->indent(); level=0; }else{ level=1; } while( rowStack.size()>level ){ parent->setRowCount( row ); parent=parentStack.pop(); row=rowStack.pop(); } CodeTreeItem *item=dynamic_cast<CodeTreeItem*>( parent->child( row++ ) ); if( !item ){ item=new CodeTreeItem; parent->appendRow( item ); } item->setData( data ); item->setText( data->ident() ); rowStack.push( row ); parentStack.push( parent ); row=0; parent=item; } for(;;){ parent->setRowCount( row ); if( parent==root ) break; parent=parentStack.pop(); row=rowStack.pop(); } _blocksDirty=false; }
void Tree::rebuildTree(string maestro){ QStack<Node*>* arranjador = new QStack<Node*>(); arranjador->push(root); for(int i = 0; i < maestro.length(); i++){ if(maestro[i] == '$'){ i++; if(arranjador->top()->getqFilhos() == false){ Node* temp = new Node(0,true,maestro[i]); arranjador->top()->setLeftChild(temp); arranjador->top()->setqFilhos(true); } else if(arranjador->top()->getqFilhos() == true){ Node* temp = new Node(0,true,maestro[i]); arranjador->top()->setRightChild(temp); arranjador->top()->setqFilhos(false); } } else{ if(maestro[i] == '('){ if(arranjador->top()->getqFilhos() == false){ Node* temp = new Node(i,false); arranjador->top()->setLeftChild(temp); arranjador->top()->setqFilhos(true); arranjador->push(temp); } else if(arranjador->top()->getqFilhos() == true){ Node* temp = new Node(i,false); arranjador->top()->setRightChild(temp); arranjador->top()->setqFilhos(false); arranjador->push(temp); } } else if(maestro[i] == ')'){ arranjador->pop(); } else{ if(arranjador->top()->getqFilhos() == false){ Node* temp = new Node(0,true,maestro[i]); arranjador->top()->setLeftChild(temp); arranjador->top()->setqFilhos(true); } else if(arranjador->top()->getqFilhos() == true){ Node* temp = new Node(0,true,maestro[i]); arranjador->top()->setRightChild(temp); arranjador->top()->setqFilhos(false); } } } } if(arranjador->size()!= 1){ cout << "TRASH! arvore desequilibrada" << endl; } }
void stackShow::Post2In(QStringList &phrase) { static QStack <QString> stack; QString r,r1,r2; QString l[4]={"+" , "-" , "*" , "/" }; for (int i=0; i<phrase.size(); i++) for (int j=0 ; j<4 ; j++) { if (phrase.at(i)!=l[j] && j==3) { stack.push(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.size()<2) return ; QStringList t = stack.toList(); t.removeLast(); t.removeLast(); r = t.join(" "); r1=stack.pop(); r2=stack.pop(); stack.push( "( " + r2 + " " + phrase.at(i) + " " + r1 + " ) "); ui->lneRes->setText( "( " + r2 + " " + phrase.at(i) + " " + r1 + " ) "); ui->lneStack->setText( r + " " "( " + r2 + " " + phrase.at(i) + " " + r1 + " ) "); phrase.removeFirst(); r = phrase.join(" "); ui->lneExp->setText(r); if (phrase.size()==0) stack.clear(); return; } } }
static const QString context() { QString context(yyPackage); bool innerClass = false; for (int i = 0; i < yyScope.size(); ++i) { if (yyScope.at(i)->type == Scope::Clazz) { if (innerClass) context.append(QLatin1String("$")); else context.append(QLatin1String(".")); context.append(yyScope.at(i)->name); innerClass = true; } } return context.isEmpty() ? yyDefaultContext : context; }
void CShareMounter::rmdir(const SShare &s) { QStack<QString> removeList; QStringList dirs = s.name.split('/', QString::SkipEmptyParts); removeList.push( mountPoint_ + dirs.front() + "/"); dirs.pop_front(); while(dirs.size()) { removeList.push(removeList.top() + dirs.front() + "/"); dirs.pop_front(); } bool first = true; while(removeList.size()) { int res = syscall_->rmdir(removeList.pop().toUtf8().constData()); if(res == -1) { int e = errno; if( e == ENOTEMPTY && !first ) // thow if only it is the last folder continue; throw CMountError(e, strerror(e)); } first = false; } }
// taken from qstardict QString WordBrowser::parseData(const char *data, int dictIndex, bool htmlSpaces, bool reformatLists) { QString result; quint32 dataSize = *reinterpret_cast<const quint32*>(data); const char *dataEnd = data + dataSize; const char *ptr = data + sizeof(quint32); while (ptr < dataEnd) { switch (*ptr++) { case 'm': case 'l': case 'g': { QString str = QString::fromUtf8(ptr); ptr += str.toUtf8().length() + 1; result += str; break; } case 'x': { QString str = QString::fromUtf8(ptr); ptr += str.toUtf8().length() + 1; xdxf2html(str); result += str; break; } case 't': { QString str = QString::fromUtf8(ptr); ptr += str.toUtf8().length() + 1; result += "<font class=\"example\">"; result += str; result += "</font>"; break; } case 'y': { ptr += strlen(ptr) + 1; break; } case 'W': case 'P': { ptr += *reinterpret_cast<const quint32*>(ptr) + sizeof(quint32); break; } default: ; // nothing } } if (reformatLists) { int pos = 0; QStack<QChar> openedLists; while (pos < result.length()) { if (result[pos].isDigit()) { int n = 0; while (result[pos + n].isDigit()) ++n; pos += n; if (result[pos] == '&' && result.mid(pos + 1, 3) == "gt;") result.replace(pos, 4, ">"); QChar marker = result[pos]; QString replacement; if (marker == '>' || marker == '.' || marker == ')') { if (n == 1 && result[pos - 1] == '1') // open new list { if (openedLists.contains(marker)) { replacement = "</li></ol>"; while (openedLists.size() && openedLists.top() != marker) { replacement += "</li></ol>"; openedLists.pop(); } } openedLists.push(marker); replacement += "<ol>"; } else { while (openedLists.size() && openedLists.top() != marker) { replacement += "</li></ol>"; openedLists.pop(); } replacement += "</li>"; } replacement += "<li>"; pos -= n; n += pos; while (result[pos - 1].isSpace()) --pos; while (result[n + 1].isSpace()) ++n; result.replace(pos, n - pos + 1, replacement); pos += replacement.length(); } else ++pos; } else ++pos; } while (openedLists.size()) { result += "</li></ol>"; openedLists.pop(); } } if (htmlSpaces) { int n = 0; while (result[n].isSpace()) ++n; result.remove(0, n); n = 0; while (result[result.length() - 1 - n].isSpace()) ++n; result.remove(result.length() - n, n); for (int pos = 0; pos < result.length();) { switch (result[pos].toAscii()) { case '[': result.insert(pos, "<font class=\"transcription\">"); pos += 28 + 1; // sizeof "<font class=\"transcription\">" + 1 break; case ']': result.insert(pos + 1, "</font>"); pos += 7 + 1; // sizeof "</font>" + 1 break; case '\t': result.insert(pos, " "); pos += 24 + 1; // sizeof " " + 1 break; case '\n': { int count = 1; n = 1; while (result[pos + n].isSpace()) { if (result[pos + n] == '\n') ++count; ++n; } if (count > 1) result.replace(pos, n, "</p><p>"); else result.replace(pos, n, "<br>"); break; } default: ++pos; } } } return result; }
bool QQuickStyledTextPrivate::parseTag(const QChar *&ch, const QString &textIn, QString &textOut, QTextCharFormat &format) { skipSpace(ch); int tagStart = ch - textIn.constData(); int tagLength = 0; while (!ch->isNull()) { if (*ch == greaterThan) { if (tagLength == 0) return false; QStringRef tag(&textIn, tagStart, tagLength); const QChar char0 = tag.at(0); if (char0 == QLatin1Char('b')) { if (tagLength == 1) { format.setFontWeight(QFont::Bold); return true; } else if (tagLength == 2 && tag.at(1) == QLatin1Char('r')) { textOut.append(QChar(QChar::LineSeparator)); hasSpace = true; prependSpace = false; return false; } } else if (char0 == QLatin1Char('i')) { if (tagLength == 1) { format.setFontItalic(true); return true; } } else if (char0 == QLatin1Char('p')) { if (tagLength == 1) { if (!hasNewLine) textOut.append(QChar::LineSeparator); hasSpace = true; prependSpace = false; } else if (tag == QLatin1String("pre")) { preFormat = true; if (!hasNewLine) textOut.append(QChar::LineSeparator); format.setFontFamily(QString::fromLatin1("Courier New,courier")); format.setFontFixedPitch(true); return true; } } else if (char0 == QLatin1Char('u')) { if (tagLength == 1) { format.setFontUnderline(true); return true; } else if (tag == QLatin1String("ul")) { List listItem; listItem.level = 0; listItem.type = Unordered; listItem.format = Bullet; listStack.push(listItem); } } else if (char0 == QLatin1Char('h') && tagLength == 2) { int level = tag.at(1).digitValue(); if (level >= 1 && level <= 6) { if (!hasNewLine) textOut.append(QChar::LineSeparator); hasSpace = true; prependSpace = false; setFontSize(7 - level, format); format.setFontWeight(QFont::Bold); return true; } } else if (tag == QLatin1String("strong")) { format.setFontWeight(QFont::Bold); return true; } else if (tag == QLatin1String("ol")) { List listItem; listItem.level = 0; listItem.type = Ordered; listItem.format = Decimal; listStack.push(listItem); } else if (tag == QLatin1String("li")) { if (!hasNewLine) textOut.append(QChar(QChar::LineSeparator)); if (!listStack.isEmpty()) { int count = ++listStack.top().level; for (int i = 0; i < listStack.size(); ++i) textOut += QString(tabsize, QChar::Nbsp); switch (listStack.top().format) { case Decimal: textOut += QString::number(count) % QLatin1Char('.'); break; case LowerAlpha: textOut += toAlpha(count, false) % QLatin1Char('.'); break; case UpperAlpha: textOut += toAlpha(count, true) % QLatin1Char('.'); break; case LowerRoman: textOut += toRoman(count, false) % QLatin1Char('.'); break; case UpperRoman: textOut += toRoman(count, true) % QLatin1Char('.'); break; case Bullet: textOut += bullet; break; case Disc: textOut += disc; break; case Square: textOut += square; break; } textOut += QString(2, QChar::Nbsp); } } return false; } else if (ch->isSpace()) { // may have params. QStringRef tag(&textIn, tagStart, tagLength); if (tag == QLatin1String("font")) return parseFontAttributes(ch, textIn, format); if (tag == QLatin1String("ol")) { parseOrderedListAttributes(ch, textIn); return false; // doesn't modify format } if (tag == QLatin1String("ul")) { parseUnorderedListAttributes(ch, textIn); return false; // doesn't modify format } if (tag == QLatin1String("a")) { return parseAnchorAttributes(ch, textIn, format); } if (tag == QLatin1String("img")) { parseImageAttributes(ch, textIn, textOut); return false; } if (*ch == greaterThan || ch->isNull()) continue; } else if (*ch != slash) { tagLength++; } ++ch; } return false; }
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(); }
QPair<int, double> WorkbookParserPrivate::calculateInfix(int start, QStringList items) { int i = start; bool ok; qreal d, n1, n2; QStack<qreal> values; QStack<OperatorBase<qreal>*> operators; QPair<int, double> result; // TODO add in errors ie unbalanced brackets wrong number // of values or operators // TODO handle cell references and ranges. while(i < items.size()) { QString s = items.at(i); if (s == ")") { result.first = i + 1; result.second = values.pop(); return result; } if (s == "(") { i++; result = calculateInfix(i, items); // Recurse. i = result.first; values.push(result.second); continue; } d = s.toDouble(&ok); if (ok) { values.insert(i++, d); continue; } // turns constants into their actual value in the list. ConstantBase *constant = dynamic_cast<ConstantBase*>(pPluginStore->getConstant(s)); if (constant) { values.insert(i++, constant->value()); continue; } IFunction *func = dynamic_cast<IFunction*>(pPluginStore->getFunction(s)); if (func) { result = calculateInfixFunction(func, i, items); // functioss should return a value. i = result.first; values.push(result.second); continue; } OperatorBase<qreal> *op1 = dynamic_cast<OperatorBase<qreal>*>(pPluginStore->getOperator(s)); if (op1) { if (operators.size() == 0 || operators.top()->level() < op1->level()) { OperatorBase<qreal> *op2 = operators.pop(); n1 = values.pop(); n2 = values.pop(); d = op2->calculate(n2, n1); values.push(d); } operators.push(op1); i++; continue; } // TODO string handling // OperatorBase<QString> *ops1 = dynamic_cast<OperatorBase<QString>*>(pPluginStore->getOperator(s)); // if (op1) { // // convert numbers to strings if necessary // } } return result; }
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(); }
bool QMakeParser::read(ProFile *pro, const QString &in, int line, SubGrammar grammar) { m_proFile = pro; m_lineNo = line; // Final precompiled token stream buffer QString tokBuff; // Worst-case size calculations: // - line marker adds 1 (2-nl) to 1st token of each line // - empty assignment "A=":2 => // TokHashLiteral(1) + hash(2) + len(1) + "A"(1) + TokAssign(1) + 0(1) + // TokValueTerminator(1) == 8 (9) // - non-empty assignment "A=B C":5 => // TokHashLiteral(1) + hash(2) + len(1) + "A"(1) + TokAssign(1) + 2(1) + // TokLiteral(1) + len(1) + "B"(1) + // TokLiteral(1) + len(1) + "C"(1) + TokValueTerminator(1) == 14 (15) // - variable expansion: "$$f":3 => // TokVariable(1) + hash(2) + len(1) + "f"(1) = 5 // - function expansion: "$$f()":5 => // TokFuncName(1) + hash(2) + len(1) + "f"(1) + TokFuncTerminator(1) = 6 // - scope: "X:":2 => // TokHashLiteral(1) + hash(2) + len(1) + "A"(1) + TokCondition(1) + // TokBranch(1) + len(2) + ... + len(2) + ... == 10 // - test: "X():":4 => // TokHashLiteral(1) + hash(2) + len(1) + "A"(1) + TokTestCall(1) + TokFuncTerminator(1) + // TokBranch(1) + len(2) + ... + len(2) + ... == 11 // - "for(A,B):":9 => // TokForLoop(1) + hash(2) + len(1) + "A"(1) + // len(2) + TokLiteral(1) + len(1) + "B"(1) + TokValueTerminator(1) + // len(2) + ... + TokTerminator(1) == 14 (15) tokBuff.reserve((in.size() + 1) * 5); ushort *tokPtr = (ushort *)tokBuff.constData(); // Current writing position // Expression precompiler buffer. QString xprBuff; xprBuff.reserve(tokBuff.capacity()); // Excessive, but simple ushort *buf = (ushort *)xprBuff.constData(); // Parser state m_blockstack.clear(); m_blockstack.resize(1); QStack<ParseCtx> xprStack; xprStack.reserve(10); // We rely on QStrings being null-terminated, so don't maintain a global end pointer. const ushort *cur = (const ushort *)in.unicode(); m_canElse = false; freshLine: m_state = StNew; m_invert = false; m_operator = NoOperator; m_markLine = m_lineNo; m_inError = false; int parens = 0; // Braces in value context int argc = 0; int wordCount = 0; // Number of words in currently accumulated expression int lastIndent = 0; // Previous line's indentation, to detect accidental continuation abuse bool lineMarked = true; // For in-expression markers ushort needSep = TokNewStr; // Met unquoted whitespace ushort quote = 0; ushort term = 0; Context context; ushort *ptr; if (grammar == ValueGrammar) { context = CtxPureValue; ptr = tokPtr + 2; } else { context = CtxTest; ptr = buf + 4; } ushort *xprPtr = ptr; #define FLUSH_LHS_LITERAL() \ do { \ if ((tlen = ptr - xprPtr)) { \ finalizeHashStr(xprPtr, tlen); \ if (needSep) { \ wordCount++; \ needSep = 0; \ } \ } else { \ ptr -= 4; \ } \ } while (0) #define FLUSH_RHS_LITERAL() \ do { \ if ((tlen = ptr - xprPtr)) { \ xprPtr[-2] = TokLiteral | needSep; \ xprPtr[-1] = tlen; \ if (needSep) { \ wordCount++; \ needSep = 0; \ } \ } else { \ ptr -= 2; \ } \ } while (0) #define FLUSH_LITERAL() \ do { \ if (context == CtxTest) \ FLUSH_LHS_LITERAL(); \ else \ FLUSH_RHS_LITERAL(); \ } while (0) #define FLUSH_VALUE_LIST() \ do { \ if (wordCount > 1) { \ xprPtr = tokPtr; \ if (*xprPtr == TokLine) \ xprPtr += 2; \ tokPtr[-1] = ((*xprPtr & TokMask) == TokLiteral) ? wordCount : 0; \ } else { \ tokPtr[-1] = 0; \ } \ tokPtr = ptr; \ putTok(tokPtr, TokValueTerminator); \ } while (0) const ushort *end; // End of this line const ushort *cptr; // Start of next line bool lineCont; int indent; if (context == CtxPureValue) { end = (const ushort *)in.unicode() + in.length(); cptr = 0; lineCont = false; indent = 0; // just gcc being stupid goto nextChr; } forever { ushort c; // First, skip leading whitespace for (indent = 0; ; ++cur, ++indent) { c = *cur; if (c == '\n') { ++cur; goto flushLine; } else if (!c) { cur = 0; goto flushLine; } else if (c != ' ' && c != '\t' && c != '\r') { break; } } // Then strip comments. Yep - no escaping is possible. for (cptr = cur;; ++cptr) { c = *cptr; if (c == '#') { for (end = cptr; (c = *++cptr);) { if (c == '\n') { ++cptr; break; } } if (end == cur) { // Line with only a comment (sans whitespace) if (m_markLine == m_lineNo) m_markLine++; // Qmake bizarreness: such lines do not affect line continuations goto ignore; } break; } if (!c) { end = cptr; break; } if (c == '\n') { end = cptr++; break; } } // Then look for line continuations. Yep - no escaping here as well. forever { // We don't have to check for underrun here, as we already determined // that the line is non-empty. ushort ec = *(end - 1); if (ec == '\\') { --end; lineCont = true; break; } if (ec != ' ' && ec != '\t' && ec != '\r') { lineCont = false; break; } --end; } // Finally, do the tokenization ushort tok, rtok; int tlen; newWord: do { if (cur == end) goto lineEnd; c = *cur++; } while (c == ' ' || c == '\t'); forever { if (c == '$') { if (*cur == '$') { // may be EOF, EOL, WS, '#' or '\\' if past end cur++; FLUSH_LITERAL(); if (!lineMarked) { lineMarked = true; *ptr++ = TokLine; *ptr++ = (ushort)m_lineNo; } term = 0; tok = TokVariable; c = *cur; if (c == '[') { ptr += 4; tok = TokProperty; term = ']'; c = *++cur; } else if (c == '{') { ptr += 4; term = '}'; c = *++cur; } else if (c == '(') { ptr += 2; tok = TokEnvVar; term = ')'; c = *++cur; } else { ptr += 4; } xprPtr = ptr; rtok = tok; while ((c & 0xFF00) || c == '.' || c == '_' || (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || (c == '/' && term)) { *ptr++ = c; if (++cur == end) { c = 0; goto notfunc; } c = *cur; } if (tok == TokVariable && c == '(') tok = TokFuncName; notfunc: if (ptr == xprPtr) languageWarning(fL1S("Missing name in expansion")); if (quote) tok |= TokQuoted; if (needSep) { tok |= needSep; wordCount++; } tlen = ptr - xprPtr; if (rtok != TokVariable || !resolveVariable(xprPtr, tlen, needSep, &ptr, &buf, &xprBuff, &tokPtr, &tokBuff, cur, in)) { if (rtok == TokVariable || rtok == TokProperty) { xprPtr[-4] = tok; uint hash = ProString::hash((const QChar *)xprPtr, tlen); xprPtr[-3] = (ushort)hash; xprPtr[-2] = (ushort)(hash >> 16); xprPtr[-1] = tlen; } else { xprPtr[-2] = tok; xprPtr[-1] = tlen; } } if ((tok & TokMask) == TokFuncName) { cur++; funcCall: { xprStack.resize(xprStack.size() + 1); ParseCtx &top = xprStack.top(); top.parens = parens; top.quote = quote; top.terminator = term; top.context = context; top.argc = argc; top.wordCount = wordCount; } parens = 0; quote = 0; term = 0; argc = 1; context = CtxArgs; nextToken: wordCount = 0; nextWord: ptr += (context == CtxTest) ? 4 : 2; xprPtr = ptr; needSep = TokNewStr; goto newWord; } if (term) { checkTerm: if (c != term) { parseError(fL1S("Missing %1 terminator [found %2]") .arg(QChar(term)) .arg(c ? QString(c) : QString::fromLatin1("end-of-line"))); pro->setOk(false); m_inError = true; // Just parse on, as if there was a terminator ... } else { cur++; } } joinToken: ptr += (context == CtxTest) ? 4 : 2; xprPtr = ptr; needSep = 0; goto nextChr; } } else if (c == '\\') {
void OwncloudPropagator::start(const SyncFileItemVector& items) { Q_ASSERT(std::is_sorted(items.begin(), items.end())); /* This builds all the jobs needed for the propagation. * Each directory is a PropagateDirectory job, which contains the files in it. * In order to do that we loop over the items. (which are sorted by destination) * When we enter a directory, we can create the directory job and push it on the stack. */ _rootJob.reset(new PropagateDirectory(this)); QStack<QPair<QString /* directory name */, PropagateDirectory* /* job */> > directories; directories.push(qMakePair(QString(), _rootJob.data())); QVector<PropagatorJob*> directoriesToRemove; QString removedDirectory; foreach(const SyncFileItemPtr &item, items) { if (!removedDirectory.isEmpty() && item->_file.startsWith(removedDirectory)) { // this is an item in a directory which is going to be removed. PropagateDirectory *delDirJob = dynamic_cast<PropagateDirectory*>(directoriesToRemove.first()); if (item->_instruction == CSYNC_INSTRUCTION_REMOVE) { // already taken care of. (by the removal of the parent directory) // increase the number of subjobs that would be there. if( delDirJob ) { delDirJob->increaseAffectedCount(); } continue; } else if (item->_isDirectory && (item->_instruction == CSYNC_INSTRUCTION_NEW || item->_instruction == CSYNC_INSTRUCTION_TYPE_CHANGE)) { // create a new directory within a deleted directory? That can happen if the directory // etag was not fetched properly on the previous sync because the sync was aborted // while uploading this directory (which is now removed). We can ignore it. if( delDirJob ) { delDirJob->increaseAffectedCount(); } continue; } else if (item->_instruction == CSYNC_INSTRUCTION_IGNORE) { continue; } else if (item->_instruction == CSYNC_INSTRUCTION_RENAME) { // all is good, the rename will be executed before the directory deletion } else { qWarning() << "WARNING: Job within a removed directory? This should not happen!" << item->_file << item->_instruction; } } while (!item->destination().startsWith(directories.top().first)) { directories.pop(); } if (item->_isDirectory) { PropagateDirectory *dir = new PropagateDirectory(this, item); dir->_firstJob.reset(createJob(item)); if (item->_instruction == CSYNC_INSTRUCTION_TYPE_CHANGE && item->_direction == SyncFileItem::Up) { // Skip all potential uploads to the new folder. // Processing them now leads to problems with permissions: // checkForPermissions() has already run and used the permissions // of the file we're about to delete to decide whether uploading // to the new dir is ok... foreach(const SyncFileItemPtr &item2, items) { if (item2->destination().startsWith(item->destination() + "/")) { item2->_instruction = CSYNC_INSTRUCTION_NONE; _anotherSyncNeeded = true; } } } if (item->_instruction == CSYNC_INSTRUCTION_REMOVE) { // We do the removal of directories at the end, because there might be moves from // these directories that will happen later. directoriesToRemove.prepend(dir); removedDirectory = item->_file + "/"; // We should not update the etag of parent directories of the removed directory // since it would be done before the actual remove (issue #1845) // NOTE: Currently this means that we don't update those etag at all in this sync, // but it should not be a problem, they will be updated in the next sync. for (int i = 0; i < directories.size(); ++i) { if (directories[i].second->_item->_instruction == CSYNC_INSTRUCTION_UPDATE_METADATA) directories[i].second->_item->_instruction = CSYNC_INSTRUCTION_NONE; } } else { PropagateDirectory* currentDirJob = directories.top().second; currentDirJob->append(dir); } directories.push(qMakePair(item->destination() + "/" , dir)); } else if (PropagateItemJob* current = createJob(item)) {
bool QFileSystemIteratorPrivate::advanceHelper() { if (m_dirStructs.isEmpty()) return true; //printf("ADV %d %d\n", int(m_currentDirShown), int(m_nextDirShown)); if ((filters & QDir::Dirs)) { m_currentDirShown = m_nextDirShown; if (m_nextDirShown == ShowDir) { //printf("RESTING ON DIR %s %x\n", m_dirPaths.top().constData(), int(filters)); m_nextDirShown = (filters & QDir::NoDotAndDotDot) ? DontShowDir : ShowDotDir; // skip start directory itself if (m_dirStructs.size() == 1 && m_currentDirShown == ShowDir) return advanceHelper(); return true; } if (m_nextDirShown == ShowDotDir) { //printf("RESTING ON DOT %s %x\n", m_dirPaths.top().constData(), int(filters)); m_nextDirShown = ShowDotDotDir; return true; } if (m_nextDirShown == ShowDotDotDir) { //printf("RESTING ON DOTDOT %s %x\n", m_dirPaths.top().constData(), int(filters)); m_nextDirShown = DontShowDir; return true; } m_currentDirShown = DontShowDir; } #ifdef Q_OS_WIN m_entry = &m_fileSearchResult; if (m_bFirstSearchResult) { m_bFirstSearchResult = false; } else { if (!FindNextFile(m_dirStructs.top(), m_entry)) m_entry = 0; } while (m_entry && isDotOrDotDot(m_entry->cFileName)) if (!FindNextFile(m_dirStructs.top(), m_entry)) m_entry = 0; if (!m_entry) { m_dirPaths.pop(); FindClose(m_dirStructs.pop()); return false; } if (m_entry->dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) { QByteArray ba = m_dirPaths.top(); ba += '\\'; ba += QString::fromWCharArray(m_entry->cFileName); pushSubDirectory(ba); } #else m_entry = ::readdir(m_dirStructs.top()); while (m_entry && isDotOrDotDot(m_entry->d_name)) m_entry = ::readdir(m_dirStructs.top()); //return false; // further iteration possibly needed //printf("READ %p %s\n", m_entry, m_entry ? m_entry->d_name : ""); if (!m_entry) { m_dirPaths.pop(); DIR *dir = m_dirStructs.pop(); ::closedir(dir); return false; // further iteration possibly needed } const char *name = m_entry->d_name; QByteArray ba = m_dirPaths.top(); ba += '/'; ba += name; struct stat st; lstat(ba.constData(), &st); if (S_ISDIR(st.st_mode)) { pushSubDirectory(ba); return false; // further iteration possibly needed } #endif return false; // further iteration possiblye needed }
void ScCodeEditor::indent( const QTextCursor & selection ) { if (selection.isNull()) return; QTextCursor cursor(selection); cursor.beginEditBlock(); QTextDocument *doc = QPlainTextEdit::document(); int startBlockNum = doc->findBlock(cursor.selectionStart()).blockNumber(); int endBlockNum = cursor.hasSelection() ? doc->findBlock(cursor.selectionEnd()).blockNumber() : startBlockNum; QStack<int> stack; int level = 0; int blockNum = 0; QTextBlock block = QPlainTextEdit::document()->begin(); while (block.isValid()) { if (level > 0) { stack.push(level); level = 0; } int initialStackSize = stack.size(); TextBlockData *data = static_cast<TextBlockData*>(block.userData()); if (data) { int count = data->tokens.size(); for (int idx = 0; idx < count; ++idx) { const Token & token = data->tokens[idx]; switch (token.type) { case Token::OpeningBracket: if (token.character != '(' || stack.size() || token.positionInBlock) level += 1; break; case Token::ClosingBracket: if (level) level -= 1; else if(!stack.isEmpty()) { stack.top() -= 1; if (stack.top() <= 0) stack.pop(); } break; default: ; } } } if(blockNum >= startBlockNum) { int indentLevel; if (data && data->tokens.size() && data->tokens[0].type == Token::ClosingBracket) indentLevel = stack.size(); else indentLevel = initialStackSize; block = indent(block, indentLevel); } if(blockNum == endBlockNum) break; block = block.next(); ++blockNum; } cursor.endEditBlock(); }
bool TableFieldBinaryTreeEvalNode::processOneTreeLevel(QStack<TableFieldBinaryTreeEvalNode*>& values, QStack<TableFieldBinaryTreeEvalNode*>& operators) { if (operators.isEmpty()) { qDebug(qPrintable(tr("Operator stack is prematurely empty"))); return true; } TableFieldBinaryTreeEvalNode* opNode = operators.pop(); //qDebug(qPrintable(tr("processOneTreeLevel Op Node value(%1) type(%2) priority(%3)").arg(opNode->nodeValue()).arg(opNode->nodeType()).arg(opNode->nodePriority()))); if (opNode->m_node->isInfix()) { // Two operands if (values.size() < 2) { qDebug(qPrintable(tr("Found an INFIX operator that requires two values, and have %1 value(s).").arg(values.size()))); return true; } else { TableFieldBinaryTreeEvalNode* child2 = values.pop(); TableFieldBinaryTreeEvalNode* child1 = values.pop(); if (child1->nodeType() == opNode->nodeType()) { // First child has the same operator type, // So, we can use a single node (faster processing and fewer nodes). if (child2->nodeType() == opNode->nodeType()) { // So does child 2, so copy the children. for (int i=0; i<child2->m_children.size(); ++i) { child1->addChild(child2->m_children.at(i)); } delete child2; } else { child1->addChild(child2); values.push(child1); } delete opNode; } else if (child2->nodeType() == opNode->nodeType()) { // Make child1 the first child of child two. child2->m_children.insert(0, child1); child1->setTreeParent(child2); delete opNode; } else { opNode->addChild(child1); opNode->addChild(child2); values.push(opNode); } } } else if (opNode->m_node->isSuffixOrPrefix()) { // Need one value. if (values.isEmpty()) { qDebug(qPrintable(tr("Found a PREFIX or SUFFIX operator with an empty value list."))); return true; } else { TableFieldBinaryTreeEvalNode* child1 = values.pop(); // I suppose if the value is boolean... if (child1->isValue()) { qDebug(qPrintable(tr("Cannot take the NOT of a value."))); return true; } // make the value a child of the NOT operator and push the NOT operator // into the values stack. opNode->addChild(child1); values.push(opNode); } } else { qDebug(qPrintable(tr("Found an operator node with an unknown type."))); return true; } return false; }
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(); }
void OwncloudPropagator::start(const SyncFileItemVector& items) { Q_ASSERT(std::is_sorted(items.begin(), items.end())); /* Check and log the transmission checksum type */ ConfigFile cfg; const QString checksumType = cfg.transmissionChecksum().toUpper(); /* if the checksum type is empty, it is not send. No error */ if( !checksumType.isEmpty() ) { if( checksumType == checkSumAdlerUpperC || checksumType == checkSumMD5C || checksumType == checkSumSHA1C ) { qDebug() << "Client sends and expects transmission checksum type" << checksumType; } else { qWarning() << "Unknown transmission checksum type from config" << checksumType; } } /* This builds all the job needed for the propagation. * Each directories is a PropagateDirectory job, which contains the files in it. * In order to do that we loop over the items. (which are sorted by destination) * When we enter adirectory, we can create the directory job and push it on the stack. */ _rootJob.reset(new PropagateDirectory(this)); QStack<QPair<QString /* directory name */, PropagateDirectory* /* job */> > directories; directories.push(qMakePair(QString(), _rootJob.data())); QVector<PropagatorJob*> directoriesToRemove; QString removedDirectory; foreach(const SyncFileItemPtr &item, items) { if (!removedDirectory.isEmpty() && item->_file.startsWith(removedDirectory)) { // this is an item in a directory which is going to be removed. PropagateDirectory *delDirJob = dynamic_cast<PropagateDirectory*>(directoriesToRemove.last()); if (item->_instruction == CSYNC_INSTRUCTION_REMOVE) { //already taken care of. (by the removal of the parent directory) // increase the number of subjobs that would be there. if( delDirJob ) { delDirJob->increaseAffectedCount(); } continue; } else if (item->_instruction == CSYNC_INSTRUCTION_NEW && item->_isDirectory) { // create a new directory within a deleted directory? That can happen if the directory // etag were not fetched properly on the previous sync because the sync was aborted // while uploading this directory (which is now removed). We can ignore it. if( delDirJob ) { delDirJob->increaseAffectedCount(); } continue; } else if (item->_instruction == CSYNC_INSTRUCTION_IGNORE) { continue; } qWarning() << "WARNING: Job within a removed directory? This should not happen!" << item->_file << item->_instruction; } while (!item->destination().startsWith(directories.top().first)) { directories.pop(); } if (item->_isDirectory) { PropagateDirectory *dir = new PropagateDirectory(this, item); dir->_firstJob.reset(createJob(item)); if (item->_instruction == CSYNC_INSTRUCTION_REMOVE) { //We do the removal of directories at the end, because there might be moves from // this directories that will happen later. directoriesToRemove.append(dir); removedDirectory = item->_file + "/"; // We should not update the etag of parent directories of the removed directory // since it would be done before the actual remove (issue #1845) // NOTE: Currently this means that we don't update those etag at all in this sync, // but it should not be a problem, they will be updated in the next sync. for (int i = 0; i < directories.size(); ++i) { directories[i].second->_item->_should_update_metadata = false; } } else { PropagateDirectory* currentDirJob = directories.top().second; currentDirJob->append(dir); } directories.push(qMakePair(item->destination() + "/" , dir)); } else if (PropagateItemJob* current = createJob(item)) { directories.top().second->append(current); } } foreach(PropagatorJob* it, directoriesToRemove) { _rootJob->append(it); }
Constante* Eval::getValue() const { Expression* exp = dynamic_cast<Expression*>(c); QStack<Constante*> p; if (exp != NULL){ int i = 0; QString s = exp->getExp(); Constante * result = 0; while(i<s.length()){ //on passe les espaces; if(s[i] == ' '){ if(result != 0){ p.push(result); result = 0; } } else if(s[i] >= '0' && s[i] <= '9'){ if(result == 0)result = Addition(Rationnel(0),Rationnel(0),mModeConstante, mModeComplexes).getValue(); result->addChiffre(s[i].toAscii() - '0'); } else if(s[i] == '$'){ if(result == 0) throw EvalException("$ mal placé"); result->setDollarEntre(); } else if(s[i] == '/'){ if(result != 0){ result->setSlashEntre(); } else{ if(p.size() < 2) throw EvalException("Pas assez d'opérandes pour /"); Constante *op2 = p.pop(), *op1 = p.pop(); try{ result = Division(*op1,*op2,mModeConstante,mModeComplexes).getValue(); } catch(DivException e){ throw EvalException("division par zéro"); } delete op1; delete op2; p.push(result); result = 0; } } else if(s[i] == ',' || s[i] == '.'){ if(result == 0) throw EvalException(", ou . mal placé"); result->setVirguleEntree(); } else if(s[i] == '+'){ if(result!=0){ p.push(result); result = 0; } if(p.size() < 2) throw EvalException("Pas assez d'opérandes pour +"); Constante *op1 = p.pop(), *op2 = p.pop(); result = Addition(*op1,*op2,mModeConstante,mModeComplexes).getValue(); delete op1; delete op2; p.push(result); result = 0; } else if(s[i] == '-'){ if(result!=0){ p.push(result); result = 0; } if(p.size() < 2) throw EvalException("Pas assez d'opérandes pour -"); Constante *op2 = p.pop(), *op1 = p.pop(); result = Soustraction(*op1,*op2,mModeConstante,mModeComplexes).getValue(); delete op1; delete op2; p.push(result); result = 0; } else if(s[i] == '*'){ if(result!=0){ p.push(result); result = 0; } if(p.size() < 2) throw EvalException("Pas assez d'opérandes pour *"); Constante *op2 = p.pop(), *op1 = p.pop(); result = Multiplication(*op1,*op2,mModeConstante,mModeComplexes).getValue(); delete op1; delete op2; p.push(result); result = 0; } else{ throw EvalException("Caractère inconnu"); } i++; } if(result!=0)p.push(result); if(p.size() > 1) throw EvalException("Il manque un opérateur."); if(p.size() < 1) throw EvalException("Pile d'évaluation vide."); return p.at(0); } else throw TypeConstanteException("Ceci n'est pas une expression"); }
void OwncloudPropagator::start(const SyncFileItemVector& _syncedItems) { /* This builds all the job needed for the propagation. * Each directories is a PropagateDirectory job, which contains the files in it. * In order to do that we sort the items by destination. and loop over it. When we enter a * directory, we can create the directory job and push it on the stack. */ SyncFileItemVector items = _syncedItems; std::sort(items.begin(), items.end()); _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 SyncFileItem &item, items) { if (!removedDirectory.isEmpty() && item._file.startsWith(removedDirectory)) { // this is an item in a directory which is going to be removed. if (item._instruction == CSYNC_INSTRUCTION_REMOVE) { //already taken care of. (by the removal of the parent directory) continue; } else if (item._instruction == CSYNC_INSTRUCTION_NEW && item._isDirectory) { // create a new directory within a deleted directory? That can happen if the directory // etag were not fetched properly on the previous sync because the sync was aborted // while uploading this directory (which is now removed). We can ignore it. continue; } else if (item._instruction == CSYNC_INSTRUCTION_IGNORE) { continue; } qWarning() << "WARNING: Job within a removed directory? This should not happen!" << item._file << item._instruction; } while (!item.destination().startsWith(directories.top().first)) { directories.pop(); } if (item._isDirectory) { PropagateDirectory *dir = new PropagateDirectory(this, item); dir->_firstJob.reset(createJob(item)); if (item._instruction == CSYNC_INSTRUCTION_REMOVE) { //We do the removal of directories at the end, because there might be moves from // this directories that will happen later. directoriesToRemove.append(dir); removedDirectory = item._file + "/"; // We should not update the etag of parent directories of the removed directory // since it would be done before the actual remove (issue #1845) // NOTE: Currently this means that we don't update those etag at all in this sync, // but it should not be a problem, they will be updated in the next sync. for (int i = 0; i < directories.size(); ++i) { directories[i].second->_item._should_update_etag = 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); }
TableFieldBinaryTreeEvalNode* TableFieldBinaryTreeEvalNode::buildTree(QList<TableFieldEvalNode *>& list, QObject *parent) { if (list.isEmpty()) { return nullptr; } // Build a new list that is surrounded with parenthesis. QList<TableFieldEvalNode *> safeList; TableFieldEvalNode leftParenEvalNode(TableFieldEvalNode::L_PAREN); TableFieldEvalNode rightParenEvalNode(TableFieldEvalNode::R_PAREN); TableFieldBinaryTreeEvalNode* headNode = new TableFieldBinaryTreeEvalNode(parent); safeList.append(&leftParenEvalNode); safeList.append(list); safeList.append(&rightParenEvalNode); bool isError = false; QStack<TableFieldBinaryTreeEvalNode*> values; QStack<TableFieldBinaryTreeEvalNode*> operators; QListIterator<TableFieldEvalNode*> i(safeList); while (i.hasNext() && !isError) { TableFieldEvalNode* eNode = i.next(); if (eNode == nullptr) { qDebug(qPrintable(tr("Cannot build a tree from null nodes."))); isError = true; } else if (eNode->isValue()) { // Push value nodes on the value stack. TableFieldBinaryTreeEvalNode* bNode = new TableFieldBinaryTreeEvalNode(headNode); bNode->setNode(eNode->clone(bNode)); values.push(bNode); } else if (eNode->isLeftParen()) { // Push left parenthesis onto the operator stack. // Will be removed when a right parenthesis is found. TableFieldBinaryTreeEvalNode* bNode = new TableFieldBinaryTreeEvalNode(headNode); bNode->setNode(eNode->clone(bNode)); operators.push(bNode); } else if (eNode->isRightParen()) { // Found a right parenthesis. // Process all operators until a left parenthesis is found then get rid of it. while (!isError && !operators.isEmpty() && !operators.top()->isLeftParen()) { isError = processOneTreeLevel(values, operators); } if (!isError) { if (operators.isEmpty()) { qDebug(qPrintable(tr("Have a ')' without a '('"))); isError = true; } else { // Dispose of the open parenthesis. TableFieldBinaryTreeEvalNode* opNode = operators.pop(); delete opNode; } } } else if (eNode->isNoType()) { qDebug(qPrintable(tr("Cannot build a tree from raw nodes with no type"))); isError = true; } else { // Found an operator. // Process all operators whose priority / precidence is the same or greater than this one. // So, after reading "a OR b OR", you know you can set "a OR b", but you don't know yet if you can // process the second OR. while (!isError && !operators.isEmpty() && !operators.top()->isLeftParen() && operators.top()->nodePriority() >= eNode->nodePriority()) { isError = processOneTreeLevel(values, operators); } if (!isError) { // No error, so push the operator onto the operator stack. TableFieldBinaryTreeEvalNode* bNode = new TableFieldBinaryTreeEvalNode(headNode); bNode->setNode(eNode->clone(bNode)); operators.push(bNode); } } } if (!isError) { if (!operators.isEmpty()) { isError = true; qDebug(qPrintable(tr("Unprocessed Operators left in the stack after processing"))); } else if (values.size() != 1) { isError = true; qDebug(qPrintable(tr("There should be only one value left after processing, not %1").arg(values.size()))); } else { // tree parent node should already be null. // Perform a shallow copy of the top node into the head node. TableFieldBinaryTreeEvalNode* topNode = values.top(); // Clone the node so that the parent / owner is properly set. headNode->m_node = topNode->m_node->clone(headNode); for (int i=0; i<topNode->m_children.size(); ++i) { headNode->addChild(topNode->m_children.at(i)); } delete topNode; return headNode; } } if (isError) { // All of the created nodes are a child of the head node. delete headNode; } return nullptr; }