void DocxReader::readParagraphProperties(Style& style, bool allowstyles) { int left_indent = 0, right_indent = 0, indent = 0; bool textdir = false; while (m_xml.readNextStartElement()) { QStringRef value = m_xml.attributes().value("w:val"); if (m_xml.qualifiedName() == "w:jc") { // ECMA-376 1st edition, ECMA-376 2nd edition transitional, ISO/IEC 29500 transitional if (value == "left") { style.block_format.setAlignment(!textdir ? Qt::AlignLeading : (Qt::AlignLeft | Qt::AlignAbsolute)); } else if (value == "right") { style.block_format.setAlignment(!textdir ? Qt::AlignTrailing : (Qt::AlignRight | Qt::AlignAbsolute)); // ECMA-376, ISO/IEC 29500 strict } else if (value == "center") { style.block_format.setAlignment(Qt::AlignCenter); } else if (value == "both") { style.block_format.setAlignment(Qt::AlignJustify); // ECMA-376 2nd edition, ISO/IEC 29500 strict } else if (value == "start") { style.block_format.setAlignment(Qt::AlignLeading); } else if (value == "end") { style.block_format.setAlignment(Qt::AlignTrailing); } } else if (m_xml.qualifiedName() == "w:ind") { // ECMA-376 1st edition, ECMA-376 2nd edition transitional, ISO/IEC 29500 transitional left_indent = std::lround(m_xml.attributes().value("w:left").toString().toDouble() / 720.0); right_indent = std::lround(m_xml.attributes().value("w:right").toString().toDouble() / 720.0); // ECMA-376 2nd edition, ISO/IEC 29500 strict indent = std::lround(m_xml.attributes().value("w:start").toString().toDouble() / 720.0); if (indent) { style.block_format.setIndent(indent); left_indent = right_indent = 0; } } else if (m_xml.qualifiedName() == "w:bidi") { if (readBool(m_xml.attributes().value("w:val"))) { style.block_format.setLayoutDirection(Qt::RightToLeft); } } else if (m_xml.qualifiedName() == "w:textDirection") { if (value == "rl") { textdir = true; style.block_format.setLayoutDirection(Qt::RightToLeft); } else if (value == "lr") { style.block_format.setLayoutDirection(Qt::LeftToRight); } } else if (m_xml.qualifiedName() == "w:outlineLvl") { int heading = m_xml.attributes().value("w:val").toString().toInt(); if (heading != 9) { style.block_format.setProperty(QTextFormat::UserProperty, qBound(1, heading + 1, 6)); } } else if ((m_xml.qualifiedName() == "w:pStyle") && allowstyles) { Style pstyle = m_styles.value(value.toString()); pstyle.merge(style); style = pstyle; } else if (m_xml.qualifiedName() == "w:rPr") { readRunProperties(style); continue; } m_xml.skipCurrentElement(); } if (!indent) { if (style.block_format.layoutDirection() != Qt::RightToLeft) { if (left_indent) { style.block_format.setIndent(left_indent); } } else { if (right_indent) { style.block_format.setIndent(right_indent); } } } if (style.block_format.property(QTextFormat::UserProperty).toInt()) { style.char_format.setFontWeight(QFont::Normal); } }
TextWithEntities MentionNameClickHandler::getExpandedLinkTextWithEntities(ExpandLinksMode mode, int entityOffset, const QStringRef &textPart) const { auto data = QString::number(_userId) + '.' + QString::number(_accessHash); return simpleTextWithEntity({ EntityInTextMentionName, entityOffset, textPart.size(), data }); }
void SpellChecker::check() { setDisabled(true); QProgressDialog wait_dialog(tr("Checking spelling..."), tr("Cancel"), 0, m_total_blocks, this); wait_dialog.setWindowTitle(tr("Please wait")); wait_dialog.setValue(0); wait_dialog.setWindowModality(Qt::WindowModal); bool canceled = false; forever { // Update wait dialog wait_dialog.setValue(m_checked_blocks); if (wait_dialog.wasCanceled()) { canceled = true; break; } // Check current line QTextBlock block = m_cursor.block(); QStringRef word = m_dictionary.check(block.text(), m_cursor.position() - block.position()); if (word.isNull()) { if (block.next().isValid()) { m_cursor.movePosition(QTextCursor::NextBlock); ++m_checked_blocks; if (m_checked_blocks < m_total_blocks) { continue; } else { break; } } else if (m_loop_available) { wait_dialog.reset(); if (QMessageBox::question(this, QString(), tr("Continue checking at beginning of file?"), QMessageBox::Yes | QMessageBox::No, QMessageBox::Yes) == QMessageBox::Yes) { m_loop_available = false; m_cursor.movePosition(QTextCursor::Start); wait_dialog.setRange(0, m_total_blocks); continue; } else { canceled = true; break; } } else { break; } } // Select misspelled word m_cursor.setPosition(word.position() + block.position()); m_cursor.setPosition(m_cursor.position() + word.length(), QTextCursor::KeepAnchor); m_word = m_cursor.selectedText(); if (!m_ignored.contains(m_word)) { wait_dialog.close(); setEnabled(true); // Show misspelled word in context QTextCursor cursor = m_cursor; cursor.movePosition(QTextCursor::PreviousWord, QTextCursor::MoveAnchor, 10); int end = m_cursor.position() - cursor.position(); int start = end - m_word.length(); cursor.movePosition(QTextCursor::NextWord, QTextCursor::KeepAnchor, 21); QString context = cursor.selectedText(); context.insert(end, "</span>"); context.insert(start, "<span style=\"color: red;\">"); context.replace("\n", "</p><p>"); context.replace("\t", "<span style=\"white-space: pre;\">\t</span>"); context = "<p>" + context + "</p>"; m_context->setHtml(context); // Show suggestions m_suggestion->clear(); m_suggestions->clear(); QStringList words = m_dictionary.suggestions(m_word); if (!words.isEmpty()) { foreach (const QString& word, words) { m_suggestions->addItem(word); } m_suggestions->setCurrentRow(0); }
bool QmcTypeUnitComponentAndAliasResolver::addAliases() { // add aliases //QmcUnitAlias al = {0, 0, 0, 8, 0, 0, 24}; //qmcTypeUnit->unit->aliases.append(al); // see QQmlComponentAndAliasResolver::resolve int effectiveAliasIndex = -1; int effectivePropertyIndex = -1; int effectiveSignalIndex = -1; int currentObjectIndex = -1; QQmlPropertyCache *propertyCache = NULL; foreach (const QmcUnitAlias &alias, qmcTypeUnit->unit->aliases) { if ((int)alias.objectIndex != currentObjectIndex) { currentObjectIndex = alias.objectIndex; effectiveAliasIndex = 0; propertyCache = qmcTypeUnit->propertyCaches.at(alias.objectIndex); effectivePropertyIndex = propertyCache->propertyIndexCacheStart + propertyCache->propertyIndexCache.count(); effectiveSignalIndex = propertyCache->signalHandlerIndexCacheStart + propertyCache->propertyIndexCache.count(); } Q_ASSERT(propertyCache); QQmlVMEMetaData::AliasData aliasData; aliasData.contextIdx = alias.contextIndex; aliasData.propertyIdx = alias.targetPropertyIndex; aliasData.propType = alias.propertyType; aliasData.flags = alias.flags; aliasData.notifySignal = alias.notifySignal; typedef QQmlVMEMetaData VMD; QByteArray &dynamicData = qmcTypeUnit->vmeMetaObjects[alias.objectIndex]; Q_ASSERT(!dynamicData.isEmpty()); VMD *vmd = (QQmlVMEMetaData *)dynamicData.data(); *(vmd->aliasData() + effectiveAliasIndex++) = aliasData; Q_ASSERT(dynamicData.isDetached()); // TBD: propertyCache const QV4::CompiledData::Object *obj = qmcTypeUnit->compiledData->qmlUnit->objectAt(alias.objectIndex); Q_ASSERT(obj); Q_ASSERT(alias.propertyIndex < obj->nProperties); const QV4::CompiledData::Property *p = &obj->propertyTable()[alias.propertyIndex]; Q_ASSERT(p); QString propertyName = qmcTypeUnit->stringAt(p->nameIndex); const QString aliasPropertyValue = qmcTypeUnit->stringAt(p->aliasPropertyValueIndex); //const int idIndex = p->aliasIdValueIndex; const int targetObjectIndex = alias.targetObjectIndex; #if 0 const int idIndex = p->aliasIdValueIndex; const int targetObjectIndex = _idToObjectIndex.value(idIndex, -1); if (targetObjectIndex == -1) { recordError(p->aliasLocation, tr("Invalid alias reference. Unable to find id \"%1\"").arg(stringAt(idIndex))); return false; } #endif QStringRef property; QStringRef subProperty; const int propertySeparator = aliasPropertyValue.indexOf(QLatin1Char('.')); if (propertySeparator != -1) { property = aliasPropertyValue.leftRef(propertySeparator); subProperty = aliasPropertyValue.midRef(propertySeparator + 1); } else property = QStringRef(&aliasPropertyValue, 0, aliasPropertyValue.length()); quint32 propertyFlags = QQmlPropertyData::IsAlias; int type = 0; bool writable = false; bool resettable = false; if (property.isEmpty()) { const QV4::CompiledData::Object *targetObject = qmcTypeUnit->compiledData->qmlUnit->objectAt(targetObjectIndex); QQmlCompiledData::TypeReference *typeRef = qmcTypeUnit->compiledData->resolvedTypes.value(targetObject->inheritedTypeNameIndex); Q_ASSERT(typeRef); if (typeRef->type) type = typeRef->type->typeId(); else type = typeRef->component->metaTypeId; //flags |= QML_ALIAS_FLAG_PTR; propertyFlags |= QQmlPropertyData::IsQObjectDerived; } else { QQmlPropertyCache *targetCache = qmcTypeUnit->propertyCaches.at(targetObjectIndex); Q_ASSERT(targetCache); QmlIR::PropertyResolver resolver(targetCache); QQmlPropertyData *targetProperty = resolver.property(property.toString()); if (!targetProperty || targetProperty->coreIndex > 0x0000FFFF) { return false; } //propIdx = targetProperty->coreIndex; type = targetProperty->propType; writable = targetProperty->isWritable(); resettable = targetProperty->isResettable(); //notifySignal = targetProperty->notifyIndex; if (!subProperty.isEmpty()) { QQmlValueType *valueType = QQmlValueTypeFactory::valueType(type); if (!valueType) { return false; } //propType = type; int valueTypeIndex = valueType->metaObject()->indexOfProperty(subProperty.toString().toUtf8().constData()); if (valueTypeIndex == -1) { return false; } Q_ASSERT(valueTypeIndex <= 0x0000FFFF); //propIdx |= (valueTypeIndex << 16); if (valueType->metaObject()->property(valueTypeIndex).isEnumType()) type = QVariant::Int; else type = valueType->metaObject()->property(valueTypeIndex).userType(); } else { if (targetProperty->isEnum()) { type = QVariant::Int; } else { // Copy type flags propertyFlags |= targetProperty->getFlags() & QQmlPropertyData::PropTypeFlagMask; if (targetProperty->isVarProperty()) propertyFlags |= QQmlPropertyData::IsQVariant; #if 0 if (targetProperty->isQObject()) flags |= QML_ALIAS_FLAG_PTR; #endif } } } if (!(p->flags & QV4::CompiledData::Property::IsReadOnly) && writable) propertyFlags |= QQmlPropertyData::IsWritable; else propertyFlags &= ~QQmlPropertyData::IsWritable; if (resettable) propertyFlags |= QQmlPropertyData::IsResettable; else propertyFlags &= ~QQmlPropertyData::IsResettable; if ((int)alias.propertyIndex == obj->indexOfDefaultProperty) propertyCache->_defaultPropertyName = propertyName; propertyCache->appendProperty(propertyName, propertyFlags, effectivePropertyIndex++, type, effectiveSignalIndex++); } return true; }
bool Metalink4Handler::parseFile( QList<MetaFile>& lFiles, quint16 ID ) { MetaFile oCurrentFile( ID ); while ( m_oMetaLink.readNextStartElement() ) { QStringRef sComp = m_oMetaLink.name(); QXmlStreamAttributes vAttributes = m_oMetaLink.attributes(); if ( !sComp.compare( "hash" ) ) { if ( vAttributes.hasAttribute( "type" ) ) { const QString sType = vAttributes.value( "type" ).toString().trimmed(); const QString sUrn = "urn:" + sType + ":" + m_oMetaLink.readElementText(); Hash* pHash = Hash::fromURN( sUrn ); if ( pHash ) { if ( !oCurrentFile.m_vHashes.insert( pHash ) ) { postParsingInfo( m_oMetaLink.lineNumber(), tr( "Found and ignored conflicting hash of type \"%1\" within <hash> tag." ).arg( sType ) ); } } else { postParsingInfo( m_oMetaLink.lineNumber(), tr( "Found unsupported hash of type \"%1\" within <hash> tag." ).arg( sType ) ); continue; } } else { postParsingError( m_oMetaLink.lineNumber(), tr( "<hash> tag is missing type specification." ) ); continue; } } else if ( !sComp.compare( "url" ) ) { MediaURI uri; uri.m_nType = uriURL; uri.m_pURL = new QUrl( m_oMetaLink.readElementText() ); if ( uri.m_pURL->isValid() ) { if ( vAttributes.hasAttribute( "location" ) ) { uri.m_sLocation = vAttributes.value( "location" ).toString().trimmed(); } if ( vAttributes.hasAttribute( "priority" ) ) { bool bOK; quint16 nPriority = vAttributes.value( "priority" ).toString().toUShort( &bOK ); if ( bOK && nPriority < 256 ) { uri.m_nPriority = nPriority; } else { postParsingError( m_oMetaLink.lineNumber(), tr( "\"priority\" attribute within <url> tag could not be parsed." ) ); } } oCurrentFile.m_lURIs.append( uri ); } else { postParsingError( m_oMetaLink.lineNumber(), tr( "Could not parse invalid URL: %1" ).arg( uri.m_pURL->toString() ) ); delete uri.m_pURL; continue; } } else if ( !sComp.compare( "size" ) ) { bool bOK; quint64 nFileSize = m_oMetaLink.readElementText().toULongLong( &bOK ); if ( bOK ) { oCurrentFile.m_nFileSize = nFileSize; } else { postParsingError( m_oMetaLink.lineNumber(), tr( "<size> tag could not be parsed." ) ); continue; } } else if ( !sComp.compare( "identity" ) ) { oCurrentFile.m_sIdentity = m_oMetaLink.readElementText(); } else if ( !sComp.compare( "description" ) ) { oCurrentFile.m_sDescription = m_oMetaLink.readElementText(); } else if ( !sComp.compare( "language" ) ) { oCurrentFile.m_sLanguage = m_oMetaLink.readElementText(); } else if ( !sComp.compare( "version" ) ) { oCurrentFile.m_sVersion = m_oMetaLink.readElementText(); } else if ( !sComp.compare( "metaurl" ) ) { if ( vAttributes.hasAttribute( "mediatype" ) ) { MediaURI uri; QString sMediaType = vAttributes.value( "mediatype" ).toString().trimmed(); if ( !sMediaType.compare( "torrent" ) ) { uri.m_nType = uriTorrent; uri.m_pTorrent = new QUrl( m_oMetaLink.readElementText() ); if ( !uri.m_pTorrent->isValid() ) { postParsingError( m_oMetaLink.lineNumber(), tr( "Could not parse invalid torrent URL: %1" ).arg( uri.m_pTorrent->toString() ) ); delete uri.m_pTorrent; continue; } } else if ( !sMediaType.compare( "magnet" ) ) { uri.m_nType = uriMagnet; uri.m_pMagnet = new Magnet( m_oMetaLink.readElementText() ); if ( !uri.m_pMagnet->isValid() ) { postParsingError( m_oMetaLink.lineNumber(), tr( "Could not parse magnet link: %1" ).arg( uri.m_pMagnet->toString() ) ); delete uri.m_pMagnet; continue; } } else { postParsingError( m_oMetaLink.lineNumber(), tr( "Found unknown media type \"%1\" within <metaurl> tag." ).arg( sMediaType ) ); continue; } if ( vAttributes.hasAttribute( "priority" ) ) { bool bOK; quint16 nPriority = vAttributes.value( "priority" ).toString().toUShort( &bOK ); if ( bOK && nPriority < 256 ) { uri.m_nPriority = nPriority; } else { postParsingError( m_oMetaLink.lineNumber(), tr( "\"priority\" attribute within <metaurl> tag could not be parsed." ) ); } } oCurrentFile.m_lURIs.append( uri ); } else { postParsingError( m_oMetaLink.lineNumber(), tr( "<metaurl> tag could not be parsed." ) ); continue; } } else { QString e = tr( "Caught unexpected XML tag \"<%1>\" while parsing <file> in Metalink XML." ); postParsingError( m_oMetaLink.lineNumber(), e.arg( sComp.toString() ) ); continue; } } if ( oCurrentFile.isValid() ) { lFiles.push_back( oCurrentFile ); return true; } else { return false; } }
quint64 BaseStateAbstract::readUInt64(QStringRef val, bool *ok) { return (quint64)val.toString().toULongLong(ok); }
/*! * Read out a widget within a category. This can either be * enclosed in a <ui> element or a (legacy) <widget> element which may * contain nested <widget> elements. * * Examples: * * <ui language="c++"> * <widget class="MultiPageWidget" name="multipagewidget"> ... </widget> * <customwidgets>...</customwidgets> * <ui> * * or * * <widget> * <widget> ... </widget> * ... * <widget> * * Returns true on success, false if end was reached or an error has been encountered * in which case the reader has its error flag set. If successful, the current item * of the reader will be the closing element (</ui> or </widget>) */ bool WidgetBoxTreeWidget::readWidget(Widget *w, const QString &xml, QXmlStreamReader &r) { qint64 startTagPosition =0, endTagPosition = 0; int nesting = 0; bool endEncountered = false; bool parsedWidgetTag = false; QString outmostElement; while (!endEncountered) { const qint64 currentPosition = r.characterOffset(); switch(r.readNext()) { case QXmlStreamReader::StartElement: if (nesting++ == 0) { // First element must be <ui> or (legacy) <widget> const QStringRef name = r.name(); if (name == QLatin1String(uiElementC)) { startTagPosition = currentPosition; } else { if (name == QLatin1String(widgetElementC)) { startTagPosition = currentPosition; parsedWidgetTag = true; } else { r.raiseError(QDesignerWidgetBox::tr("Unexpected element <%1> encountered when parsing for <widget> or <ui>").arg(name.toString())); return false; } } } else { // We are within <ui> looking for the first <widget> tag if (!parsedWidgetTag && r.name() == QLatin1String(widgetElementC)) { parsedWidgetTag = true; } } break; case QXmlStreamReader::EndElement: // Reached end of widget? if (--nesting == 0) { endTagPosition = r.characterOffset(); endEncountered = true; } break; case QXmlStreamReader::EndDocument: r.raiseError(QDesignerWidgetBox::tr("Unexpected end of file encountered when parsing widgets.")); return false; case QXmlStreamReader::Invalid: return false; default: break; } } if (!parsedWidgetTag) { r.raiseError(QDesignerWidgetBox::tr("A widget element could not be found.")); return false; } // Oddity: Startposition is 1 off QString widgetXml = xml.mid(startTagPosition, endTagPosition - startTagPosition); const QChar lessThan = QLatin1Char('<'); if (!widgetXml.startsWith(lessThan)) widgetXml.prepend(lessThan); w->setDomXml(widgetXml); return true; }
void Utilisateur::loadParam(){ QFile input("../parametres.xml"); if(input.open(QIODevice::ReadOnly)){ QXmlStreamReader xml(&input); while(!xml.atEnd() && !xml.hasError()){ if(xml.isStartElement() && xml.name()=="Type"){ QXmlStreamAttributes attr = xml.attributes(); QStringRef entier = attr.value("Entier"); QStringRef reel = attr.value("Reel"); QStringRef rationnel = attr.value("Rationnel"); QStringRef complexe = attr.value("Complexe"); QStringRef degre = attr.value("Degre"); if(entier=="True") _entier=true; else _entier=false; if(reel=="True") _reel=true; else _reel=false; if(rationnel=="True") _rationnel=true; else _rationnel=false; if(complexe=="True") _complexe=true; else _complexe=false; if(degre=="True") _degre=true; else _degre=false; } else if(xml.isStartElement() && xml.name()=="Pile"){ QXmlStreamAttributes attr = xml.attributes(); QStringRef x = attr.value("X"); QStringRef affichage = attr.value("Affichage"); QString xstr = x.toString(); if(xstr.contains(QRegExp("^[0-9]+$"))) _X = xstr.toInt(); else _X=10; if(affichage=="True") _pile=true; else _pile=false; } else if(xml.isStartElement() && xml.name()=="Clavier"){ QXmlStreamAttributes attr = xml.attributes(); QStringRef affichage = attr.value("Affichage"); if(affichage=="True") _clavier=true; else _clavier=false; } //lit l'element suivant xml.readNext(); } } input.close(); }
bool DialogStartup::populateListWidget(QListWidget* lw,QString configPath) { QFile xmlFile(configPath); if (!xmlFile.exists() || (xmlFile.error() != QFile::NoError)) { qDebug() << "ERROR: Unable to open config file " << configPath; return false; } xmlFile.open(QIODevice::ReadOnly); QXmlStreamReader reader(&xmlFile); while (!reader.atEnd()) { reader.readNext(); if (reader.isStartElement()) { if (reader.name() == "demos") while (!reader.atEnd()) { reader.readNext(); if (reader.isStartElement() && reader.name() == "example") { QXmlStreamAttributes attrs = reader.attributes(); QStringRef filename = attrs.value("filename"); if (!filename.isEmpty()) { QStringRef name = attrs.value("name"); QStringRef image = attrs.value("image"); QStringRef args = attrs.value("args"); QStringRef idpocket = attrs.value("idpocket"); QStringRef desc = attrs.value("desc"); QStringRef _connectortype = attrs.value("connectortype"); QStringRef _conngender = attrs.value("conngender"); QListWidgetItem *newItem = new QListWidgetItem; newItem->setText(name.toString()); newItem->setIcon(QIcon(image.toString())); newItem->setData(Qt::UserRole,idpocket.toString()); if (!idpocket.startsWith("#")) lw->addItem( newItem); // filter on connectors type and gender // if (!connType.isEmpty() && (_connectortype.indexOf(connType)==-1)) continue; // qWarning()<<connType<<" found:"<<_connectortype; // if (!connGender.isEmpty() && (_conngender.indexOf(connGender)==-1)) continue; // qWarning()<<"included"; } } else if(reader.isEndElement() && reader.name() == "demos") { return true; } } } } if (reader.hasError()) { qDebug() << QString("Error parsing %1 on line %2 column %3: \n%4") .arg(configPath) .arg(reader.lineNumber()) .arg(reader.columnNumber()) .arg(reader.errorString()); } return true; }
/*! \reimp */ void QXmlFormatter::characters(const QStringRef &value) { Q_D(QXmlFormatter); d->isPreviousAtomic = false; d->characterBuffer += value.toString(); }
bool QGeoCodeXmlParser::parseRootElement() { /* <xsd:element name="places"> <xsd:complexType> <xsd:sequence> <xsd:element minOccurs="0" maxOccurs="unbounded" name="place" type="gc:Place"/> </xsd:sequence> <xsd:attribute name="resultCode" type="gc:ResultCodes"/> <xsd:attribute name="resultDescription" type="xsd:string"/> <xsd:attribute name="resultsTotal" type="xsd:nonNegativeInteger"/> </xsd:complexType> </xsd:element> <xsd:simpleType name="ResultCodes"> <xsd:restriction base="xsd:string"> <xsd:enumeration value="OK"/> <xsd:enumeration value="FAILED"/> </xsd:restriction> </xsd:simpleType> */ if (m_reader->readNextStartElement()) { if (m_reader->name() == "places") { if (m_reader->attributes().hasAttribute("resultCode")) { QStringRef result = m_reader->attributes().value("resultCode"); if (result == "FAILED") { QString resultDesc = m_reader->attributes().value("resultDescription").toString(); if (resultDesc.isEmpty()) resultDesc = "The attribute \"resultCode\" of the element \"places\" indicates that the request failed."; m_reader->raiseError(resultDesc); return false; } else if (result != "OK") { m_reader->raiseError(QString("The attribute \"resultCode\" of the element \"places\" has an unknown value (value was %1).").arg(result.toString())); return false; } } while (m_reader->readNextStartElement()) { if (m_reader->name() == "place") { QGeoLocation location; if (!parsePlace(&location)) return false; if (!m_bounds.isValid() || m_bounds.contains(location.coordinate())) m_results.append(location); } else { m_reader->raiseError(QString("The element \"places\" did not expect a child element named \"%1\".").arg(m_reader->name().toString())); return false; } } } else { m_reader->raiseError(QString("The root element is expected to have the name \"places\" (root element was named \"%1\").").arg(m_reader->name().toString())); return false; } } else { m_reader->raiseError("Expected a root element named \"places\" (no root element found)."); return false; } if (m_reader->readNextStartElement()) { m_reader->raiseError(QString("A single root element named \"places\" was expected (second root element was named \"%1\")").arg(m_reader->name().toString())); return false; } return true; }
void TuneFactory::handleCharacterData(const QStringRef &text) { if(m_depth == 2 && m_state != TuneInvalid) m_data[m_state] = text.toString(); }
void ZLibCompressionFeature::handleCharacterData(const QStringRef &text) { if (m_state == AtMethod) m_methods << text.toString(); }
bool GlslHighlighter::isPPKeyword(const QStringRef &text) const { switch (text.length()) { case 2: if (text.at(0) == QLatin1Char('i') && text.at(1) == QLatin1Char('f')) return true; break; case 4: if (text.at(0) == QLatin1Char('e') && text == QLatin1String("elif")) return true; else if (text.at(0) == QLatin1Char('e') && text == QLatin1String("else")) return true; break; case 5: if (text.at(0) == QLatin1Char('i') && text == QLatin1String("ifdef")) return true; else if (text.at(0) == QLatin1Char('u') && text == QLatin1String("undef")) return true; else if (text.at(0) == QLatin1Char('e') && text == QLatin1String("endif")) return true; else if (text.at(0) == QLatin1Char('e') && text == QLatin1String("error")) return true; break; case 6: if (text.at(0) == QLatin1Char('i') && text == QLatin1String("ifndef")) return true; if (text.at(0) == QLatin1Char('i') && text == QLatin1String("import")) return true; else if (text.at(0) == QLatin1Char('d') && text == QLatin1String("define")) return true; else if (text.at(0) == QLatin1Char('p') && text == QLatin1String("pragma")) return true; break; case 7: if (text.at(0) == QLatin1Char('i') && text == QLatin1String("include")) return true; else if (text.at(0) == QLatin1Char('w') && text == QLatin1String("warning")) return true; break; case 12: if (text.at(0) == QLatin1Char('i') && text == QLatin1String("include_next")) return true; break; default: break; } return false; }
QColor BaseStateAbstract::stringToColor(QStringRef val) { return stringToColor(val.toString()); }
void XmlQueryToWriter::attribute(const QXmlName & name, const QStringRef & value) { _writer->writeAttribute(name.localName(_query->namePool()), value.toString()); }
int BaseStateAbstract::readInt(QStringRef val, bool *ok) { return val.toString().toInt(ok); }
void parseDeclensionDictWordGroup(QXmlStreamReader& xml, WordDeclensionGroup* owningWordGroup) { while (!xml.atEnd()) { xml.readNext(); if (xml.isEndElement() && xml.name() == "group") break; if (xml.isStartElement() && xml.name() == "word") { WordDeclensionForm wordForm; wordForm.OwningWordGroup = owningWordGroup; const QXmlStreamAttributes& attrs = xml.attributes(); if (attrs.hasAttribute("name")) { QStringRef nameStr = attrs.value("name"); QString nameQ = QString::fromRawData(nameStr.constData(), nameStr.size()); wordForm.Name = nameQ.toStdWString(); } if (attrs.hasAttribute("class")) { QStringRef attrStr = attrs.value("class"); wordForm.WordClass = details::parseWordClass(attrStr); } if (attrs.hasAttribute("isInfinitive")) { QStringRef attrStr = attrs.value("isInfinitive"); wordForm.IsInfinitive = details::parseBool(attrStr); } if (attrs.hasAttribute("person")) { QStringRef attrStr = attrs.value("person"); wordForm.Person = details::parseWordPerson(attrStr); } if (attrs.hasAttribute("case")) { QStringRef attrStr = attrs.value("case"); wordForm.Case = details::parseWordCase(attrStr); } if (attrs.hasAttribute("gender")) { QStringRef attrStr = attrs.value("gender"); wordForm.Gender = details::parseWordGender(attrStr); } if (attrs.hasAttribute("tense")) { QStringRef attrStr = attrs.value("tense"); wordForm.Tense = details::parseWordTense(attrStr); } if (attrs.hasAttribute("degree")) { QStringRef attrStr = attrs.value("degree"); wordForm.Degree = details::parseWordDegree(attrStr); } if (attrs.hasAttribute("mandative")) { QStringRef attrStr = attrs.value("mandative"); wordForm.Mandative = details::parseBool(attrStr); } if (attrs.hasAttribute("number")) { QStringRef attrStr = attrs.value("number"); wordForm.NumberCategory = details::parseWordNumber(attrStr); } if (attrs.hasAttribute("active")) { QStringRef attrStr = attrs.value("active"); wordForm.ActiveOrPassive = details::parseWordActiveOrPassive(attrStr); } owningWordGroup->Forms.push_back(wordForm); } } }
XBMCVideoChecker::XBMCVideoChecker(const std::string & address, uint16_t port, bool grabVideo, bool grabPhoto, bool grabAudio, bool grabMenu, bool grabScreensaver, bool enable3DDetection) : QObject(), _address(QString::fromStdString(address)), _port(port), _activePlayerRequest(R"({"id":666,"jsonrpc":"2.0","method":"Player.GetActivePlayers"})"), _currentPlayingItemRequest(R"({"id":667,"jsonrpc":"2.0","method":"Player.GetItem","params":{"playerid":%1,"properties":["file"]}})"), _checkScreensaverRequest(R"({"id":668,"jsonrpc":"2.0","method":"XBMC.GetInfoBooleans","params":{"booleans":["System.ScreenSaverActive"]}})"), _socket(), _grabVideo(grabVideo), _grabPhoto(grabPhoto), _grabAudio(grabAudio), _grabMenu(grabMenu), _grabScreensaver(grabScreensaver), _enable3DDetection(enable3DDetection), _previousScreensaverMode(false), _previousGrabbingMode(GRABBINGMODE_INVALID), _previousVideoMode(VIDEO_2D) { // setup socket connect(&_socket, SIGNAL(readyRead()), this, SLOT(receiveReply())); connect(&_socket, SIGNAL(disconnected()), this, SLOT(disconnected())); connect(&_socket, SIGNAL(connected()), this, SLOT(connected())); connect(&_socket, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(connectionError(QAbstractSocket::SocketError))); } void XBMCVideoChecker::start() { reconnect(); } void XBMCVideoChecker::receiveReply() { // expect that the reply is received as a single message. Probably oke considering the size of the expected reply QString reply(_socket.readAll()); std::cout << "Message from XBMC: " << reply.toStdString() << std::endl; if (reply.contains("\"method\":\"Player.OnPlay\"")) { // send a request for the current player state _socket.write(_activePlayerRequest.toUtf8()); return; } else if (reply.contains("\"method\":\"Player.OnStop\"")) { // the player has stopped setGrabbingMode(_grabMenu ? GRABBINGMODE_MENU : GRABBINGMODE_OFF); setVideoMode(VIDEO_2D); } else if (reply.contains("\"method\":\"GUI.OnScreensaverActivated\"")) { setScreensaverMode(!_grabScreensaver); } else if (reply.contains("\"method\":\"GUI.OnScreensaverDeactivated\"")) { setScreensaverMode(false); } else if (reply.contains("\"id\":666")) { // Result of Player.GetActivePlayers // always start a new video in 2D mode emit videoMode(VIDEO_2D); if (reply.contains("video")) { // video is playing setGrabbingMode(_grabVideo ? GRABBINGMODE_VIDEO : GRABBINGMODE_OFF); // we need to get the filename // first retrieve the playerid QString key = "\"playerid\":"; QRegExp regex(key + "(\\d+)"); int pos = regex.indexIn(reply); if (pos > 0) { // now request info of the playing item QStringRef idText(&reply, pos + key.length(), regex.matchedLength() - key.length()); _socket.write(_currentPlayingItemRequest.arg(idText.toString()).toUtf8()); } } else if (reply.contains("picture")) { // picture viewer is playing setGrabbingMode(_grabPhoto ? GRABBINGMODE_PHOTO : GRABBINGMODE_OFF); } else if (reply.contains("audio")) { // audio is playing setGrabbingMode(_grabAudio ? GRABBINGMODE_AUDIO : GRABBINGMODE_OFF); } else { // Nothing is playing. setGrabbingMode(_grabMenu ? GRABBINGMODE_MENU : GRABBINGMODE_OFF); } } else if (reply.contains("\"id\":667")) { // result of Player.GetItem // TODO: what if the filename contains a '"'. In Json this should have been escaped QRegExp regex("\"file\":\"((?!\").)*\""); int pos = regex.indexIn(reply); if (pos > 0) { QStringRef filename = QStringRef(&reply, pos+8, regex.matchedLength()-9); if (filename.contains("3DSBS", Qt::CaseInsensitive) || filename.contains("HSBS", Qt::CaseInsensitive)) { setVideoMode(VIDEO_3DSBS); } else if (filename.contains("3DTAB", Qt::CaseInsensitive) || filename.contains("HTAB", Qt::CaseInsensitive)) { setVideoMode(VIDEO_3DTAB); } else { setVideoMode(VIDEO_2D); } } } else if (reply.contains("\"id\":668")) { // result of System.ScreenSaverActive bool active = reply.contains("\"System.ScreenSaverActive\":true"); setScreensaverMode(!_grabScreensaver && active); } }
std::tuple<bool, const char*> loadUkrainianWordDeclensionXml(const std::wstring& declensionDictPath, std::unordered_map<std::wstring, std::unique_ptr<WordDeclensionGroup>>& declinedWords) { QFile file(QString::fromStdWString(declensionDictPath)); if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) return std::make_tuple(false, "Can't open file for reading"); QXmlStreamReader xml(&file); QTextStream dumpFileStream(&file); dumpFileStream.setCodec("UTF-8"); while (!xml.atEnd()) { xml.readNext(); if (xml.isStartElement() && xml.name() == "group") { auto newGroup = std::make_unique<WordDeclensionGroup>(); const QXmlStreamAttributes& attrs = xml.attributes(); if (attrs.hasAttribute("name")) { QStringRef nameStr = attrs.value("name"); QString nameQ = QString::fromRawData(nameStr.constData(), nameStr.size()); newGroup->Name = nameQ.toStdWString(); } if (attrs.hasAttribute("class")) { QStringRef attrStr = attrs.value("class"); newGroup->WordClass = details::parseWordClass(attrStr); } if (attrs.hasAttribute("gender")) { QStringRef attrStr = attrs.value("gender"); newGroup->Gender = details::parseWordGender(attrStr); } if (attrs.hasAttribute("number")) { QStringRef attrStr = attrs.value("number"); newGroup->NumberCategory = details::parseWordNumber(attrStr); } if (attrs.hasAttribute("isBeing")) { QStringRef attrStr = attrs.value("isBeing"); newGroup->IsBeing = details::parseBool(attrStr); } if (attrs.hasAttribute("person")) { QStringRef attrStr = attrs.value("person"); newGroup->Person = details::parseWordPerson(attrStr); } if (attrs.hasAttribute("perfective")) { QStringRef attrStr = attrs.value("perfective"); newGroup->PerfectiveAspect = details::parseWordPerfectiveAspect(attrStr); } if (attrs.hasAttribute("transitive")) { QStringRef attrStr = attrs.value("transitive"); newGroup->Transitive = details::parseWordTransitive(attrStr); } details::parseDeclensionDictWordGroup(xml, newGroup.get()); //declinedWords.re auto it = declinedWords.find(newGroup->Name); if (it == std::end(declinedWords)) { // new word declinedWords.insert(std::make_pair(newGroup->Name, std::move(newGroup))); } else { // duplicate word auto& oldGroup = it->second; if (oldGroup->Forms.empty() && !newGroup->Forms.empty()) declinedWords[newGroup->Name] = std::move(newGroup); // update word else { // ignore if old and new groups are empty // ignore if old is not empty and new is empty // ignore if old and new groups are not empty and are the same if (!oldGroup->Forms.empty() && !newGroup->Forms.empty() && oldGroup->Forms.size() != newGroup->Forms.size()) return std::make_tuple(false, "Duplicate word groups with different word forms"); } } } } if (xml.hasError()) { return std::make_tuple(true, "Error in XML stucture"); } return std::make_tuple(true, nullptr); }
void CoordXmlTest::readHumanReadableStream() { namespace literal = XmlStreamLiteral; QFETCH(int, num_coords); MapCoordVector coords(num_coords, proto_coord); buffer.buffer().truncate(0); QBuffer header; { QXmlStreamWriter xml(&header); header.open(QBuffer::ReadWrite); xml.setAutoFormatting(false); xml.writeStartDocument(); xml.writeStartElement("root"); xml.writeCharacters(""); // flush root start element buffer.open(QBuffer::ReadWrite); xml.setDevice(&buffer); xml.writeStartElement("coords"); // Using the more efficient string implementation. writeHumanReadableString_implementation(coords, xml); xml.writeEndElement(); xml.setDevice(NULL); buffer.close(); header.close(); } header.open(QBuffer::ReadOnly); buffer.open(QBuffer::ReadOnly); QXmlStreamReader xml; xml.addData(header.buffer()); xml.readNextStartElement(); QCOMPARE(xml.name().toString(), QString("root")); bool failed = false; QBENCHMARK { // benchmark iteration overhead coords.clear(); xml.addData(buffer.data()); xml.readNextStartElement(); if (xml.name() != "coords") { failed = true; break; } for( xml.readNext(); xml.tokenType() != QXmlStreamReader::EndElement; xml.readNext() ) { if (xml.error()) { qDebug() << xml.errorString(); failed = true; break; } const QXmlStreamReader::TokenType token = xml.tokenType(); if (token == QXmlStreamReader::EndDocument) { failed = true; break; } if (token == QXmlStreamReader::Characters && !xml.isWhitespace()) { QStringRef text = xml.text(); QString data = QString::fromRawData(text.constData(), text.length()); QTextStream stream(&data, QIODevice::ReadOnly); stream.setIntegerBase(10); while (!stream.atEnd()) { qint32 x, y; int flags = 0; char separator; stream >> x >> y >> separator; if (separator != ';') { stream >> flags >> separator; } coords.push_back(MapCoord::fromNative(x, y, flags)); } if (stream.status() == QTextStream::ReadCorruptData) { failed = true; break; } } // otherwise: ignore element }
bool toBool(const QStringRef stringref) { return (stringref == "true" || stringref.string()->toInt() == 1); }
GModelComponent* GModelComponent::readComponent(QXmlStreamReader & xmlReader, HydroCoupleProject* project, QList<QString>& errorMessages) { if(!xmlReader.name().compare("ModelComponent", Qt::CaseInsensitive) && !xmlReader.hasError() && xmlReader.tokenType() == QXmlStreamReader::StartElement ) { QXmlStreamAttributes attributes = xmlReader.attributes(); if(attributes.hasAttribute("ModelComponentFile")) { QStringRef value = attributes.value("ModelComponentFile"); QFileInfo fileInfo(value.toString()); if(fileInfo.isRelative() && project) { fileInfo = project->projectFile().dir().absoluteFilePath(value.toString()); } if(fileInfo.exists()) { GModelComponent* modelComponent = readComponentFile(fileInfo, project, errorMessages); return modelComponent; } else { errorMessages.append("ModelComponentFile specified was not found : "+ fileInfo.absoluteFilePath() +" : Column " + QString::number(xmlReader.columnNumber()) + " Row " + QString::number(xmlReader.lineNumber())); } } else { if(attributes.hasAttribute("ModelComponentLibrary")) { QStringRef value = attributes.value("ModelComponentLibrary"); QFileInfo fileInfo(value.toString()); if(fileInfo.isRelative() && project) { fileInfo = project->projectFile().dir().absoluteFilePath(value.toString()); } if(fileInfo.exists()) { IModelComponentInfo* modelComponentInfo = dynamic_cast<IModelComponentInfo*>(project->m_componentManager->loadComponent(fileInfo)); if(modelComponentInfo) { IModelComponent* component = modelComponentInfo->createComponentInstance(); GModelComponent* gcomponent = new GModelComponent(component, project); if(attributes.hasAttribute("IsTrigger")) { QString trigVal = attributes.value("IsTrigger").toString(); if(!trigVal.compare("True" , Qt::CaseInsensitive)) { gcomponent->setTrigger(true); } } if(attributes.hasAttribute("XPos") && attributes.hasAttribute("YPos")) { QString xposS = attributes.value("XPos").toString(); QString yposS = attributes.value("YPos").toString(); bool ok; double xloc = xposS.toDouble(&ok); double yloc = yposS.toDouble(&ok); if(ok) { gcomponent->setPos(xloc,yloc); } } while (!(xmlReader.isEndElement() && !xmlReader.name().compare("ModelComponent", Qt::CaseInsensitive)) && !xmlReader.hasError()) { if(!xmlReader.name().compare("Arguments", Qt::CaseInsensitive) && !xmlReader.hasError() && xmlReader.tokenType() == QXmlStreamReader::StartElement) { while (!(xmlReader.isEndElement() && !xmlReader.name().compare("Arguments", Qt::CaseInsensitive)) && !xmlReader.hasError()) { if(!xmlReader.name().compare("Argument", Qt::CaseInsensitive) && !xmlReader.hasError() && xmlReader.tokenType() == QXmlStreamReader::StartElement) { readArgument(xmlReader, component); while (!(xmlReader.isEndElement() && !xmlReader.name().compare("Argument", Qt::CaseInsensitive)) && !xmlReader.hasError()) { xmlReader.readNext(); } } xmlReader.readNext(); } component->initialize(); } xmlReader.readNext(); } return gcomponent; } else { errorMessages.append("Unable to load component specified at: "+ fileInfo.absoluteFilePath() +" : Column " + QString::number(xmlReader.columnNumber()) + " Row " + QString::number(xmlReader.lineNumber())); } } else { errorMessages.append("ModelComponentFile specified was not found : "+ fileInfo.absoluteFilePath() +" : Column " + QString::number(xmlReader.columnNumber()) + " Row " + QString::number(xmlReader.lineNumber())); } } } while (!(xmlReader.isEndElement() && !xmlReader.name().compare("ModelComponent", Qt::CaseInsensitive)) && !xmlReader.hasError()) { xmlReader.readNext(); } } return nullptr; }
void VT100Parser::decodeOSC(uchar character) { if (!parameters.size() && character >= 0x30 && character <= 0x3f) { decodeParameters(character); } else { if (decodeOscState == None) { appendParameter(); if (parameters.size() != 1) { tokenFinished(); return; } oscData.clear(); switch (parameters.at(0)) { case 0: decodeOscState = ChangeWindowAndIconName; break; case 1: decodeOscState = ChangeIconTitle; break; case 2: decodeOscState = ChangeWindowTitle; break; case 4: // TODO: set 256-color palette decodeOscState = Other; break; case 105: decodeOscState = ExTermBlock; break; default: qDebug() << parameters; decodeOscState = Other; } oscData.append(QChar(character)); } else if (character == 0x07 || (decodeOscState == Other && character == 0x5c)) { if (decodeOscState == ChangeWindowAndIconName || decodeOscState == ChangeWindowTitle) { //m_screen->setTitle(title); } else if(decodeOscState == ExTermBlock) { int index = oscData.indexOf(QChar(';')); QStringRef type = oscData.leftRef(index); QStringRef data = oscData.midRef(index+1); if(type.compare("HTML") == 0) { int argIndexes[2] = {0,}; int argN = 0; for(int i = 0; i < data.length(); ++i) { if(data.at(i) == QChar(';')) { argIndexes[argN++] = i; } if(argN == 2) break; } QStringRef objectId = oscData.midRef(index + 1, argIndexes[0]); QStringRef numLines = oscData.midRef(index + 1 + argIndexes[0] + 1, argIndexes[1] - argIndexes[0] - 1); QStringRef actualData = oscData.midRef(index + 1 + argIndexes[1] + 1); int lines = numLines.toString().toInt(); for(int i = 0; i < lines-1; ++i) screen.lineFeed(); emit htmlBlock(objectId.toString(), lines, actualData.toString()); } else if(type.compare("JS")) { } } tokenFinished(); } else { oscData.append(QChar(character)); } } }
void SpellChecker::check() { setDisabled(true); QProgressDialog wait_dialog(tr("Checking spelling..."), tr("Cancel"), 0, m_document->document()->characterCount(), this); wait_dialog.setWindowTitle(tr("Please wait")); wait_dialog.setValue(0); wait_dialog.setWindowModality(Qt::WindowModal); forever { // Update wait dialog wait_dialog.setValue(m_cursor.position()); if (wait_dialog.wasCanceled()) { m_document->setTextCursor(m_start_cursor); reject(); } // Check current line QTextBlock block = m_cursor.block(); QStringRef word = m_dictionary->check(block.text(), m_cursor.position() - block.position()); if (word.isNull()) { if (block.next().isValid()) { m_cursor.movePosition(QTextCursor::NextBlock); continue; } else { break; } } // Select misspelled word m_cursor.setPosition(word.position() + block.position()); m_cursor.setPosition(m_cursor.position() + word.length(), QTextCursor::KeepAnchor); m_word = m_cursor.selectedText(); if (!m_ignored.contains(m_word)) { wait_dialog.close(); setEnabled(true); // Show misspelled word in context QTextCursor cursor = m_cursor; cursor.movePosition(QTextCursor::PreviousWord, QTextCursor::MoveAnchor, 10); int end = m_cursor.position() - cursor.position(); int start = end - m_word.length(); cursor.movePosition(QTextCursor::NextWord, QTextCursor::KeepAnchor, 21); QString context = cursor.selectedText(); context.insert(end, "</span>"); context.insert(start, "<span style=\"color: red;\">"); context.replace("\n", "</p><p>"); context.replace("\t", "<span style=\"white-space: pre;\">\t</span>"); context = "<p>" + context + "</p>"; m_context->setHtml(context); // Show suggestions m_suggestion->clear(); m_suggestions->clear(); QStringList words = m_dictionary->suggestions(m_word); if (!words.isEmpty()) { foreach (const QString& word, words) { m_suggestions->addItem(word); } m_suggestions->setCurrentRow(0); }
String::String(const QStringRef& ref) { if (!ref.string()) return; m_impl = StringImpl::create(reinterpret_cast_ptr<const UChar*>(ref.unicode()), ref.length()); }
TextWithEntities BotCommandClickHandler::getExpandedLinkTextWithEntities(ExpandLinksMode mode, int entityOffset, const QStringRef &textPart) const { return simpleTextWithEntity({ EntityInTextHashtag, entityOffset, textPart.size() }); }
ItemInfo *ItemDB::readItem(XmlReader &xml) { const QXmlStreamAttributes attr = xml.attributes(); int id = attr.value("id").toInt(); if (!id) { qDebug() << "Bad or missing item id at line " << xml.lineNumber(); xml.skipCurrentElement(); return 0; } // TODO: Move races to a seperate file and move parsing to racedb if (attr.value("type") == "racesprite") { // Race "item" RaceInfo *raceInfo = new RaceInfo(-id); raceInfo->setName(attr.value("name").toString()); while (xml.readNextStartElement()) { if (xml.name() == "sprite") { const BeingGender gender = genderFromString(xml.attributes().value("gender")); SpriteReference *sprite = SpriteReference::readSprite(xml, raceInfo); raceInfo->setSprite(gender, sprite); } else { xml.skipCurrentElement(); } } RaceDB::instance()->setInfo(-id, raceInfo); return 0; } // TODO: Move hairs to a seperate file and move parsing to hairdb if (attr.value("type") == "hairsprite") { // Hair "item" // invert the negative id for now id = -id; HairInfo *hairInfo = new HairInfo(id, HairDB::instance()); hairInfo->setName(attr.value("name").toString()); while (xml.readNextStartElement()) { if (xml.name() == "sprite") { const BeingGender gender = genderFromString(xml.attributes().value("gender")); SpriteReference *sprite = SpriteReference::readSprite(xml, hairInfo); hairInfo->setSprite(gender, sprite); } else { xml.skipCurrentElement(); } } HairDB::instance()->setInfo(id, hairInfo); return 0; } ItemInfo *item = new ItemInfo(id, this); item->setType(itemTypeFromString(attr.value("type"))); item->setName(attr.value("name").toString()); item->setDescription(attr.value("description").toString()); item->setWeight(attr.value("weight").toInt()); SpriteDisplay display; item->setImage(attr.value("image").toString()); if (item->name().isEmpty()) item->setName("unnamed"); QStringList effects; for (int i = 0; i < int(sizeof(fields) / sizeof(fields[0])); ++i) { int value = attr.value(fields[i].tag).toInt(); if (value) effects.append(fields[i].format.arg(value)); } // foreach (Stat stat, mExtraStats) { // int value = xml.intAttribute(stat.tag); // if (value) // effects.append(stat.format.arg(value)); // } const QStringRef temp = attr.value("effect"); if (!temp.isEmpty()) effects.append(temp.toString()); item->setEffects(effects); while (xml.readNextStartElement()) { if (xml.name() == "sprite") { const BeingGender gender = genderFromString(xml.attributes().value("gender")); SpriteReference *sprite = SpriteReference::readSprite(xml, item); item->addSprite(gender, sprite); } else if (xml.name() == "particlefx") { item->setParticleFx(xml.readElementText()); } else if (xml.name() == "sound") { xml.skipCurrentElement(); // TODO } else if (xml.name() == "floor") { while (xml.readNextStartElement()) { if (xml.name() == "sprite") { display.sprites.append( SpriteReference::readSprite(xml, item)); } else if (xml.name() == "particlefx") { display.particles.append(xml.readElementText()); } else { xml.readUnknownElement(); } } } else { xml.skipCurrentElement(); } } item->setDisplay(display); return item; }
void FluidLauncher::parseDemos(QXmlStreamReader& reader) { while (!reader.atEnd()) { reader.readNext(); if (reader.isStartElement() && reader.name() == "example") { QXmlStreamAttributes attrs = reader.attributes(); QStringRef filename = attrs.value("filename"); if (!filename.isEmpty()) { QStringRef name = attrs.value("name"); QStringRef image = attrs.value("image"); QStringRef args = attrs.value("args"); QStringRef idpocket = attrs.value("idpocket"); QStringRef desc = attrs.value("desc"); Launcher* newDemo = new Launcher( idpocket.toString(), filename.toString(), name.isEmpty() ? "Unnamed Demo" : name.toString(), image.toString(), args.toString().split(" "), desc.toString()); demoList.append(newDemo); } } else if(reader.isEndElement() && reader.name() == "demos") { return; } } }
void IosToolHandlerPrivate::processXml() { while (!outputParser.atEnd()) { QXmlStreamReader::TokenType tt = outputParser.readNext(); //qCDebug(toolHandlerLog) << "processXml, tt=" << tt; switch (tt) { case QXmlStreamReader::NoToken: // The reader has not yet read anything. continue; case QXmlStreamReader::Invalid: // An error has occurred, reported in error() and errorString(). break; case QXmlStreamReader::StartDocument: // The reader reports the XML version number in documentVersion(), and the encoding // as specified in the XML document in documentEncoding(). If the document is declared // standalone, isStandaloneDocument() returns true; otherwise it returns false. break; case QXmlStreamReader::EndDocument: // The reader reports the end of the document. // state = XmlEndProcessed; break; case QXmlStreamReader::StartElement: // The reader reports the start of an element with namespaceUri() and name(). Empty // elements are also reported as StartElement, followed directly by EndElement. // The convenience function readElementText() can be called to concatenate all content // until the corresponding EndElement. Attributes are reported in attributes(), // namespace declarations in namespaceDeclarations(). { QStringRef elName = outputParser.name(); if (elName == QLatin1String("msg")) { stack.append(ParserState(ParserState::Msg)); } else if (elName == QLatin1String("exit")) { stack.append(ParserState(ParserState::Exit)); toolExited(outputParser.attributes().value(QLatin1String("code")) .toString().toInt()); } else if (elName == QLatin1String("device_id")) { stack.append(ParserState(ParserState::DeviceId)); } else if (elName == QLatin1String("key")) { stack.append(ParserState(ParserState::Key)); } else if (elName == QLatin1String("value")) { stack.append(ParserState(ParserState::Value)); } else if (elName == QLatin1String("query_result")) { stack.append(ParserState(ParserState::QueryResult)); } else if (elName == QLatin1String("app_output")) { stack.append(ParserState(ParserState::AppOutput)); } else if (elName == QLatin1String("control_char")) { QXmlStreamAttributes attributes = outputParser.attributes(); QChar c[1] = { QChar::fromLatin1(static_cast<char>(attributes.value(QLatin1String("code")).toString().toInt())) }; if (stack.size() > 0 && stack.last().collectChars()) stack.last().chars.append(c[0]); stack.append(ParserState(ParserState::ControlChar)); break; } else if (elName == QLatin1String("item")) { stack.append(ParserState(ParserState::Item)); } else if (elName == QLatin1String("status")) { ParserState pState(ParserState::Status); QXmlStreamAttributes attributes = outputParser.attributes(); pState.progress = attributes.value(QLatin1String("progress")).toString().toInt(); pState.maxProgress = attributes.value(QLatin1String("max_progress")).toString().toInt(); stack.append(pState); } else if (elName == QLatin1String("app_started")) { stack.append(ParserState(ParserState::AppStarted)); QXmlStreamAttributes attributes = outputParser.attributes(); QStringRef statusStr = attributes.value(QLatin1String("status")); Ios::IosToolHandler::OpStatus status = Ios::IosToolHandler::Unknown; if (statusStr.compare(QLatin1String("success"), Qt::CaseInsensitive) == 0) status = Ios::IosToolHandler::Success; else if (statusStr.compare(QLatin1String("failure"), Qt::CaseInsensitive) == 0) status = Ios::IosToolHandler::Failure; didStartApp(bundlePath, deviceId, status); } else if (elName == QLatin1String("app_transfer")) { stack.append(ParserState(ParserState::AppTransfer)); QXmlStreamAttributes attributes = outputParser.attributes(); QStringRef statusStr = attributes.value(QLatin1String("status")); Ios::IosToolHandler::OpStatus status = Ios::IosToolHandler::Unknown; if (statusStr.compare(QLatin1String("success"), Qt::CaseInsensitive) == 0) status = Ios::IosToolHandler::Success; else if (statusStr.compare(QLatin1String("failure"), Qt::CaseInsensitive) == 0) status = Ios::IosToolHandler::Failure; emit didTransferApp(bundlePath, deviceId, status); } else if (elName == QLatin1String("device_info") || elName == QLatin1String("deviceinfo")) { stack.append(ParserState(ParserState::DeviceInfo)); } else if (elName == QLatin1String("inferior_pid")) { stack.append(ParserState(ParserState::InferiorPid)); } else if (elName == QLatin1String("server_ports")) { stack.append(ParserState(ParserState::ServerPorts)); QXmlStreamAttributes attributes = outputParser.attributes(); int gdbServerPort = attributes.value(QLatin1String("gdb_server")).toString().toInt(); int qmlServerPort = attributes.value(QLatin1String("qml_server")).toString().toInt(); gotServerPorts(bundlePath, deviceId, gdbServerPort, qmlServerPort); } else { qCWarning(toolHandlerLog) << "unexpected element " << elName; } break; } case QXmlStreamReader::EndElement: // The reader reports the end of an element with namespaceUri() and name(). { ParserState p = stack.last(); stack.removeLast(); switch (p.kind) { case ParserState::Msg: errorMsg(p.chars); break; case ParserState::DeviceId: if (deviceId.isEmpty()) deviceId = p.chars; else QTC_CHECK(deviceId.compare(p.chars, Qt::CaseInsensitive) == 0); break; case ParserState::Key: stack.last().key = p.chars; break; case ParserState::Value: stack.last().value = p.chars; break; case ParserState::Status: isTransferringApp(bundlePath, deviceId, p.progress, p.maxProgress, p.chars); break; case ParserState::QueryResult: state = XmlEndProcessed; stop(0); return; case ParserState::AppOutput: appOutput(p.chars); break; case ParserState::ControlChar: break; case ParserState::AppStarted: break; case ParserState::AppTransfer: break; case ParserState::Item: stack.last().info.insert(p.key, p.value); break; case ParserState::DeviceInfo: deviceInfo(deviceId, p.info); break; case ParserState::Exit: break; case ParserState::InferiorPid: gotInferiorPid(bundlePath, deviceId, Q_PID(p.chars.toInt())); break; case ParserState::ServerPorts: break; } break; } case QXmlStreamReader::Characters: // The reader reports characters in text(). If the characters are all white-space, // isWhitespace() returns true. If the characters stem from a CDATA section, // isCDATA() returns true. if (stack.isEmpty()) break; if (stack.last().collectChars()) stack.last().chars.append(outputParser.text()); break; case QXmlStreamReader::Comment: // The reader reports a comment in text(). break; case QXmlStreamReader::DTD: // The reader reports a DTD in text(), notation declarations in notationDeclarations(), // and entity declarations in entityDeclarations(). Details of the DTD declaration are // reported in in dtdName(), dtdPublicId(), and dtdSystemId(). break; case QXmlStreamReader::EntityReference: // The reader reports an entity reference that could not be resolved. The name of // the reference is reported in name(), the replacement text in text(). break; case QXmlStreamReader::ProcessingInstruction: break; } } if (outputParser.hasError() && outputParser.error() != QXmlStreamReader::PrematureEndOfDocumentError) { qCWarning(toolHandlerLog) << "error parsing iosTool output:" << outputParser.errorString(); stop(-1); } }