本文整理汇总了C++中QStack::push方法的典型用法代码示例。如果您正苦于以下问题:C++ QStack::push方法的具体用法?C++ QStack::push怎么用?C++ QStack::push使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类QStack
的用法示例。
在下文中一共展示了QStack::push方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。
示例1: parse
TypeParser::Info TypeParser::parse(const QString &str)
{
Scanner scanner(str);
Info info;
QStack<Info *> stack;
stack.push(&info);
bool colon_prefix = false;
bool in_array = false;
QString array;
Scanner::Token tok = scanner.nextToken();
while (tok != Scanner::NoToken) {
// switch (tok) {
// case Scanner::StarToken: printf(" - *\n"); break;
// case Scanner::AmpersandToken: printf(" - &\n"); break;
// case Scanner::LessThanToken: printf(" - <\n"); break;
// case Scanner::GreaterThanToken: printf(" - >\n"); break;
// case Scanner::ColonToken: printf(" - ::\n"); break;
// case Scanner::CommaToken: printf(" - ,\n"); break;
// case Scanner::ConstToken: printf(" - const\n"); break;
// case Scanner::SquareBegin: printf(" - [\n"); break;
// case Scanner::SquareEnd: printf(" - ]\n"); break;
// case Scanner::Identifier: printf(" - '%s'\n", qPrintable(scanner.identifier())); break;
// default:
// break;
// }
switch (tok) {
case Scanner::StarToken:
++stack.top()->indirections;
break;
case Scanner::AmpersandToken:
stack.top()->is_reference = true;
break;
case Scanner::LessThanToken:
stack.top()->template_instantiations << Info();
stack.push(&stack.top()->template_instantiations.last());
break;
case Scanner::CommaToken:
stack.pop();
stack.top()->template_instantiations << Info();
stack.push(&stack.top()->template_instantiations.last());
break;
case Scanner::GreaterThanToken:
stack.pop();
break;
case Scanner::ColonToken:
colon_prefix = true;
break;
case Scanner::ConstToken:
stack.top()->is_constant = true;
break;
case Scanner::OpenParenToken: // function pointers not supported
case Scanner::CloseParenToken:
{
Info i;
i.is_busted = true;
return i;
}
case Scanner::Identifier:
if (in_array) {
array = scanner.identifier();
} else if (colon_prefix || stack.top()->qualified_name.isEmpty()) {
stack.top()->qualified_name << scanner.identifier();
colon_prefix = false;
} else {
stack.top()->qualified_name.last().append(" " + scanner.identifier());
}
break;
case Scanner::SquareBegin:
in_array = true;
break;
case Scanner::SquareEnd:
in_array = false;
stack.top()->arrays += array;
break;
default:
break;
}
tok = scanner.nextToken();
}
//.........这里部分代码省略.........
示例2: parseLinks
void FlatTextarea::parseLinks() { // some code is duplicated in text.cpp!
LinkRanges newLinks;
QString text(toPlainText());
if (text.isEmpty()) {
if (!_links.isEmpty()) {
_links.clear();
emit linksChanged();
}
return;
}
initLinkSets();
int32 len = text.size();
const QChar *start = text.unicode(), *end = start + text.size();
for (int32 offset = 0, matchOffset = offset; offset < len;) {
QRegularExpressionMatch m = reDomain().match(text, matchOffset);
if (!m.hasMatch()) break;
int32 domainOffset = m.capturedStart();
QString protocol = m.captured(1).toLower();
QString topDomain = m.captured(3).toLower();
bool isProtocolValid = protocol.isEmpty() || validProtocols().contains(hashCrc32(protocol.constData(), protocol.size() * sizeof(QChar)));
bool isTopDomainValid = !protocol.isEmpty() || validTopDomains().contains(hashCrc32(topDomain.constData(), topDomain.size() * sizeof(QChar)));
if (protocol.isEmpty() && domainOffset > offset + 1 && *(start + domainOffset - 1) == QChar('@')) {
QString forMailName = text.mid(offset, domainOffset - offset - 1);
QRegularExpressionMatch mMailName = reMailName().match(forMailName);
if (mMailName.hasMatch()) {
offset = matchOffset = m.capturedEnd();
continue;
}
}
if (!isProtocolValid || !isTopDomainValid) {
offset = matchOffset = m.capturedEnd();
continue;
}
QStack<const QChar*> parenth;
const QChar *domainEnd = start + m.capturedEnd(), *p = domainEnd;
for (; p < end; ++p) {
QChar ch(*p);
if (chIsLinkEnd(ch)) break; // link finished
if (chIsAlmostLinkEnd(ch)) {
const QChar *endTest = p + 1;
while (endTest < end && chIsAlmostLinkEnd(*endTest)) {
++endTest;
}
if (endTest >= end || chIsLinkEnd(*endTest)) {
break; // link finished at p
}
p = endTest;
ch = *p;
}
if (ch == '(' || ch == '[' || ch == '{' || ch == '<') {
parenth.push(p);
} else if (ch == ')' || ch == ']' || ch == '}' || ch == '>') {
if (parenth.isEmpty()) break;
const QChar *q = parenth.pop(), open(*q);
if ((ch == ')' && open != '(') || (ch == ']' && open != '[') || (ch == '}' && open != '{') || (ch == '>' && open != '<')) {
p = q;
break;
}
}
}
if (p > domainEnd) { // check, that domain ended
if (domainEnd->unicode() != '/' && domainEnd->unicode() != '?') {
matchOffset = domainEnd - start;
continue;
}
}
newLinks.push_back(qMakePair(domainOffset - 1, p - start - domainOffset + 2));
offset = matchOffset = p - start;
}
if (newLinks != _links) {
_links = newLinks;
emit linksChanged();
}
}
示例3: changePainter
void QtVideoSinkDelegate::changePainter(const BufferFormat & format)
{
if (m_painter) {
m_painter->cleanup();
if (G_UNLIKELY(!m_painter->supportsFormat(format.videoFormat()))) {
destroyPainter();
}
}
QStack<PainterType> possiblePainters;
if (GenericSurfacePainter::supportedPixelFormats().contains(format.videoFormat())) {
possiblePainters.push(Generic);
}
#ifndef GST_QT_VIDEO_SINK_NO_OPENGL
if (OpenGLSurfacePainter::supportedPixelFormats().contains(format.videoFormat())) {
if (m_supportedPainters & ArbFp) {
possiblePainters.push(ArbFp);
}
if (m_supportedPainters & Glsl) {
possiblePainters.push(Glsl);
}
}
#endif
while (!possiblePainters.isEmpty()) {
if (!m_painter) {
PainterType type = possiblePainters.pop();
switch(type) {
#ifndef GST_QT_VIDEO_SINK_NO_OPENGL
case Glsl:
GST_LOG_OBJECT(m_sink, "Creating GLSL painter");
m_painter = new GlslSurfacePainter;
break;
# ifndef QT_OPENGL_ES
case ArbFp:
GST_LOG_OBJECT(m_sink, "Creating ARB Fragment Shader painter");
m_painter = new ArbFpSurfacePainter;
break;
# endif
#endif
case Generic:
GST_LOG_OBJECT(m_sink, "Creating Generic painter");
m_painter = new GenericSurfacePainter;
break;
default:
Q_ASSERT(false);
}
}
try {
m_painter->init(format);
return;
} catch (const QString & error) {
GST_ELEMENT_WARNING(m_sink, RESOURCE, FAILED,
("Failed to start painter"), ("%s", error.toUtf8().constData()));
delete m_painter;
m_painter = 0;
}
}
GST_ELEMENT_ERROR(m_sink, RESOURCE, FAILED,
("Failed to create a painter for the given format"), (NULL));
}
示例4: parse
bool QMimeTypeParserBase::parse(QIODevice *dev, const QString &fileName, QString *errorMessage)
{
QMimeTypePrivate data;
int priority = 50;
QStack<QMimeMagicRule *> currentRules; // stack for the nesting of rules
QList<QMimeMagicRule> rules; // toplevel rules
QXmlStreamReader reader(dev);
ParseState ps = ParseBeginning;
QXmlStreamAttributes atts;
while (!reader.atEnd()) {
switch (reader.readNext()) {
case QXmlStreamReader::StartElement:
ps = nextState(ps, reader.name());
atts = reader.attributes();
switch (ps) {
case ParseMimeType: { // start parsing a MIME type name
const QString name = atts.value(QLatin1String(mimeTypeAttributeC)).toString();
if (name.isEmpty()) {
reader.raiseError(QString::fromLatin1("Missing '%1'-attribute").arg(QString::fromLatin1(mimeTypeAttributeC)));
} else {
data.name = name;
}
}
break;
case ParseGenericIcon:
data.genericIconName = atts.value(QLatin1String(nameAttributeC)).toString();
break;
case ParseIcon:
data.iconName = atts.value(QLatin1String(nameAttributeC)).toString();
break;
case ParseGlobPattern: {
const QString pattern = atts.value(QLatin1String(patternAttributeC)).toString();
unsigned weight = atts.value(QLatin1String(weightAttributeC)).toString().toInt();
const bool caseSensitive = atts.value(QLatin1String(caseSensitiveAttributeC)).toString() == QLatin1String("true");
if (weight == 0)
weight = QMimeGlobPattern::DefaultWeight;
Q_ASSERT(!data.name.isEmpty());
const QMimeGlobPattern glob(pattern, data.name, weight, caseSensitive ? Qt::CaseSensitive : Qt::CaseInsensitive);
if (!process(glob, errorMessage)) // for actual glob matching
return false;
data.addGlobPattern(pattern); // just for QMimeType::globPatterns()
}
break;
case ParseSubClass: {
const QString inheritsFrom = atts.value(QLatin1String(mimeTypeAttributeC)).toString();
if (!inheritsFrom.isEmpty())
processParent(data.name, inheritsFrom);
}
break;
case ParseComment: {
// comments have locale attributes. We want the default, English one
QString locale = atts.value(QLatin1String(localeAttributeC)).toString();
const QString comment = reader.readElementText();
if (locale.isEmpty())
locale = QString::fromLatin1("en_US");
data.localeComments.insert(locale, comment);
}
break;
case ParseAlias: {
const QString alias = atts.value(QLatin1String(mimeTypeAttributeC)).toString();
if (!alias.isEmpty())
processAlias(alias, data.name);
}
break;
case ParseMagic: {
priority = 50;
const QString priorityS = atts.value(QLatin1String(priorityAttributeC)).toString();
if (!priorityS.isEmpty()) {
if (!parseNumber(priorityS, &priority, errorMessage))
return false;
}
currentRules.clear();
//qDebug() << "MAGIC start for mimetype" << data.name;
}
break;
case ParseMagicMatchRule: {
QMimeMagicRule *rule = 0;
if (!createMagicMatchRule(atts, errorMessage, rule))
return false;
QList<QMimeMagicRule> *ruleList;
if (currentRules.isEmpty())
ruleList = &rules;
else // nest this rule into the proper parent
ruleList = ¤tRules.top()->m_subMatches;
ruleList->append(*rule);
//qDebug() << " MATCH added. Stack size was" << currentRules.size();
currentRules.push(&ruleList->last());
delete rule;
break;
}
case ParseError:
reader.raiseError(QString::fromLatin1("Unexpected element <%1>").
arg(reader.name().toString()));
break;
default:
break;
}
//.........这里部分代码省略.........
示例5: calculPopupGeometry
void pTreeComboBox::calculPopupGeometry()
{
if ( !mView ) {
return;
}
QStyle * const style = this->style();
// set current item and select it
view()->selectionModel()->setCurrentIndex( mCurrentIndex, QItemSelectionModel::ClearAndSelect | QItemSelectionModel::Rows );
QFrame* container = mFrame;
QStyleOptionComboBox opt;
initStyleOption( &opt );
QRect listRect( style->subControlRect( QStyle::CC_ComboBox, &opt, QStyle::SC_ComboBoxListBoxPopup, this ) );
QRect screen = popupGeometry( QApplication::desktop()->screenNumber( this ) );
QPoint below = mapToGlobal( listRect.bottomLeft() );
int belowHeight = screen.bottom() -below.y();
QPoint above = mapToGlobal( listRect.topLeft() );
int aboveHeight = above.y() -screen.y();
bool boundToScreen = !window()->testAttribute( Qt::WA_DontShowOnScreen );
listRect.moveTopLeft( mapToGlobal( rect().bottomLeft() ) );
listRect.setSize( QSize(
qMax( qMax( view()->viewport()->width(), mFrame->width() ), width() )
,
qMax( view()->viewport()->height(), mFrame->height() )
) );
const bool usePopup = style->styleHint( QStyle::SH_ComboBox_Popup, &opt, this );
{
int listHeight = 0;
int count = 0;
QStack<QModelIndex> toCheck;
toCheck.push( view()->rootIndex() );
#ifndef QT_NO_TREEVIEW
QTreeView* treeView = qobject_cast<QTreeView*>( view() );
if ( treeView && treeView->header() && !treeView->header()->isHidden() )
listHeight += treeView->header()->height();
#endif
while ( !toCheck.isEmpty() ) {
QModelIndex parent = toCheck.pop();
for ( int i = 0; i < model()->rowCount( parent ); ++i ) {
QModelIndex idx = model()->index( i, mModelColumn, parent );
if ( !idx.isValid() )
continue;
listHeight += view()->visualRect( idx ).height();
#ifndef QT_NO_TREEVIEW
if ( model()->hasChildren( idx ) && treeView && treeView->isExpanded( idx ) )
toCheck.push( idx );
#endif
++count;
if ( !usePopup && count > mMaxVisibleItems ) {
toCheck.clear();
break;
}
}
}
listRect.setHeight( listHeight );
}
{
// add the spacing for the grid on the top and the bottom;
int heightMargin = 0;
// add the frame of the container
int marginTop, marginBottom;
container->getContentsMargins( 0, &marginTop, 0, &marginBottom );
heightMargin += marginTop +marginBottom;
//add the frame of the view
view()->getContentsMargins( 0, &marginTop, 0, &marginBottom );
marginTop += 0/*static_cast<QAbstractScrollAreaPrivate *>(QObjectPrivate::get(view()))->top*/;
marginBottom += 0/*static_cast<QAbstractScrollAreaPrivate *>(QObjectPrivate::get(view()))->bottom*/;
heightMargin += marginTop +marginBottom;
listRect.setHeight( listRect.height() +heightMargin );
}
// Add space for margin at top and bottom if the style wants it.
if ( usePopup )
listRect.setHeight( listRect.height() +style->pixelMetric( QStyle::PM_MenuVMargin, &opt, this ) *2 );
// Make sure the popup is wide enough to display its contents.
if ( usePopup ) {
const int diff = sizeHint().width() /*d->computeWidthHint()*/ -width();
if ( diff > 0 )
listRect.setWidth( listRect.width() +diff );
}
//we need to activate the layout to make sure the min/maximum size are set when the widget was not yet show
container->layout()->activate();
//takes account of the minimum/maximum size of the container
listRect.setSize( listRect.size().expandedTo(container->minimumSize())
.boundedTo(container->maximumSize()));
// make sure the widget fits on screen
if (boundToScreen) {
if (listRect.width() > screen.width() )
listRect.setWidth(screen.width());
if (/*mapToGlobal(*/listRect/*.bottomRight())*/.x() > screen.right()) {
//.........这里部分代码省略.........
示例6: on_equal_clicked
void fractin::on_equal_clicked()
{
QStack<QChar> t;
int d=0;
QString str=text;
QChar ch=text[0];
text.remove(0,1);
if((!ch.isDigit()&&ch!='(')||text.isEmpty()){
text="格式不支持!";
ui->show->setText(text);
return;
}
while(!text.isEmpty()){
if(ch.isDigit()){
while(ch.isDigit()&&!text.isEmpty()){
ch=text[0];
text.remove(0,1);
}
if(ch!='|'||text.isEmpty()){
text="格式不支持!";
ui->show->setText(text);
return;
}
ch=text[0];
text.remove(0,1);
if(!ch.isDigit()){
text="格式不支持!";
ui->show->setText(text);
return;
}
while(ch.isDigit()&&!text.isEmpty()){
d=d*10+ch.unicode()-48;
ch=text[0];
text.remove(0,1);
}
if(ch.isDigit())
d=d*10+ch.unicode()-48;
if(d==0){
text="分母不能为零!";
ui->show->setText(text);
return;
}
if(ch=='.'||ch=='('||ch=='|'){
text="格式不支持!";
ui->show->setText(text);
return;
}
continue;
}
if(ch=='+'||ch=='-'||ch=='*'||ch=='/'){
if(text.isEmpty()){
text="格式不支持!";
ui->show->setText(text);
return;
}
ch=text[0];
text.remove(0,1);
if(!(ch.isDigit()||ch=='(')){
text="格式不支持!";
ui->show->setText(text);
return;
}
continue;
}
if(ch=='('){
t.push(ch);
if(text.isEmpty()){
text="格式不支持!";
ui->show->setText(text);
return;
}
ch=text[0];
text.remove(0,1);
if(!ch.isDigit()&&ch!='('){
text="格式不支持!";
ui->show->setText(text);
return;
}
continue;
}
if(ch==')'){
if(t.isEmpty()){
text="格式不支持!";
ui->show->setText(text);
return;
}
else{
t.pop();
if(!text.isEmpty()){
ch=text[0];
text.remove(0,1);
if(ch!='+'&&ch!='-'&&ch!='*'&&ch!='/'&&ch!=')'){
text="格式不支持!";
ui->show->setText(text);
return;
}
}
continue;
}
//.........这里部分代码省略.........
示例7: start
void OwncloudPropagator::start(const SyncFileItemVector& items)
{
Q_ASSERT(std::is_sorted(items.begin(), items.end()));
/* Check and log the transmission checksum type */
ConfigFile cfg;
const QString checksumType = cfg.transmissionChecksum().toUpper();
/* if the checksum type is empty, it is not send. No error */
if( !checksumType.isEmpty() ) {
if( checksumType == checkSumAdlerUpperC ||
checksumType == checkSumMD5C ||
checksumType == checkSumSHA1C ) {
qDebug() << "Client sends and expects transmission checksum type" << checksumType;
} else {
qWarning() << "Unknown transmission checksum type from config" << checksumType;
}
}
/* This builds all the job needed for the propagation.
* Each directories is a PropagateDirectory job, which contains the files in it.
* In order to do that we loop over the items. (which are sorted by destination)
* When we enter adirectory, we can create the directory job and push it on the stack. */
_rootJob.reset(new PropagateDirectory(this));
QStack<QPair<QString /* directory name */, PropagateDirectory* /* job */> > directories;
directories.push(qMakePair(QString(), _rootJob.data()));
QVector<PropagatorJob*> directoriesToRemove;
QString removedDirectory;
foreach(const SyncFileItemPtr &item, items) {
if (!removedDirectory.isEmpty() && item->_file.startsWith(removedDirectory)) {
// this is an item in a directory which is going to be removed.
PropagateDirectory *delDirJob = dynamic_cast<PropagateDirectory*>(directoriesToRemove.last());
if (item->_instruction == CSYNC_INSTRUCTION_REMOVE) {
//already taken care of. (by the removal of the parent directory)
// increase the number of subjobs that would be there.
if( delDirJob ) {
delDirJob->increaseAffectedCount();
}
continue;
} else if (item->_instruction == CSYNC_INSTRUCTION_NEW && item->_isDirectory) {
// create a new directory within a deleted directory? That can happen if the directory
// etag were not fetched properly on the previous sync because the sync was aborted
// while uploading this directory (which is now removed). We can ignore it.
if( delDirJob ) {
delDirJob->increaseAffectedCount();
}
continue;
} else if (item->_instruction == CSYNC_INSTRUCTION_IGNORE) {
continue;
}
qWarning() << "WARNING: Job within a removed directory? This should not happen!"
<< item->_file << item->_instruction;
}
while (!item->destination().startsWith(directories.top().first)) {
directories.pop();
}
if (item->_isDirectory) {
PropagateDirectory *dir = new PropagateDirectory(this, item);
dir->_firstJob.reset(createJob(item));
if (item->_instruction == CSYNC_INSTRUCTION_REMOVE) {
//We do the removal of directories at the end, because there might be moves from
// this directories that will happen later.
directoriesToRemove.append(dir);
removedDirectory = item->_file + "/";
// We should not update the etag of parent directories of the removed directory
// since it would be done before the actual remove (issue #1845)
// NOTE: Currently this means that we don't update those etag at all in this sync,
// but it should not be a problem, they will be updated in the next sync.
for (int i = 0; i < directories.size(); ++i) {
directories[i].second->_item->_should_update_metadata = false;
}
} else {
PropagateDirectory* currentDirJob = directories.top().second;
currentDirJob->append(dir);
}
directories.push(qMakePair(item->destination() + "/" , dir));
} else if (PropagateItemJob* current = createJob(item)) {
directories.top().second->append(current);
}
}
foreach(PropagatorJob* it, directoriesToRemove) {
_rootJob->append(it);
}
示例8: setCustomData
void QDeclarativeListModelParser::setCustomData(QObject *obj, const QByteArray &d)
{
QDeclarativeListModel *rv = static_cast<QDeclarativeListModel *>(obj);
ModelNode *root = new ModelNode(rv->m_nested);
rv->m_nested->_root = root;
QStack<ModelNode *> nodes;
nodes << root;
bool processingSet = false;
const ListModelData *lmd = (const ListModelData *)d.constData();
const char *data = ((const char *)lmd) + lmd->dataOffset;
for (int ii = 0; ii < lmd->instrCount; ++ii) {
const ListInstruction &instr = lmd->instructions()[ii];
switch(instr.type) {
case ListInstruction::Push:
{
ModelNode *n = nodes.top();
ModelNode *n2 = new ModelNode(rv->m_nested);
n->values << QVariant::fromValue(n2);
nodes.push(n2);
if (processingSet)
n->isArray = true;
}
break;
case ListInstruction::Pop:
nodes.pop();
break;
case ListInstruction::Value:
{
ModelNode *n = nodes.top();
switch (QDeclarativeParser::Variant::Type(data[instr.dataIdx])) {
case QDeclarativeParser::Variant::Invalid:
n->isArray = true;
break;
case QDeclarativeParser::Variant::Boolean:
n->values.append(bool(data[1 + instr.dataIdx]));
break;
case QDeclarativeParser::Variant::Number:
n->values.append(QByteArray(data + 1 + instr.dataIdx).toDouble());
break;
case QDeclarativeParser::Variant::String:
n->values.append(QString::fromUtf8(data + 1 + instr.dataIdx));
break;
default:
Q_ASSERT("Format error in ListInstruction");
}
processingSet = false;
}
break;
case ListInstruction::Set:
{
ModelNode *n = nodes.top();
ModelNode *n2 = new ModelNode(rv->m_nested);
n->properties.insert(QString::fromUtf8(data + instr.dataIdx), n2);
nodes.push(n2);
processingSet = true;
}
break;
}
}
ModelNode *rootNode = rv->m_nested->_root;
for (int i=0; i<rootNode->values.count(); ++i) {
ModelNode *node = qvariant_cast<ModelNode *>(rootNode->values[i]);
node->listIndex = i;
node->updateListIndexes();
}
}
示例9: loadData
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;
//.........这里部分代码省略.........
示例10: parse
static void parse( Translator *tor )
{
QString text;
QString com;
QString extracomment;
yyCh = getChar();
yyTok = getToken();
while ( yyTok != Tok_Eof ) {
switch ( yyTok ) {
case Tok_class:
yyTok = getToken();
if(yyTok == Tok_Ident) {
yyScope.push(new Scope(yyIdent, Scope::Clazz, yyLineNo));
}
else {
yyMsg() << qPrintable(LU::tr("'class' must be followed by a class name.\n"));
break;
}
while (!match(Tok_LeftBrace)) {
yyTok = getToken();
}
break;
case Tok_tr:
yyTok = getToken();
if ( match(Tok_LeftParen) && matchString(text) ) {
com.clear();
bool plural = false;
if ( match(Tok_RightParen) ) {
// no comment
} else if (match(Tok_Comma) && matchStringOrNull(com)) { //comment
if ( match(Tok_RightParen)) {
// ok,
} else if (match(Tok_Comma)) {
plural = true;
}
}
if (!text.isEmpty())
recordMessage(tor, context(), text, com, extracomment, plural);
}
break;
case Tok_translate:
{
QString contextOverride;
yyTok = getToken();
if ( match(Tok_LeftParen) &&
matchString(contextOverride) &&
match(Tok_Comma) &&
matchString(text) ) {
com.clear();
bool plural = false;
if (!match(Tok_RightParen)) {
// look for comment
if ( match(Tok_Comma) && matchStringOrNull(com)) {
if (!match(Tok_RightParen)) {
if (match(Tok_Comma) && matchExpression() && match(Tok_RightParen)) {
plural = true;
} else {
break;
}
}
} else {
break;
}
}
if (!text.isEmpty())
recordMessage(tor, contextOverride, text, com, extracomment, plural);
}
}
break;
case Tok_Ident:
yyTok = getToken();
break;
case Tok_Comment:
if (yyComment.startsWith(QLatin1Char(':'))) {
yyComment.remove(0, 1);
extracomment.append(yyComment);
}
yyTok = getToken();
break;
case Tok_RightBrace:
if ( yyScope.isEmpty() ) {
yyMsg() << qPrintable(LU::tr("Excess closing brace.\n"));
}
else
delete (yyScope.pop());
extracomment.clear();
yyTok = getToken();
break;
case Tok_LeftBrace:
yyScope.push(new Scope(QString(), Scope::Other, yyLineNo));
yyTok = getToken();
//.........这里部分代码省略.........
示例11: addGroupFilter
bool OsmAnd::MapStyle_P::parse( QXmlStreamReader& xmlReader )
{
auto rulesetType = MapStyleRulesetType::Invalid;
struct Lexeme
{
enum Type
{
Rule,
Group,
};
Lexeme(Type type_, MapStyle_P* style_)
: type(type_)
, style(style_)
{}
const Type type;
MapStyle_P* const style;
};
struct Rule : public Lexeme
{
Rule(std::shared_ptr<MapStyleRule> rule_, MapStyle_P* style_)
: Lexeme(Lexeme::Rule, style_)
, rule(rule_)
{}
const std::shared_ptr<MapStyleRule> rule;
};
struct Group : public Lexeme
{
Group(MapStyle_P* const style_)
: Lexeme(Lexeme::Group, style_)
{}
QHash< QString, QString > attributes;
QList< std::shared_ptr<MapStyleRule> > children;
QList< std::shared_ptr<Lexeme> > subgroups;
void addGroupFilter(const std::shared_ptr<MapStyleRule>& rule)
{
for(auto itChild = children.cbegin(); itChild != children.cend(); ++itChild)
{
auto child = *itChild;
child->_d->_ifChildren.push_back(rule);
}
for(auto itSubgroup = subgroups.cbegin(); itSubgroup != subgroups.cend(); ++itSubgroup)
{
auto subgroup = *itSubgroup;
assert(subgroup->type == Lexeme::Group);
std::static_pointer_cast<Group>(subgroup)->addGroupFilter(rule);
}
}
bool registerGlobalRules(const MapStyleRulesetType type)
{
for(auto itChild = children.cbegin(); itChild != children.cend(); ++itChild)
{
auto child = *itChild;
if(!style->registerRule(type, child))
return false;
}
for(auto itSubgroup = subgroups.cbegin(); itSubgroup != subgroups.cend(); ++itSubgroup)
{
auto subgroup = *itSubgroup;
assert(subgroup->type == Lexeme::Group);
if(!std::static_pointer_cast<Group>(subgroup)->registerGlobalRules(type))
return false;
}
return true;
}
};
QStack< std::shared_ptr<Lexeme> > stack;
while (!xmlReader.atEnd() && !xmlReader.hasError())
{
xmlReader.readNext();
const auto tagName = xmlReader.name();
if (xmlReader.isStartElement())
{
if(tagName == QLatin1String("renderingStyle"))
{
// We have already parsed metadata and resolved dependencies, so here we don't need to do anything
}
else if(tagName == QLatin1String("renderingConstant"))
{
const auto& attribs = xmlReader.attributes();
auto name = attribs.value(QLatin1String("name")).toString();
auto value = attribs.value(QLatin1String("value")).toString();
//.........这里部分代码省略.........
示例12: indent
void ScCodeEditor::indent( const QTextCursor & selection )
{
if (selection.isNull())
return;
QTextCursor cursor(selection);
cursor.beginEditBlock();
QTextDocument *doc = QPlainTextEdit::document();
int startBlockNum = doc->findBlock(cursor.selectionStart()).blockNumber();
int endBlockNum = cursor.hasSelection() ?
doc->findBlock(cursor.selectionEnd()).blockNumber() : startBlockNum;
QStack<int> stack;
int level = 0;
int blockNum = 0;
QTextBlock block = QPlainTextEdit::document()->begin();
while (block.isValid())
{
if (level > 0) {
stack.push(level);
level = 0;
}
int initialStackSize = stack.size();
TextBlockData *data = static_cast<TextBlockData*>(block.userData());
if (data)
{
int count = data->tokens.size();
for (int idx = 0; idx < count; ++idx)
{
const Token & token = data->tokens[idx];
switch (token.type)
{
case Token::OpeningBracket:
if (token.character != '(' || stack.size() || token.positionInBlock)
level += 1;
break;
case Token::ClosingBracket:
if (level)
level -= 1;
else if(!stack.isEmpty()) {
stack.top() -= 1;
if (stack.top() <= 0)
stack.pop();
}
break;
default:
;
}
}
}
if(blockNum >= startBlockNum) {
int indentLevel;
if (data && data->tokens.size() && data->tokens[0].type == Token::ClosingBracket)
indentLevel = stack.size();
else
indentLevel = initialStackSize;
block = indent(block, indentLevel);
}
if(blockNum == endBlockNum)
break;
block = block.next();
++blockNum;
}
cursor.endEditBlock();
}
示例13: copyNodeTo
void AccelTree::copyNodeTo(const QXmlNodeModelIndex &node,
QAbstractXmlReceiver *const receiver,
const NodeCopySettings &settings) const
{
/* This code piece can be seen as a customized version of
* QAbstractXmlReceiver::item/sendAsNode(). */
Q_ASSERT(receiver);
Q_ASSERT(!node.isNull());
typedef QHash<QXmlName::PrefixCode, QXmlName::NamespaceCode> Binding;
QStack<Binding> outputted;
switch(node.kind())
{
case QXmlNodeModelIndex::Element:
{
outputted.push(Binding());
/* Add the namespace for our element name. */
const QXmlName elementName(node.name());
receiver->startElement(elementName);
if(!settings.testFlag(InheritNamespaces))
receiver->namespaceBinding(QXmlName(StandardNamespaces::StopNamespaceInheritance, 0,
StandardPrefixes::StopNamespaceInheritance));
if(settings.testFlag(PreserveNamespaces))
node.sendNamespaces(receiver);
else
{
/* Find the namespaces that we actually use and add them to outputted. These are drawn
* from the element name, and the node's attributes. */
outputted.top().insert(elementName.prefix(), elementName.namespaceURI());
const QXmlNodeModelIndex::Iterator::Ptr attributes(iterate(node, QXmlNodeModelIndex::AxisAttribute));
QXmlNodeModelIndex attr(attributes->next());
while(!attr.isNull())
{
const QXmlName &attrName = attr.name();
outputted.top().insert(attrName.prefix(), attrName.namespaceURI());
attr = attributes->next();
}
Binding::const_iterator it(outputted.top().constBegin());
const Binding::const_iterator end(outputted.top().constEnd());
for(; it != end; ++it)
receiver->namespaceBinding(QXmlName(it.value(), 0, it.key()));
}
/* Send the attributes of the element. */
{
QXmlNodeModelIndex::Iterator::Ptr attributes(node.iterate(QXmlNodeModelIndex::AxisAttribute));
QXmlNodeModelIndex attribute(attributes->next());
while(!attribute.isNull())
{
const QString &v = attribute.stringValue();
receiver->attribute(attribute.name(), QStringRef(&v));
attribute = attributes->next();
}
}
/* Send the children of the element. */
copyChildren(node, receiver, settings);
receiver->endElement();
outputted.pop();
break;
}
case QXmlNodeModelIndex::Document:
{
/* We need to intercept and grab the elements of the document node, such
* that we preserve/inherit preference applies to them. */
receiver->startDocument();
copyChildren(node, receiver, settings);
receiver->endDocument();
break;
}
default:
receiver->item(node);
}
}
示例14: simplify
QPolygonF QwtWeedingCurveFitter::simplify( const QPolygonF &points ) const
{
const double toleranceSqr = d_data->tolerance * d_data->tolerance;
QStack<Line> stack;
stack.reserve( 500 );
const QPointF *p = points.data();
const int nPoints = points.size();
QVector<bool> usePoint( nPoints, false );
stack.push( Line( 0, nPoints - 1 ) );
while ( !stack.isEmpty() )
{
const Line r = stack.pop();
// initialize line segment
const double vecX = p[r.to].x() - p[r.from].x();
const double vecY = p[r.to].y() - p[r.from].y();
const double vecLength = qSqrt( vecX * vecX + vecY * vecY );
const double unitVecX = ( vecLength != 0.0 ) ? vecX / vecLength : 0.0;
const double unitVecY = ( vecLength != 0.0 ) ? vecY / vecLength : 0.0;
double maxDistSqr = 0.0;
int nVertexIndexMaxDistance = r.from + 1;
for ( int i = r.from + 1; i < r.to; i++ )
{
//compare to anchor
const double fromVecX = p[i].x() - p[r.from].x();
const double fromVecY = p[i].y() - p[r.from].y();
double distToSegmentSqr;
if ( fromVecX * unitVecX + fromVecY * unitVecY < 0.0 )
{
distToSegmentSqr = fromVecX * fromVecX + fromVecY * fromVecY;
}
else
{
const double toVecX = p[i].x() - p[r.to].x();
const double toVecY = p[i].y() - p[r.to].y();
const double toVecLength = toVecX * toVecX + toVecY * toVecY;
const double s = toVecX * ( -unitVecX ) + toVecY * ( -unitVecY );
if ( s < 0.0 )
{
distToSegmentSqr = toVecLength;
}
else
{
distToSegmentSqr = qFabs( toVecLength - s * s );
}
}
if ( maxDistSqr < distToSegmentSqr )
{
maxDistSqr = distToSegmentSqr;
nVertexIndexMaxDistance = i;
}
}
if ( maxDistSqr <= toleranceSqr )
{
usePoint[r.from] = true;
usePoint[r.to] = true;
}
else
{
stack.push( Line( r.from, nVertexIndexMaxDistance ) );
stack.push( Line( nVertexIndexMaxDistance, r.to ) );
}
}
QPolygonF stripped;
for ( int i = 0; i < nPoints; i++ )
{
if ( usePoint[i] )
stripped += p[i];
}
return stripped;
}
示例15: insertStone
/*
* Returns: true - son of current move was found
* false -
*/
bool Tree::insertStone(Move *node)
{
if (root == NULL)
{
qFatal("Error: No root!");
return false;
}
else
{
if (current == NULL)
{
qFatal("Error: No current node!");
return false;
}
// current node has no son?
if (current->son == NULL)
{
if(current == node)
{
qDebug("Attempting to add move as its own son!");
return false;
}
current->son = node;
node->parent = current;
node->setTimeinfo(false);
current = node;
node->getMatrix()->insertStone(node->getX(), node->getY(), node->getColor());
return false;
}
// A son found
else
{
//we insert node between current and current->son
node->parent = current;
node->son = current->son;
current->son->parent = node;
current->son = node;
//update all brothers to enable switching between them
Move *t = node->son->brother;
while (t != NULL)
{
t->parent = node;
t = t->brother;
}
current->parent->marker = current;
node->marker = NULL;
node->setTimeinfo(false);
current = node;
node->getMatrix()->insertStone(node->getX(), node->getY(), node->getColor());
//update son - it is exclude from traverse search because we cannot update brothers of node->son
node->son->setMoveNumber(node->son->getMoveNumber()+1);
node->son->getMatrix()->insertStone(node->getX(), node->getY(), node->getColor());
if (node->son->son != NULL)
{
// Traverse the tree and update every node (matrix and moveNum)
QStack<Move*> stack;
Move *t = NULL;
stack.push(node->son->son);
while (!stack.isEmpty())
{
t = stack.pop();
if (t != NULL)
{
if (t->brother != NULL)
stack.push(t->brother);
if (t->son != NULL)
stack.push(t->son);
t->setMoveNumber(t->getMoveNumber()+1);
t->getMatrix()->insertStone(node->getX(), node->getY(), node->getColor());
}
}
}
return true;
}
}
}