// Index any resources void NoteIndexer::indexRecognition(qint32 reslid, Resource &r) { QLOG_TRACE_IN(); if (!r.noteGuid.isSet() || !r.guid.isSet()) return; if (reslid <= 0) return; NSqlQuery sql(db); // Make sure we have something to look through. Data recognition; if (r.recognition.isSet()) recognition = r.recognition; if (!recognition.body.isSet()) return; QDomDocument doc; QString emsg; doc.setContent(recognition.body, &emsg); // look for text tags QDomNodeList anchors = doc.documentElement().elementsByTagName("t"); QLOG_TRACE() << "Beginning insertion of recognition:"; QLOG_TRACE() << "Anchors found: " << anchors.length(); sql.exec("begin;"); #if QT_VERSION < 0x050000 for (unsigned int i=0; i<anchors.length(); i++) { #else for (int i=0; i<anchors.length(); i++) { #endif QLOG_TRACE() << "Anchor: " << i; QApplication::processEvents(); QDomElement enmedia = anchors.at(i).toElement(); QString weight = enmedia.attribute("w"); QString text = enmedia.text(); if (text != "") { // Add the new content. it is basically a text version of the note with a weight of 100. sql.prepare("Insert into SearchIndex (lid, weight, source, content) values (:lid, :weight, :source, :content)"); sql.bindValue(":lid", reslid); sql.bindValue(":weight", weight); sql.bindValue(":source", "recognition"); text = global.normalizeTermForSearchAndIndex(text); sql.bindValue(":content", text); sql.exec(); } } QLOG_TRACE() << "Committing"; sql.exec("commit"); QLOG_TRACE_OUT(); } // Index any PDFs that are attached. Basically it turns the PDF into text and adds it the same // way as a note's body void NoteIndexer::indexPdf(qint32 reslid) { QLOG_TRACE_IN(); if (!global.indexPDFLocally) return; NSqlQuery sql(db); if (reslid <= 0) return; QString file = global.fileManager.getDbaDirPath() + QString::number(reslid) +".pdf"; QString text = ""; Poppler::Document *doc = Poppler::Document::load(file); if (doc == nullptr || doc->isEncrypted() || doc->isLocked()) return; for (int i=0; i<doc->numPages(); i++) { QRectF rect; text = text + doc->page(i)->text(rect) + QString(" "); } QLOG_TRACE() << "Adding PDF"; // Add the new content. it is basically a text version of the note with a weight of 100. sql.prepare("Insert into SearchIndex (lid, weight, source, content) values (:lid, :weight, :source, :content)"); sql.bindValue(":lid", reslid); sql.bindValue(":weight", 100); sql.bindValue(":source", "recognition"); text = global.normalizeTermForSearchAndIndex(text); sql.bindValue(":content", text); sql.exec(); QLOG_TRACE_OUT(); }
void for_each_node(const QDomNodeList & list, F f) { for (int i = 0; i < list.size(); ++i) { f(list.at(i)); } }
bool QgsComposerLegend::readXML( const QDomElement& itemElem, const QDomDocument& doc ) { if ( itemElem.isNull() ) { return false; } //read general properties mTitle = itemElem.attribute( "title" ); //title font QString titleFontString = itemElem.attribute( "titleFont" ); if ( !titleFontString.isEmpty() ) { mTitleFont.fromString( titleFontString ); } //group font QString groupFontString = itemElem.attribute( "groupFont" ); if ( !groupFontString.isEmpty() ) { mGroupFont.fromString( groupFontString ); } //layer font QString layerFontString = itemElem.attribute( "layerFont" ); if ( !layerFontString.isEmpty() ) { mLayerFont.fromString( layerFontString ); } //item font QString itemFontString = itemElem.attribute( "itemFont" ); if ( !itemFontString.isEmpty() ) { mItemFont.fromString( itemFontString ); } //spaces mBoxSpace = itemElem.attribute( "boxSpace", "2.0" ).toDouble(); mLayerSpace = itemElem.attribute( "layerSpace", "3.0" ).toDouble(); mSymbolSpace = itemElem.attribute( "symbolSpace", "2.0" ).toDouble(); mIconLabelSpace = itemElem.attribute( "iconLabelSpace", "2.0" ).toDouble(); mSymbolWidth = itemElem.attribute( "symbolWidth", "7.0" ).toDouble(); mSymbolHeight = itemElem.attribute( "symbolHeight", "14.0" ).toDouble(); //composer map if ( !itemElem.attribute( "map" ).isEmpty() ) { mComposerMap = mComposition->getComposerMapById( itemElem.attribute( "map" ).toInt() ); } //read model properties QDomNodeList modelNodeList = itemElem.elementsByTagName( "Model" ); if ( modelNodeList.size() > 0 ) { QDomElement modelElem = modelNodeList.at( 0 ).toElement(); mLegendModel.readXML( modelElem, doc ); } //restore general composer item properties QDomNodeList composerItemList = itemElem.elementsByTagName( "ComposerItem" ); if ( composerItemList.size() > 0 ) { QDomElement composerItemElem = composerItemList.at( 0 ).toElement(); _readXML( composerItemElem, doc ); } emit itemChanged(); return true; }
int QgsSLDConfigParser::layersAndStyles( QStringList& layers, QStringList& styles ) const { QgsDebugMsg( "Entering." ); layers.clear(); styles.clear(); if ( mXMLDoc ) { QDomElement sldElem = mXMLDoc->documentElement(); if ( !sldElem.isNull() ) { //go through all the children and search for <NamedLayers> and <UserLayers> QDomNodeList layerNodes = sldElem.childNodes(); for ( int i = 0; i < layerNodes.size(); ++i ) { QDomElement currentLayerElement = layerNodes.item( i ).toElement(); if ( currentLayerElement.localName() == QLatin1String( "NamedLayer" ) ) { QgsDebugMsg( "Found a NamedLayer" ); //layer name QDomNodeList nameList = currentLayerElement.elementsByTagName/*NS*/( /*mSLDNamespace,*/ QStringLiteral( "Name" ) ); if ( nameList.length() < 1 ) { continue; //a layer name is mandatory } QString layerName = nameList.item( 0 ).toElement().text(); //find the Named Styles and the corresponding names QDomNodeList namedStyleList = currentLayerElement.elementsByTagName/*NS*/( /*mSLDNamespace,*/ QStringLiteral( "NamedStyle" ) ); for ( int j = 0; j < namedStyleList.size(); ++j ) { QDomNodeList styleNameList = namedStyleList.item( j ).toElement().elementsByTagName/*NS*/( /*mSLDNamespace,*/ QStringLiteral( "Name" ) ); if ( styleNameList.size() < 1 ) { continue; //a layer name is mandatory } QString styleName = styleNameList.item( 0 ).toElement().text(); QgsDebugMsg( "styleName is: " + styleName ); layers.push_back( layerName ); styles.push_back( styleName ); } //named layers can also have User Styles QDomNodeList userStyleList = currentLayerElement.elementsByTagName/*NS*/( /*mSLDNamespace,*/ QStringLiteral( "UserStyle" ) ); for ( int j = 0; j < userStyleList.size(); ++j ) { QDomNodeList styleNameList = userStyleList.item( j ).toElement().elementsByTagName/*NS*/( /*mSLDNamespace,*/ QStringLiteral( "Name" ) ); if ( styleNameList.size() < 1 ) { continue; //a layer name is mandatory } QString styleName = styleNameList.item( 0 ).toElement().text(); QgsDebugMsg( "styleName is: " + styleName ); layers.push_back( layerName ); styles.push_back( styleName ); } } else if ( currentLayerElement.localName() == QLatin1String( "UserLayer" ) ) { QgsDebugMsg( "Found a UserLayer" ); //layer name QDomNodeList nameList = currentLayerElement.elementsByTagName/*NS*/( /*mSLDNamespace,*/ QStringLiteral( "Name" ) ); if ( nameList.length() < 1 ) { QgsDebugMsg( "Namelist size is <1" ); continue; //a layer name is mandatory } QString layerName = nameList.item( 0 ).toElement().text(); QgsDebugMsg( "layerName is: " + layerName ); //find the User Styles and the corresponding names QDomNodeList userStyleList = currentLayerElement.elementsByTagName/*NS*/( /*mSLDNamespace,*/ QStringLiteral( "UserStyle" ) ); for ( int j = 0; j < userStyleList.size(); ++j ) { QDomNodeList styleNameList = userStyleList.item( j ).toElement().elementsByTagName/*NS*/( /*mSLDNamespace,*/ QStringLiteral( "Name" ) ); if ( styleNameList.size() < 1 ) { QgsDebugMsg( "Namelist size is <1" ); continue; } QString styleName = styleNameList.item( 0 ).toElement().text(); QgsDebugMsg( "styleName is: " + styleName ); layers.push_back( layerName ); styles.push_back( styleName ); } } } } } else { return 1; } return 0; }
void QgsSLDConfigParser::layersAndStylesCapabilities( QDomElement& parentElement, QDomDocument& doc, const QString& version, bool fullProjectSettings ) const { Q_UNUSED( version ); Q_UNUSED( fullProjectSettings ); //iterate over all <UserLayer> nodes if ( mXMLDoc ) { QDomNode sldNode = mXMLDoc->documentElement(); if ( !sldNode.isNull() ) { //create wgs84 to reproject the layer bounding boxes //QgsCoordinateReferenceSystem wgs84; //wgs84.createFromEpsg(4326); QDomNodeList layerNodeList = sldNode.toElement().elementsByTagName( QStringLiteral( "UserLayer" ) ); for ( int i = 0; i < layerNodeList.size(); ++i ) { QDomElement layerElement = doc.createElement( QStringLiteral( "Layer" ) ); layerElement.setAttribute( QStringLiteral( "queryable" ), QStringLiteral( "1" ) ); //support GetFeatureInfo for all layers parentElement.appendChild( layerElement ); //add name QDomNodeList nameList = layerNodeList.item( i ).toElement().elementsByTagName( QStringLiteral( "Name" ) ); if ( !nameList.isEmpty() ) { //layer name QDomElement layerNameElement = doc.createElement( QStringLiteral( "Name" ) ); QDomText layerNameText = doc.createTextNode( nameList.item( 0 ).toElement().text() ); layerNameElement.appendChild( layerNameText ); layerElement.appendChild( layerNameElement ); } //add title QDomNodeList titleList = layerNodeList.item( i ).toElement().elementsByTagName( QStringLiteral( "Title" ) ); if ( !titleList.isEmpty() ) { QDomElement layerTitleElement = doc.createElement( QStringLiteral( "Title" ) ); QDomText layerTitleText = doc.createTextNode( titleList.item( 0 ).toElement().text() ); layerTitleElement.appendChild( layerTitleText ); layerElement.appendChild( layerTitleElement ); } //add abstract QDomNodeList abstractList = layerNodeList.item( i ).toElement().elementsByTagName( QStringLiteral( "Abstract" ) ); if ( !abstractList.isEmpty() ) { QDomElement layerAbstractElement = doc.createElement( QStringLiteral( "Abstract" ) ); QDomText layerAbstractText = doc.createTextNode( abstractList.item( 0 ).toElement().text() ); layerAbstractElement.appendChild( layerAbstractText ); layerElement.appendChild( layerAbstractElement ); } //get QgsMapLayer object to add Ex_GeographicalBoundingBox, Bounding Box QList<QgsMapLayer*> layerList = mapLayerFromStyle( nameList.item( 0 ).toElement().text(), QLatin1String( "" ) ); if ( layerList.size() < 1 )//error while generating the layer { QgsDebugMsg( "Error, no maplayer in layer list" ); continue; } //get only the first layer since we don't want to have the other ones in the capabilities document QgsMapLayer* theMapLayer = layerList.at( 0 ); if ( !theMapLayer )//error while generating the layer { QgsDebugMsg( "Error, QgsMapLayer object is 0" ); continue; } //append geographic bbox and the CRS elements QStringList crsNumbers = QgsConfigParserUtils::createCrsListForLayer( theMapLayer ); QStringList crsRestriction; //no crs restrictions in SLD parser QgsConfigParserUtils::appendCrsElementsToLayer( layerElement, doc, crsNumbers, crsRestriction ); QgsConfigParserUtils::appendLayerBoundingBoxes( layerElement, doc, theMapLayer->extent(), theMapLayer->crs(), crsNumbers, crsRestriction ); //iterate over all <UserStyle> nodes within a user layer QDomNodeList userStyleList = layerNodeList.item( i ).toElement().elementsByTagName( QStringLiteral( "UserStyle" ) ); for ( int j = 0; j < userStyleList.size(); ++j ) { QDomElement styleElement = doc.createElement( QStringLiteral( "Style" ) ); layerElement.appendChild( styleElement ); //Name QDomNodeList nameList = userStyleList.item( j ).toElement().elementsByTagName( QStringLiteral( "Name" ) ); if ( !nameList.isEmpty() ) { QDomElement styleNameElement = doc.createElement( QStringLiteral( "Name" ) ); QDomText styleNameText = doc.createTextNode( nameList.item( 0 ).toElement().text() ); styleNameElement.appendChild( styleNameText ); styleElement.appendChild( styleNameElement ); QDomElement styleTitleElement = doc.createElement( QStringLiteral( "Title" ) ); QDomText styleTitleText = doc.createTextNode( nameList.item( 0 ).toElement().text() ); styleTitleElement.appendChild( styleTitleText ); styleElement.appendChild( styleTitleElement ); } //Title QDomNodeList titleList = userStyleList.item( j ).toElement().elementsByTagName( QStringLiteral( "Title" ) ); if ( !titleList.isEmpty() ) { QDomElement styleTitleElement = doc.createElement( QStringLiteral( "Title" ) ); QDomText styleTitleText = doc.createTextNode( titleList.item( 0 ).toElement().text() ); styleTitleElement.appendChild( styleTitleText ); styleElement.appendChild( styleTitleElement ); } //Abstract QDomNodeList abstractList = userStyleList.item( j ).toElement().elementsByTagName( QStringLiteral( "Abstract" ) ); if ( !abstractList.isEmpty() ) { QDomElement styleAbstractElement = doc.createElement( QStringLiteral( "Abstract" ) ); QDomText styleAbstractText = doc.createTextNode( abstractList.item( 0 ).toElement().text() ); styleAbstractElement.appendChild( styleAbstractText ); styleElement.appendChild( styleAbstractElement ); } } } } } }
bool LH_MonitoringSource_Aida64::doUpdate() { #ifdef Q_OS_WIN bool resultVal = true; const char* mapnameAida64 = "AIDA64_SensorValues"; const char* mapnameEverest = "EVEREST_SensorValues"; // Create file mapping HANDLE filemap = (HANDLE)OpenFileMappingA(FILE_MAP_READ,0,mapnameAida64); if(filemap == NULL) filemap = (HANDLE)OpenFileMappingA(FILE_MAP_READ,0,mapnameEverest); setDataAvailable(filemap != NULL); if(dataAvailable()) { char* aidaData = (char*)MapViewOfFile(filemap, FILE_MAP_READ, 0, 0, 0); if (aidaData) { aidaXml_.setContent(QString("<data>%1</data>").arg(QString(aidaData))); QRegExp rx = QRegExp("([^0-9]*)([0-9]+#?\\s?)(.*)"); rx.setPatternSyntax(QRegExp::RegExp2); QDomNode n = aidaXml_.documentElement().firstChild(); while(!n.isNull()) { QDomElement e = n.toElement(); // try to convert the node to an element. if(!e.isNull()) { QDomNodeList labelNodes = e.elementsByTagName("label"); QDomNodeList valueNodes = e.elementsByTagName("value"); if(labelNodes.count()==1 && valueNodes.count()==1) { QString typeName = e.tagName(); QString itemName = labelNodes.at(0).toElement().text(); QString groupName = (rx.indexIn(reverse(itemName))==-1 ? itemName : reverse(rx.cap(3)) + reverse(rx.cap(1)) ); QString valueString = valueNodes.at(0).toElement().text(); QString units=""; if(typeName=="sys") { typeName = "System"; if (itemName.endsWith("FSB")) units="mhz"; if (itemName.endsWith("Clock")) units="mhz"; if (itemName.endsWith("Utilization")) units="%"; if (itemName.endsWith("Memory")) units="MB"; } if(typeName=="temp") { typeName = "Temperatures"; units=QLatin1Literal("\260C"); } if(typeName=="fan") { typeName = "Cooling Fans"; units="rpm"; } if(typeName=="duty") { typeName = "Fan Speeds"; } if(typeName=="volt") { typeName = "Voltage Values"; units="V"; } bool ok; double valueDouble = valueString.toDouble(&ok); if(ok) updateValue(typeName,groupName,itemName, valueDouble, SensorDefinition(units)); else updateValue(typeName,groupName,itemName, valueString, SensorDefinition(units)); } } n = n.nextSibling(); } UnmapViewOfFile(aidaData); } else resultVal = false; CloseHandle(filemap); } else resultVal = false; return resultVal; #else return false; #endif }
bool ConfigManager::InitReportConfig() { XmlHelper *xmlhelper = XmlHelper::GetInstance(); QString node_str; node_str = "report_config"; QDomElement root = xmlhelper->GetXmlNodeParent(node_str); QDomNodeList nodelist = root.childNodes(); for(int i = 0;i < nodelist.count();++i) { QDomNode child = nodelist.at(i); if (child.nodeName() == "export_path") { app_settings_.set_export_path(child.toElement().text()); continue; } if (child.nodeName() == "summary_day") { app_settings_.set_summary_day(child.toElement().text().toInt()); continue; } if (child.nodeName() == "summary_reference_magnitude") { app_settings_.set_summary_reference_magnitude(child.toElement().text().toFloat()); continue; } if (child.nodeName() == "reference_date_order") { app_settings_.set_reference_date_order(child.toElement().text().toInt() != 0); continue; } if (child.nodeName() == "reference_date_include") { app_settings_.set_reference_date_include(child.toElement().text().toInt() != 0); continue; } if (child.nodeName() == "seis_event_column") { app_settings_.set_seis_event_column(child.toElement().text().toInt()); continue; } if (child.nodeName() == "trigger_start") { app_settings_.set_trigger_start(child.toElement().text().toInt()); continue; } if (child.nodeName() == "trigger_end") { app_settings_.set_trigger_end(child.toElement().text().toInt()); continue; } if (child.nodeName() == "stat_trigger_filter") { app_settings_.set_stat_trigger_filter(child.toElement().text().toInt()); continue; } // if (child.nodeName() == "stat_magnitude_filter") // { // app_settings_.set_stat_magnitude_filter(child.toElement().text().toFloat()); // continue; // } if (child.nodeName() == "stat_reference_magnitude") { app_settings_.set_stat_reference_magnitude(child.toElement().text().toFloat()); continue; } if (child.nodeName() == "enable_large_event_config") { app_settings_.set_enable_large_event_config(child.toElement().text().toInt() != 0); continue; } if (child.nodeName() == "large_event_reference_magnitude") { app_settings_.set_large_event_reference_magnitude(child.toElement().text().toFloat()); continue; } // if (child.nodeName() == "large_event_show_num") // { // app_settings_.set_large_event_show_num(child.toElement().text().toInt()); // continue; // } if (child.nodeName() == "fit_magnitude") { app_settings_.set_fit_magnitude(child.toElement().text().toFloat()); continue; } if (child.nodeName() == "summary_compare_last_level") { InitSummaryCompareLastLevelParams(child.toElement().text()); continue; } if (child.nodeName() == "start_selected_magnitude") { app_settings_.set_start_selected_magnitude(child.toElement().text().toFloat()); continue; } if (child.nodeName() == "cover_company_name") { app_settings_.set_cover_company_name(child.toElement().text()); continue; } if (child.nodeName() == "cover_email") { app_settings_.set_cover_email(child.toElement().text()); continue; } if(child.nodeName() == "adc_station_status_enable") { app_settings_.set_adc_station_status_enable(child.toElement().text().toInt() != 0); continue; } if (child.nodeName() == "graphic_3d_enable") { app_settings_.set_graphic_3d_enable(child.toElement().text().toInt() != 0); continue; } } InitReportPictureAndTableNumber(); return true; }
bool QgsPropertyValue::readXML( QDomNode & keyNode ) { // this *should* be a Dom element node QDomElement subkeyElement = keyNode.toElement(); // get the type so that we can properly parse the key value QString typeString = subkeyElement.attribute( "type" ); if ( QString::null == typeString ) { QgsDebugMsg( QString( "null ``type'' attribute for %1" ).arg( keyNode.nodeName() ) ); return false; } // the values come in as strings; we need to restore them to their // original values *and* types value_.clear(); // get the type associated with the value first QVariant::Type type = QVariant::nameToType( typeString.toLocal8Bit().constData() ); // This huge switch is left-over from an earlier incarnation of // QgsProject where there was a fine level of granularity for value // types. The current interface, borrowed from QSettings, supports a // very small sub-set of these types. However, I've left all the // other types just in case the interface is expanded to include these // other types. switch ( type ) { case QVariant::Invalid: QgsDebugMsg( QString( "invalid value type %1 .. " ).arg( typeString ) ); return false; case QVariant::Map: QgsDebugMsg( "no support for QVariant::Map" ); return false; case QVariant::List: QgsDebugMsg( "no support for QVariant::List" ); return false; case QVariant::String: value_ = subkeyElement.text(); // no translating necessary break; case QVariant::StringList: { int i = 0; QDomNodeList values = keyNode.childNodes(); // all the QStringList values will be inside <value> elements QStringList valueStringList; while ( i < values.count() ) { if ( "value" == values.item( i ).nodeName() ) { // <value>s have only one element, which contains actual string value valueStringList.append( values.item( i ).firstChild().nodeValue() ); } else { QgsDebugMsg( QString( "non <value> element ``%1'' in string list" ).arg( values.item( i ).nodeName() ) ); } ++i; } value_ = valueStringList; break; } case QVariant::Font: QgsDebugMsg( "no support for QVariant::Font" ); return false; case QVariant::Pixmap: QgsDebugMsg( "no support for QVariant::Pixmap" ); return false; case QVariant::Brush: QgsDebugMsg( "no support for QVariant::Brush" ); return false; case QVariant::Rect: QgsDebugMsg( "no support for QVariant::Rect" ); return false; case QVariant::Size: QgsDebugMsg( "no support for QVariant::Size" ); return false; case QVariant::Color: QgsDebugMsg( "no support for QVariant::Color" ); return false; case QVariant::Palette: QgsDebugMsg( "no support for QVariant::Palette" ); return false; case QVariant::Point: QgsDebugMsg( "no support for QVariant::Point" ); return false; case QVariant::Image: QgsDebugMsg( "no support for QVariant::Image" ); return false; case QVariant::Int: value_ = QVariant( subkeyElement.text() ).toInt(); break; case QVariant::UInt: value_ = QVariant( subkeyElement.text() ).toUInt(); break; case QVariant::Bool: value_ = QVariant( subkeyElement.text() ).toBool(); break; case QVariant::Double: value_ = QVariant( subkeyElement.text() ).toDouble(); break; case QVariant::ByteArray: value_ = QVariant( subkeyElement.text() ).toByteArray(); break; case QVariant::Polygon: QgsDebugMsg( "no support for QVariant::Polygon" ); return false; case QVariant::Region: QgsDebugMsg( "no support for QVariant::Region" ); return false; case QVariant::Bitmap: QgsDebugMsg( "no support for QVariant::Bitmap" ); return false; case QVariant::Cursor: QgsDebugMsg( "no support for QVariant::Cursor" ); return false; case QVariant::BitArray : QgsDebugMsg( "no support for QVariant::BitArray" ); return false; case QVariant::KeySequence : QgsDebugMsg( "no support for QVariant::KeySequence" ); return false; case QVariant::Pen : QgsDebugMsg( "no support for QVariant::Pen" ); return false; // // QGIS DIES NOT SUPPORT THESE VARIANT TYPES IN VERSION 3.1 DISABLING FOR NOW // /* case QVariant::LongLong : value_ = QVariant(subkeyElement.text()).toLongLong(); break; case QVariant::ULongLong : value_ = QVariant(subkeyElement.text()).toULongLong(); break; */ default : QgsDebugMsg( QString( "unsupported value type %1 .. not propertly translated to QVariant" ).arg( typeString ) ); } return true; } // QgsPropertyValue::readXML
void PacificaServices::downloadFinished(QNetworkReply *reply) { const char *prefix = ""; QDomElement root; QDomNode services; QDomNode n; QDomElement e; int i; int res; QUrl url; QVariant possible_redirect = reply->attribute(QNetworkRequest::RedirectionTargetAttribute); url = possible_redirect.toUrl(); if(!url.isEmpty() && current_url != url && redirect_count < 5) { redirect_count++; current_url = url; std::cout << "Redirecting to " << url.toString().toStdString() << "\n"; QNetworkRequest request(current_url); QNetworkReply *reply = manager.get(request); return; } //FIXME handle error. _services = new QHash<QString, QString>(); //FIXME rename root element once server is updated. QDomDocument doc("myemsl"); std::cout << doc.setContent(reply) << "\n"; root = doc.documentElement(); QDomNodeList list = root.elementsByTagName("prefix"); for(i = 0; i < list.count(); i++) { e = list.at(i).toElement(); prefix = strdup(e.text().toStdString().c_str()); } QSettings settings; if(settings.contains("url/prefix")) { prefix = strdup(settings.value("url/prefix").toString().toStdString().c_str()); } list = root.elementsByTagName("services"); for(i = 0; i < list.count(); i++) { services = list.at(i); } list = services.childNodes(); for(i = 0; i < list.count(); i++) { e = list.at(i).toElement(); if(e.nodeName() == "service") { if(e.attribute("location", "").toStdString().c_str()[0] == '/') { _services->insert(e.attribute("name", NULL), prefix + e.attribute("location", "")); } else { _services->insert(e.attribute("name", NULL), e.attribute("location", "")); } } } ready(_services); }
void UpgradeCheck::httpRequestFinished(int requestId, bool error) { bd_.upgradeCallbacks++; if (http == 0 || error) { bd_.upgradeErrors++; return; } // This is not an error state; it's just the internal state of Qt's network // stack flailing around. if (requestId != httpRequestId) { return; } QString oresponse(http->readAll()); QDomDocument document; int line = -1; QString error_text; // This shouldn't ever be seen by a user. if (!document.setContent(oresponse, &error_text, &line)) { QMessageBox::critical(0, tr("Error"), tr("Invalid return data at line %1: %2.") .arg(line) .arg( error_text)); bd_.upgradeErrors++; return; } QString response; QString upgradeText; if (testing) currentVersion = "1.3.1"; // for testing bool allowBeta = true; // TODO: come from prefs or current version... QDomNodeList upgrades = document.elementsByTagName("update"); QUrl downloadUrl; updateStatus_ = updateCurrent; // Current until proven guilty. for (unsigned int i = 0; i < upgrades.length(); i++) { QDomNode upgradeNode = upgrades.item(i); QDomElement upgrade = upgradeNode.toElement(); QString updateVersion = upgrade.attribute("version"); if (upgrade.attribute("downloadURL").isEmpty()) { downloadUrl = "http://www.gpsbabel.org/download.html"; } else { downloadUrl = upgrade.attribute("downloadURL"); } bool updateIsBeta = upgrade.attribute("type") == "beta"; bool updateIsMajor = upgrade.attribute("type") == "major"; bool updateIsMinor = upgrade.attribute("type") == "minor"; bool updateCandidate = updateIsMajor || updateIsMinor || (updateIsBeta && allowBeta); upgradeText = upgrade.firstChildElement("overview").text(); // String compare, not a numeric one. Server will return "best first". if((updateVersion > currentVersion) && updateCandidate) { bd_.upgradeOffers++; updateStatus_ = updateNeeded; response = tr("A new version of GPSBabel is available.<br />" "Your version is %1 <br />" "The latest version is %2") .arg(currentVersion) .arg(updateVersion); break; } } if (response.length()) { QMessageBox information; information.setWindowTitle(tr("Upgrade")); information.setStandardButtons(QMessageBox::Yes | QMessageBox::No); information.setDefaultButton(QMessageBox::Yes); information.setText(response); information.setInformativeText(tr("Do you wish to download an upgrade?")); information.setDetailedText(upgradeText); switch (information.exec()) { case QMessageBox::Yes: // downloadUrl.addQueryItem("os", getOsName()); QDesktopServices::openUrl(downloadUrl); default: ; bd_.upgradeDeclines++; } } upgradeWarningTime = QDateTime(QDateTime::currentDateTime()); for (int i = 0; i < formatList_.size(); i++) { formatList_[i].zeroUseCounts(); } }
bool QgsPropertyKey::readXML( QDomNode & keyNode ) { int i = 0; QDomNodeList subkeys = keyNode.childNodes(); while ( i < subkeys.count() ) { // if the current node is an element that has a "type" attribute, // then we know it's a leaf node; i.e., a subkey _value_, and not // a subkey if ( subkeys.item( i ).hasAttributes() && // if we have attributes subkeys.item( i ).isElement() && // and we're an element subkeys.item( i ).toElement().hasAttribute( "type" ) ) // and we have a "type" attribute { // then we're a key value delete mProperties.take( subkeys.item( i ).nodeName() ); mProperties.insert( subkeys.item( i ).nodeName(), new QgsPropertyValue ); QDomNode subkey = subkeys.item( i ); if ( !mProperties[subkeys.item( i ).nodeName()]->readXML( subkey ) ) { QgsDebugMsg( QString( "unable to parse key value %1" ).arg( subkeys.item( i ).nodeName() ) ); } } else // otherwise it's a subkey, so just recurse on down the remaining keys { addKey( subkeys.item( i ).nodeName() ); QDomNode subkey = subkeys.item( i ); if ( !mProperties[subkeys.item( i ).nodeName()]->readXML( subkey ) ) { QgsDebugMsg( QString( "unable to parse subkey %1" ).arg( subkeys.item( i ).nodeName() ) ); } } ++i; } return true; } // QgsPropertyKey::readXML(QDomNode & keyNode)
bool ParameterEdit::setDocument(const QDomDocument & doc) { QDomElement root = doc.documentElement(); if(root.tagName() != "report") { QMessageBox::critical(this, tr("Not a Valid Report"), tr("The report definition does not appear to be a valid report." "\n\nThe root node is not 'report'.")); return false; } _list->show(); _new->hide(); _delete->hide(); for(QDomNode n = root.firstChild(); !n.isNull(); n = n.nextSibling()) { if(n.nodeName() == "parameter") { QDomElement elemSource = n.toElement(); ORParameter param; param.name = elemSource.attribute("name"); if(param.name.isEmpty()) continue; param.type = elemSource.attribute("type"); param.defaultValue = elemSource.attribute("default"); param.active = (elemSource.attribute("active") == "true"); param.listtype = elemSource.attribute("listtype"); QList<QPair<QString,QString> > pairs; if(param.listtype.isEmpty()) param.description = elemSource.text(); else { QDomNodeList section = elemSource.childNodes(); for(int nodeCounter = 0; nodeCounter < section.count(); nodeCounter++) { QDomElement elemThis = section.item(nodeCounter).toElement(); if(elemThis.tagName() == "description") param.description = elemThis.text(); else if(elemThis.tagName() == "query") param.query = elemThis.text(); else if(elemThis.tagName() == "item") param.values.append(qMakePair(elemThis.attribute("value"), elemThis.text())); else qDebug("While parsing parameter encountered an unknown element: %s",(const char*)elemThis.tagName().toLatin1().data()); } } QVariant defaultVar; if(!param.defaultValue.isEmpty()) defaultVar = QVariant(param.defaultValue); if("integer" == param.type) defaultVar = defaultVar.toInt(); else if("double" == param.type) defaultVar = defaultVar.toDouble(); else if("bool" == param.type) defaultVar = QVariant(defaultVar.toBool()); else defaultVar = defaultVar.toString(); updateParam(param.name, defaultVar, param.active); QList<QPair<QString, QString> > list; if("static" == param.listtype) list = param.values; else if("dynamic" == param.listtype && !param.query.isEmpty()) { QSqlQuery qry(param.query); while(qry.next()) list.append(qMakePair(qry.value(0).toString(), qry.value(1).toString())); } if(!list.isEmpty()) _lists.insert(param.name, list); } } if(_lists.isEmpty()) return false; // no defined parameters else return true; }
static bool loadDetailsFromXML(const QString &filename, FileDetails *details) { QDomDocument doc("mydocument"); QFile file(filename); if (!file.open(QIODevice::ReadOnly)) return false; if (!doc.setContent(&file)) { file.close(); return false; } file.close(); QString docType = doc.doctype().name(); if (docType == "MYTHARCHIVEITEM") { QDomNodeList itemNodeList = doc.elementsByTagName("item"); QString type, dbVersion; if (itemNodeList.count() < 1) { LOG(VB_GENERAL, LOG_ERR, "Couldn't find an 'item' element in XML file"); return false; } QDomNode n = itemNodeList.item(0); QDomElement e = n.toElement(); type = e.attribute("type"); dbVersion = e.attribute("databaseversion"); if (type == "recording") { QDomNodeList nodeList = e.elementsByTagName("recorded"); if (nodeList.count() < 1) { LOG(VB_GENERAL, LOG_ERR, "Couldn't find a 'recorded' element in XML file"); return false; } n = nodeList.item(0); e = n.toElement(); n = e.firstChild(); while (!n.isNull()) { e = n.toElement(); if (!e.isNull()) { if (e.tagName() == "title") details->title = e.text(); if (e.tagName() == "subtitle") details->subtitle = e.text(); if (e.tagName() == "starttime") details->startTime = MythDate::fromString(e.text()); if (e.tagName() == "description") details->description = e.text(); } n = n.nextSibling(); } // get channel info n = itemNodeList.item(0); e = n.toElement(); nodeList = e.elementsByTagName("channel"); if (nodeList.count() < 1) { LOG(VB_GENERAL, LOG_ERR, "Couldn't find a 'channel' element in XML file"); details->chanID = ""; details->chanNo = ""; details->chanName = ""; details->callsign = ""; return false; } n = nodeList.item(0); e = n.toElement(); details->chanID = e.attribute("chanid"); details->chanNo = e.attribute("channum"); details->chanName = e.attribute("name"); details->callsign = e.attribute("callsign"); return true; } else if (type == "video") { QDomNodeList nodeList = e.elementsByTagName("videometadata"); if (nodeList.count() < 1) { LOG(VB_GENERAL, LOG_ERR, "Couldn't find a 'videometadata' element in XML file"); return false; } n = nodeList.item(0); e = n.toElement(); n = e.firstChild(); while (!n.isNull()) { e = n.toElement(); if (!e.isNull()) { if (e.tagName() == "title") { details->title = e.text(); details->subtitle = ""; details->startTime = QDateTime(); } if (e.tagName() == "plot") { details->description = e.text(); } } n = n.nextSibling(); } details->chanID = "N/A"; details->chanNo = "N/A"; details->chanName = "N/A"; details->callsign = "N/A"; return true; } } return false; }
/** * Parse a kxml file and insert content into the document. Returns * true on success. */ bool KDocument::loadKxml(QString filename) { QFile file(filename); file.open(QIODevice::ReadOnly); QDomDocument document("kxml"); if (!document.setContent(&file)) { return false; } /* * Meta information */ QStringList meta; meta << "title" << "author" << "description" << "language"; for (int i = 0; i < meta.size(); i++) { setProperty( meta.at(i).toUtf8(), document.elementsByTagName( meta.at(i) ).at(0).toElement().text() ); } /* * Categories */ QDomNodeList categories = document.elementsByTagName("category"); for (uint i = 0; i < categories.length(); i++) { QDomElement category = categories.at(i).toElement(); m_categories.append(category.attribute("name")); /* * Questions */ QDomNodeList questions = category.elementsByTagName("question"); for (uint j = 0; j < questions.length(); j++) { QDomElement question = questions.at(j).toElement(); KQuestion q; q.setCategory(category.attribute("name")); // Text QDomElement text = question.elementsByTagName("text").at(0).toElement(); q.setText(text.text()); // Id if (question.hasAttribute("id")) { q.setId(question.attribute("id").toInt()); } // Type if (question.attribute("type") == "alternatives") { q.setType(KQuestion::Alternatives); } else { q.setType(KQuestion::Manual); } // Level if (question.attribute("level") == "easy") { q.setLevel(KQuestion::Easy); } else if (question.attribute("level") == "medium") { q.setLevel(KQuestion::Medium); } else { q.setLevel(KQuestion::Hard); } // Image QDomNodeList images = question.elementsByTagName("image"); if (images.count() > 0) { QDomElement image = images.at(0).toElement(); QByteArray ba = QByteArray::fromBase64(image.text().toUtf8()); QPixmap p; p.loadFromData(ba, "PNG"); q.setImage(p); } // Answers QDomNodeList answers = question.elementsByTagName("answer"); for (uint k = 0; k < answers.length(); k++) { QDomElement answer = answers.at(k).toElement(); if (answer.attribute("correct") != 0) { q.m_answers.prepend(answer.text()); } else { q.m_answers.append(answer.text()); } } m_questions.append(q); } } /* * Settings */ QDomNodeList settings = document.elementsByTagName("setting"); for (uint i = 0; i < settings.length(); i++) { QDomElement setting = settings.at(i).toElement(); m_settings.insert( setting.attribute("name"), QVariant(setting.text()) ); } m_isLoaded = true; return true; }
SyncDocument *SyncDocument::load(const QString &fileName) { SyncDocument *ret = new SyncDocument; ret->fileName = fileName; QFile file(fileName); if (!file.open(QIODevice::ReadOnly)) { QMessageBox::critical(NULL, "Error", file.errorString()); return NULL; } QDomDocument doc; QString err; if (!doc.setContent(&file, &err)) { file.close(); QMessageBox::critical(NULL, "Error", err); return NULL; } file.close(); QDomNamedNodeMap attribs = doc.documentElement().attributes(); QDomNode rowsParam = attribs.namedItem("rows"); if (!rowsParam.isNull()) { QString rowsString = rowsParam.nodeValue(); ret->setRows(rowsString.toInt()); } QDomNodeList trackNodes = doc.documentElement().elementsByTagName("track"); for (int i = 0; i < int(trackNodes.length()); ++i) { QDomNode trackNode = trackNodes.item(i); QDomNamedNodeMap attribs = trackNode.attributes(); QString name = attribs.namedItem("name").nodeValue(); // look up track-name, create it if it doesn't exist int trackIndex = sync_find_track(ret, name.toUtf8()); if (0 > trackIndex) trackIndex = int(ret->createTrack(name.toUtf8().constData())); QDomNodeList rowNodes = trackNode.childNodes(); for (int i = 0; i < int(rowNodes.length()); ++i) { QDomNode keyNode = rowNodes.item(i); QString baseName = keyNode.nodeName(); if (baseName == "key") { QDomNamedNodeMap rowAttribs = keyNode.attributes(); QString rowString = rowAttribs.namedItem("row").nodeValue(); QString valueString = rowAttribs.namedItem("value").nodeValue(); QString interpolationString = rowAttribs.namedItem("interpolation").nodeValue(); track_key k; k.row = rowString.toInt(); k.value = valueString.toFloat(); k.type = key_type(interpolationString.toInt()); Q_ASSERT(!is_key_frame(ret->tracks[trackIndex], k.row)); if (sync_set_key(ret->tracks[trackIndex], &k)) qFatal("failed to insert key"); } } } // YUCK: gathers from entire document QDomNodeList bookmarkNodes = doc.documentElement().elementsByTagName("bookmark"); for (int i = 0; i < int(bookmarkNodes.length()); ++i) { QDomNode bookmarkNode = bookmarkNodes.item(i); QDomNamedNodeMap bookmarkAttribs = bookmarkNode.attributes(); QString str = bookmarkAttribs.namedItem("row").nodeValue(); int row = str.toInt(); ret->toggleRowBookmark(row); } return ret; }
bool QgsLayoutItemScaleBar::readPropertiesFromElement( const QDomElement &itemElem, const QDomDocument &, const QgsReadWriteContext &context ) { mSettings.setHeight( itemElem.attribute( QStringLiteral( "height" ), QStringLiteral( "5.0" ) ).toDouble() ); mSettings.setLabelBarSpace( itemElem.attribute( QStringLiteral( "labelBarSpace" ), QStringLiteral( "3.0" ) ).toDouble() ); mSettings.setBoxContentSpace( itemElem.attribute( QStringLiteral( "boxContentSpace" ), QStringLiteral( "1.0" ) ).toDouble() ); mSettings.setNumberOfSegments( itemElem.attribute( QStringLiteral( "numSegments" ), QStringLiteral( "2" ) ).toInt() ); mSettings.setNumberOfSegmentsLeft( itemElem.attribute( QStringLiteral( "numSegmentsLeft" ), QStringLiteral( "0" ) ).toInt() ); mSettings.setUnitsPerSegment( itemElem.attribute( QStringLiteral( "numUnitsPerSegment" ), QStringLiteral( "1.0" ) ).toDouble() ); mSettings.setSegmentSizeMode( static_cast<QgsScaleBarSettings::SegmentSizeMode>( itemElem.attribute( QStringLiteral( "segmentSizeMode" ), QStringLiteral( "0" ) ).toInt() ) ); mSettings.setMinimumBarWidth( itemElem.attribute( QStringLiteral( "minBarWidth" ), QStringLiteral( "50" ) ).toDouble() ); mSettings.setMaximumBarWidth( itemElem.attribute( QStringLiteral( "maxBarWidth" ), QStringLiteral( "150" ) ).toDouble() ); mSegmentMillimeters = itemElem.attribute( QStringLiteral( "segmentMillimeters" ), QStringLiteral( "0.0" ) ).toDouble(); mSettings.setMapUnitsPerScaleBarUnit( itemElem.attribute( QStringLiteral( "numMapUnitsPerScaleBarUnit" ), QStringLiteral( "1.0" ) ).toDouble() ); mSettings.setLineWidth( itemElem.attribute( QStringLiteral( "outlineWidth" ), QStringLiteral( "0.3" ) ).toDouble() ); mSettings.setUnitLabel( itemElem.attribute( QStringLiteral( "unitLabel" ) ) ); mSettings.setLineJoinStyle( QgsSymbolLayerUtils::decodePenJoinStyle( itemElem.attribute( QStringLiteral( "lineJoinStyle" ), QStringLiteral( "miter" ) ) ) ); mSettings.setLineCapStyle( QgsSymbolLayerUtils::decodePenCapStyle( itemElem.attribute( QStringLiteral( "lineCapStyle" ), QStringLiteral( "square" ) ) ) ); QDomNodeList textFormatNodeList = itemElem.elementsByTagName( QStringLiteral( "text-style" ) ); if ( !textFormatNodeList.isEmpty() ) { QDomElement textFormatElem = textFormatNodeList.at( 0 ).toElement(); mSettings.textFormat().readXml( textFormatElem, context ); } else { QFont f; if ( !QgsFontUtils::setFromXmlChildNode( f, itemElem, QStringLiteral( "scaleBarFont" ) ) ) { f.fromString( itemElem.attribute( QStringLiteral( "font" ), QString() ) ); } mSettings.textFormat().setFont( f ); if ( f.pointSizeF() > 0 ) { mSettings.textFormat().setSize( f.pointSizeF() ); mSettings.textFormat().setSizeUnit( QgsUnitTypes::RenderPoints ); } else if ( f.pixelSize() > 0 ) { mSettings.textFormat().setSize( f.pixelSize() ); mSettings.textFormat().setSizeUnit( QgsUnitTypes::RenderPixels ); } } //colors //fill color QDomNodeList fillColorList = itemElem.elementsByTagName( QStringLiteral( "fillColor" ) ); if ( !fillColorList.isEmpty() ) { QDomElement fillColorElem = fillColorList.at( 0 ).toElement(); bool redOk, greenOk, blueOk, alphaOk; int fillRed, fillGreen, fillBlue, fillAlpha; fillRed = fillColorElem.attribute( QStringLiteral( "red" ) ).toDouble( &redOk ); fillGreen = fillColorElem.attribute( QStringLiteral( "green" ) ).toDouble( &greenOk ); fillBlue = fillColorElem.attribute( QStringLiteral( "blue" ) ).toDouble( &blueOk ); fillAlpha = fillColorElem.attribute( QStringLiteral( "alpha" ) ).toDouble( &alphaOk ); if ( redOk && greenOk && blueOk && alphaOk ) { mSettings.setFillColor( QColor( fillRed, fillGreen, fillBlue, fillAlpha ) ); } } else { mSettings.setFillColor( QColor( itemElem.attribute( QStringLiteral( "brushColor" ), QStringLiteral( "#000000" ) ) ) ); } //fill color 2 QDomNodeList fillColor2List = itemElem.elementsByTagName( QStringLiteral( "fillColor2" ) ); if ( !fillColor2List.isEmpty() ) { QDomElement fillColor2Elem = fillColor2List.at( 0 ).toElement(); bool redOk, greenOk, blueOk, alphaOk; int fillRed, fillGreen, fillBlue, fillAlpha; fillRed = fillColor2Elem.attribute( QStringLiteral( "red" ) ).toDouble( &redOk ); fillGreen = fillColor2Elem.attribute( QStringLiteral( "green" ) ).toDouble( &greenOk ); fillBlue = fillColor2Elem.attribute( QStringLiteral( "blue" ) ).toDouble( &blueOk ); fillAlpha = fillColor2Elem.attribute( QStringLiteral( "alpha" ) ).toDouble( &alphaOk ); if ( redOk && greenOk && blueOk && alphaOk ) { mSettings.setFillColor2( QColor( fillRed, fillGreen, fillBlue, fillAlpha ) ); } } else { mSettings.setFillColor2( QColor( itemElem.attribute( QStringLiteral( "brush2Color" ), QStringLiteral( "#ffffff" ) ) ) ); } //stroke color QDomNodeList strokeColorList = itemElem.elementsByTagName( QStringLiteral( "strokeColor" ) ); if ( !strokeColorList.isEmpty() ) { QDomElement strokeColorElem = strokeColorList.at( 0 ).toElement(); bool redOk, greenOk, blueOk, alphaOk; int strokeRed, strokeGreen, strokeBlue, strokeAlpha; strokeRed = strokeColorElem.attribute( QStringLiteral( "red" ) ).toDouble( &redOk ); strokeGreen = strokeColorElem.attribute( QStringLiteral( "green" ) ).toDouble( &greenOk ); strokeBlue = strokeColorElem.attribute( QStringLiteral( "blue" ) ).toDouble( &blueOk ); strokeAlpha = strokeColorElem.attribute( QStringLiteral( "alpha" ) ).toDouble( &alphaOk ); if ( redOk && greenOk && blueOk && alphaOk ) { mSettings.setLineColor( QColor( strokeRed, strokeGreen, strokeBlue, strokeAlpha ) ); QPen p = mSettings.pen(); p.setColor( mSettings.lineColor() ); mSettings.setPen( p ); } } else { mSettings.setLineColor( QColor( itemElem.attribute( QStringLiteral( "penColor" ), QStringLiteral( "#000000" ) ) ) ); QPen p = mSettings.pen(); p.setColor( mSettings.lineColor() ); mSettings.setPen( p ); } //font color QDomNodeList textColorList = itemElem.elementsByTagName( QStringLiteral( "textColor" ) ); if ( !textColorList.isEmpty() ) { QDomElement textColorElem = textColorList.at( 0 ).toElement(); bool redOk, greenOk, blueOk, alphaOk; int textRed, textGreen, textBlue, textAlpha; textRed = textColorElem.attribute( QStringLiteral( "red" ) ).toDouble( &redOk ); textGreen = textColorElem.attribute( QStringLiteral( "green" ) ).toDouble( &greenOk ); textBlue = textColorElem.attribute( QStringLiteral( "blue" ) ).toDouble( &blueOk ); textAlpha = textColorElem.attribute( QStringLiteral( "alpha" ) ).toDouble( &alphaOk ); if ( redOk && greenOk && blueOk && alphaOk ) { mSettings.textFormat().setColor( QColor( textRed, textGreen, textBlue, textAlpha ) ); } } else if ( itemElem.hasAttribute( QStringLiteral( "fontColor" ) ) ) { QColor c; c.setNamedColor( itemElem.attribute( QStringLiteral( "fontColor" ), QStringLiteral( "#000000" ) ) ); mSettings.textFormat().setColor( c ); } //style QString styleString = itemElem.attribute( QStringLiteral( "style" ), QString() ); setStyle( styleString.toLocal8Bit().data() ); if ( itemElem.attribute( QStringLiteral( "unitType" ) ).isEmpty() ) { QgsUnitTypes::DistanceUnit u = QgsUnitTypes::DistanceUnknownUnit; switch ( itemElem.attribute( QStringLiteral( "units" ) ).toInt() ) { case 0: u = QgsUnitTypes::DistanceUnknownUnit; break; case 1: u = QgsUnitTypes::DistanceMeters; break; case 2: u = QgsUnitTypes::DistanceFeet; break; case 3: u = QgsUnitTypes::DistanceNauticalMiles; break; } mSettings.setUnits( u ); } else { mSettings.setUnits( QgsUnitTypes::decodeDistanceUnit( itemElem.attribute( QStringLiteral( "unitType" ) ) ) ); } mSettings.setAlignment( static_cast< QgsScaleBarSettings::Alignment >( itemElem.attribute( QStringLiteral( "alignment" ), QStringLiteral( "0" ) ).toInt() ) ); //map disconnectCurrentMap(); mMap = nullptr; mMapUuid = itemElem.attribute( QStringLiteral( "mapUuid" ) ); return true; }
QList< QgsLayoutItem * > QgsLayout::loadFromTemplate( const QDomDocument &document, const QgsReadWriteContext &context, bool clearExisting, bool *ok ) { if ( ok ) *ok = false; QList< QgsLayoutItem * > result; if ( clearExisting ) { clear(); } QDomDocument doc; // If this is a 2.x composition template, convert it to a layout template if ( QgsCompositionConverter::isCompositionTemplate( document ) ) { doc = QgsCompositionConverter::convertCompositionTemplate( document, mProject ); } else { doc = document; } // remove all uuid attributes since we don't want duplicates UUIDS QDomNodeList itemsNodes = doc.elementsByTagName( QStringLiteral( "LayoutItem" ) ); for ( int i = 0; i < itemsNodes.count(); ++i ) { QDomNode itemNode = itemsNodes.at( i ); if ( itemNode.isElement() ) { itemNode.toElement().removeAttribute( QStringLiteral( "uuid" ) ); } } QDomNodeList multiFrameNodes = doc.elementsByTagName( QStringLiteral( "LayoutMultiFrame" ) ); for ( int i = 0; i < multiFrameNodes.count(); ++i ) { QDomNode multiFrameNode = multiFrameNodes.at( i ); if ( multiFrameNode.isElement() ) { multiFrameNode.toElement().removeAttribute( QStringLiteral( "uuid" ) ); QDomNodeList frameNodes = multiFrameNode.toElement().elementsByTagName( QStringLiteral( "childFrame" ) ); QDomNode itemNode = frameNodes.at( i ); if ( itemNode.isElement() ) { itemNode.toElement().removeAttribute( QStringLiteral( "uuid" ) ); } } } //read general settings if ( clearExisting ) { QDomElement layoutElem = doc.documentElement(); if ( layoutElem.isNull() ) { return result; } bool loadOk = readXml( layoutElem, doc, context ); if ( !loadOk ) { return result; } layoutItems( result ); } else { result = addItemsFromXml( doc.documentElement(), doc, context ); } if ( ok ) *ok = true; return result; }
void editorModel::loadData(TtableDef table) { activeTable = table; this->beginResetModel(); //m_dataFile = dataFile; //doc = QDomDocument("ODKDocument"); /*QFile xmlfile(dataFile); if (!xmlfile.open(QIODevice::ReadOnly)) return ; if (!doc.setContent(&xmlfile)) { xmlfile.close(); return ; } xmlfile.close();*/ int index; index = 0; //qDebug() << "Begin load data"; for (int idoc = 0; idoc <= fileList.count()-1;idoc++) { if (fileList[idoc].opened) { fileList[idoc].dataList.clear(); if (table.name == "mainModule") { QDomNodeList records; QDomNodeList fields; int clm; records = fileList[idoc].doc.elementsByTagName(table.xmlCode); for (int pos = 0; pos <= records.count()-1;pos++) { TdataDef record; record.modified = false; record.itemElement = records.item(pos).toElement(); record.index = index; for (clm = 0; clm <= activeTable.fields.count()-1; clm++) { fields = record.itemElement.elementsByTagName(activeTable.fields[clm].name); if (fields.count() > 0) { TdataItemDef item; item.ignore = false; item.modified = false; item.itemElement = fields.item(0).toElement(); item.value = fields.item(0).toElement().firstChild().nodeValue(); record.fields.append(item); } else { TdataItemDef item; item.ignore = true; item.value = "NA"; item.modified = false; record.fields.append(item); } } fileList[idoc].dataList.append(record); index++; } } else { QDomNodeList records; QDomNodeList fields; int clm; records = fileList[idoc].doc.elementsByTagName(table.name); for (int pos = 0; pos <= records.count()-1;pos++) { TdataDef record; record.modified = false; record.itemElement = records.item(pos).toElement(); record.index = index; for (clm = 0; clm <= activeTable.fields.count()-1; clm++) { fields = record.itemElement.elementsByTagName(activeTable.fields[clm].name); if (fields.count() > 0) { TdataItemDef item; item.ignore = false; item.modified = false; item.itemElement = fields.item(0).toElement(); item.value = fields.item(0).toElement().firstChild().nodeValue(); record.fields.append(item); } else { TdataItemDef item; item.ignore = true; item.value = "NA"; item.modified = false; record.fields.append(item); } } fileList[idoc].dataList.append(record); index++; } } } else { qDebug() << fileList[idoc].dataFile + " is not opened"; } } //qDebug() << "End load data"; this->endResetModel(); }
bool ConfigManager::InitDebugParams() { XmlHelper *xmlhelper = XmlHelper::GetInstance(); QString node_str; node_str = "debug"; QDomElement root = xmlhelper->GetXmlNodeParent(node_str); QDomNodeList nodelist = root.childNodes(); for(int i = 0;i < nodelist.count(); ++i) { QDomNode child = nodelist.at(i); if(child.nodeName() == "enable") { app_settings_.set_debug_enable(child.toElement().text().toInt() != 0); continue; } if(child.nodeName() == "fileenable") { app_settings_.set_debug_fileenable(child.toElement().text().toInt() != 0); continue; } if(child.nodeName() == "terminalenable") { app_settings_.set_debug_terminalenable(child.toElement().text().toInt() != 0); continue; } if(child.nodeName() == "timestamp") { app_settings_.set_debug_timestamp_enable(child.toElement().text().toInt() != 0); continue; } if(child.nodeName() == "modulename") { app_settings_.set_debug_module_name_enable(child.toElement().text().toInt() != 0); continue; } if(child.nodeName() == "level") { InitDebugLevelParams(child.toElement().text()); continue; } if(child.nodeName() == "module") { QDomNodeList modulelist = child.toElement().childNodes(); for(int j = 0;j < modulelist.count(); ++j ) { QDomNode module_child = modulelist.at(j); if(module_child.toElement().text().toInt() != 0) { app_settings_.AddModule(module_child.nodeName()); } } continue; } } return true; }
bool QgsComposerLegend::readXML( const QDomElement& itemElem, const QDomDocument& doc ) { if ( itemElem.isNull() ) { return false; } //read general properties mSettings.setTitle( itemElem.attribute( "title" ) ); if ( !itemElem.attribute( "titleAlignment" ).isEmpty() ) { mSettings.setTitleAlignment(( Qt::AlignmentFlag )itemElem.attribute( "titleAlignment" ).toInt() ); } int colCount = itemElem.attribute( "columnCount", "1" ).toInt(); if ( colCount < 1 ) colCount = 1; mSettings.setColumnCount( colCount ); mSettings.setSplitLayer( itemElem.attribute( "splitLayer", "0" ).toInt() == 1 ); mSettings.setEqualColumnWidth( itemElem.attribute( "equalColumnWidth", "0" ).toInt() == 1 ); QDomNodeList stylesNodeList = itemElem.elementsByTagName( "styles" ); if ( stylesNodeList.size() > 0 ) { QDomNode stylesNode = stylesNodeList.at( 0 ); for ( int i = 0; i < stylesNode.childNodes().size(); i++ ) { QDomElement styleElem = stylesNode.childNodes().at( i ).toElement(); QgsComposerLegendStyle style; style.readXML( styleElem, doc ); QString name = styleElem.attribute( "name" ); QgsComposerLegendStyle::Style s; if ( name == "title" ) s = QgsComposerLegendStyle::Title; else if ( name == "group" ) s = QgsComposerLegendStyle::Group; else if ( name == "subgroup" ) s = QgsComposerLegendStyle::Subgroup; else if ( name == "symbol" ) s = QgsComposerLegendStyle::Symbol; else if ( name == "symbolLabel" ) s = QgsComposerLegendStyle::SymbolLabel; else continue; setStyle( s, style ); } } //font color QColor fontClr; fontClr.setNamedColor( itemElem.attribute( "fontColor", "#000000" ) ); mSettings.setFontColor( fontClr ); //spaces mSettings.setBoxSpace( itemElem.attribute( "boxSpace", "2.0" ).toDouble() ); mSettings.setColumnSpace( itemElem.attribute( "columnSpace", "2.0" ).toDouble() ); mSettings.setSymbolSize( QSizeF( itemElem.attribute( "symbolWidth", "7.0" ).toDouble(), itemElem.attribute( "symbolHeight", "14.0" ).toDouble() ) ); mSettings.setWmsLegendSize( QSizeF( itemElem.attribute( "wmsLegendWidth", "50" ).toDouble(), itemElem.attribute( "wmsLegendHeight", "25" ).toDouble() ) ); mSettings.setWrapChar( itemElem.attribute( "wrapChar" ) ); //composer map if ( !itemElem.attribute( "map" ).isEmpty() ) { mComposerMap = mComposition->getComposerMapById( itemElem.attribute( "map" ).toInt() ); } QDomElement layerTreeElem = itemElem.firstChildElement( "layer-tree-group" ); setCustomLayerTree( QgsLayerTreeGroup::readXML( layerTreeElem ) ); //restore general composer item properties QDomNodeList composerItemList = itemElem.elementsByTagName( "ComposerItem" ); if ( composerItemList.size() > 0 ) { QDomElement composerItemElem = composerItemList.at( 0 ).toElement(); _readXML( composerItemElem, doc ); } // < 2.0 projects backward compatibility >>>>> //title font QString titleFontString = itemElem.attribute( "titleFont" ); if ( !titleFontString.isEmpty() ) { rstyle( QgsComposerLegendStyle::Title ).rfont().fromString( titleFontString ); } //group font QString groupFontString = itemElem.attribute( "groupFont" ); if ( !groupFontString.isEmpty() ) { rstyle( QgsComposerLegendStyle::Group ).rfont().fromString( groupFontString ); } //layer font QString layerFontString = itemElem.attribute( "layerFont" ); if ( !layerFontString.isEmpty() ) { rstyle( QgsComposerLegendStyle::Subgroup ).rfont().fromString( layerFontString ); } //item font QString itemFontString = itemElem.attribute( "itemFont" ); if ( !itemFontString.isEmpty() ) { rstyle( QgsComposerLegendStyle::SymbolLabel ).rfont().fromString( itemFontString ); } if ( !itemElem.attribute( "groupSpace" ).isEmpty() ) { rstyle( QgsComposerLegendStyle::Group ).setMargin( QgsComposerLegendStyle::Top, itemElem.attribute( "groupSpace", "3.0" ).toDouble() ); } if ( !itemElem.attribute( "layerSpace" ).isEmpty() ) { rstyle( QgsComposerLegendStyle::Subgroup ).setMargin( QgsComposerLegendStyle::Top, itemElem.attribute( "layerSpace", "3.0" ).toDouble() ); } if ( !itemElem.attribute( "symbolSpace" ).isEmpty() ) { rstyle( QgsComposerLegendStyle::Symbol ).setMargin( QgsComposerLegendStyle::Top, itemElem.attribute( "symbolSpace", "2.0" ).toDouble() ); rstyle( QgsComposerLegendStyle::SymbolLabel ).setMargin( QgsComposerLegendStyle::Top, itemElem.attribute( "symbolSpace", "2.0" ).toDouble() ); } // <<<<<<< < 2.0 projects backward compatibility emit itemChanged(); return true; }
void Devices::addDeviceToUsedDevList(QDomDocument &doc) { QDomNodeList list = doc.firstChildElement("device").childNodes(); if ( list.length()==0 ) return; QString device, desc, name; device = list.item(0).nodeName(); if ( device=="disk" ) { // Hard drives, floppy disks, CDROMs if (list.item(0).attributes().contains("type")) desc = list.item(0).attributes().namedItem("type").nodeValue(); name.append(QString("Disk %1").arg(desc.toUpper())); } else if ( device=="interface" ) { // Network Interface if (list.item(0).attributes().contains("type")) desc = list.item(0).attributes().namedItem("type").nodeValue(); name.append(QString("Network %1").arg(desc.toUpper())); } else if ( device=="serial" ) { // Serial port if (list.item(0).attributes().contains("type")) desc = list.item(0).attributes().namedItem("type").nodeValue(); name.append(QString("Serial Port %1").arg(desc.toUpper())); } else if ( device=="parallel" ) { // Parallel port if (list.item(0).attributes().contains("type")) desc = list.item(0).attributes().namedItem("type").nodeValue(); name.append(QString("Parallel Port %1").arg(desc.toUpper())); } else if ( device=="console" ) { // Console if (list.item(0).attributes().contains("type")) desc = list.item(0).attributes().namedItem("type").nodeValue(); name.append(QString("Console %1").arg(desc.toUpper())); } else if ( device=="channel" ) { // Channel if (list.item(0).attributes().contains("type")) desc = list.item(0).attributes().namedItem("type").nodeValue(); name.append(QString("Channel %1").arg(desc.toUpper())); } else if ( device=="smartcard" ) { // SmartCard name.append(QString("SmartCard %1").arg(desc.toUpper())); } else if ( device=="input" ) { // Input if (list.item(0).attributes().contains("type")) desc = list.item(0).attributes().namedItem("type").nodeValue(); name.append(QString("Input %1").arg(desc.toUpper())); } else if ( device=="hub" ) { // Hub if (list.item(0).attributes().contains("type")) desc = list.item(0).attributes().namedItem("type").nodeValue(); name.append(QString("Hub %1").arg(desc.toUpper())); } else if ( device=="video" ) { // Video if (list.item(0).firstChildElement("model").attributes().contains("type")) desc = list.item(0).firstChildElement("model").attributes().namedItem("type").nodeValue(); name.append(QString("Video %1").arg(desc.toUpper())); } else if ( device=="sound" ) { // Sound if (list.item(0).attributes().contains("model")) desc = list.item(0).attributes().namedItem("model").nodeValue(); name.append(QString("Sound %1").arg(desc.toUpper())); } else if ( device=="hostdev" ) { // HostDevice if (list.item(0).attributes().contains("type")) desc = list.item(0).attributes().namedItem("type").nodeValue(); name.append(QString("Host Device %1").arg(desc.toUpper())); } else if ( device=="graphics" ) { // Graphics if (list.item(0).attributes().contains("type")) desc = list.item(0).attributes().namedItem("type").nodeValue(); name.append(QString("Display %1").arg(desc.toUpper())); } else if ( device=="redirdev" ) { // Redirected devices if (list.item(0).attributes().contains("type")) desc = list.item(0).attributes().namedItem("type").nodeValue(); name.append(QString("USB Redirector %1").arg(desc.toUpper())); } else if ( device=="filesystem" ) { // Filesystems if (list.item(0).attributes().contains("type")) desc = list.item(0).attributes().namedItem("type").nodeValue(); name.append(QString("Filesystem %1").arg(desc.toUpper())); } else if ( device=="controller" ) { // Controller if (list.item(0).attributes().contains("type")) desc = list.item(0).attributes().namedItem("type").nodeValue(); name.append(QString("Controller %1").arg(desc.toUpper())); } else if ( device=="emulator" ) { // Emulator name.append(QString("Emulator")); } else if ( device=="watchdog" ) { // WatchDog if (list.item(0).attributes().contains("model")) desc = list.item(0).attributes().namedItem("model").nodeValue(); name.append(QString("WatchDog %1").arg(desc.toUpper())); } else if ( device=="memballoon" ) { // MemBalloon if (list.item(0).attributes().contains("model")) desc = list.item(0).attributes().namedItem("model").nodeValue(); name.append(QString("MemBalloon %1").arg(desc.toUpper())); } else if ( device=="rng" ) { // Random if (list.item(0).attributes().contains("model")) desc = list.item(0).attributes().namedItem("model").nodeValue(); name.append(QString("RNG %1").arg(desc.toUpper())); } else if ( device=="tpm" ) { // TPM if (list.item(0).attributes().contains("model")) desc = list.item(0).attributes().namedItem("model").nodeValue(); name.append(QString("TPM %1").arg(desc.toUpper())); } else if ( device=="nvram" ) { // NVRAM name.append(QString("NVRAM")); } else if ( device=="panic" ) { // Panic name.append(QString("Panic")); } else return; // find DeviceName in Order int i = -1; foreach (QString _name, devNameOrder) { if ( name.startsWith(_name) ) { i = devNameOrder.indexOf(_name); break; }; }; // impossible case, but... if (i<0) return; // insert item by Device Name Order bool inserted = false; do { int row = 0; QList<QListWidgetItem*> _family = usedDeviceList->findItems( devNameOrder.at(i), Qt::MatchCaseSensitive | Qt::MatchStartsWith); if ( _family.isEmpty() ) { if ( i>0) { --i; continue; }; } else { QListWidgetItem *lastItem = _family.last(); row = usedDeviceList->row( lastItem ) + 1; }; QListWidgetItem *item = new QListWidgetItem(); item->setText(name); item->setData(Qt::UserRole, doc.toString()); usedDeviceList->insertItem(row, item); //usedDeviceList->insertItem(row, name); //usedDeviceList->item(row)->setData(Qt::UserRole, doc.toString()); showDevice(item, NULL); inserted = true; } while ( !inserted ); //qDebug()<<"added New Device:"<<name; initBootDevices(); }
ResourcePtr ModelMaker::readResource(Model& model, const QDomElement& el) { QString rdfns = RDFVocab::self()->namespaceURI(); QString about = QLatin1String("about"); QString resource = QLatin1String("resource"); QString descriptionStr = QLatin1String("Description"); ResourcePtr res; ResourcePtr type = model.createResource(el.namespaceURI() + el.localName()); if (*type == *(RDFVocab::self()->seq())) { SequencePtr seq = model.createSequence(el.attribute(about)); res = seq; } else { res = model.createResource(el.attribute(about)); } model.addStatement(res, RDFVocab::self()->type(), type); QDomNodeList children = el.childNodes(); bool isSeq = res->isSequence(); for (uint i = 0; i < children.length(); ++i) { if (children.item(i).isElement()) { QDomElement ce = children.item(i).toElement(); PropertyPtr pred = model.createProperty(ce.namespaceURI() + ce.localName()); if (ce.hasAttribute(resource)) // referenced Resource via (rdf:)resource { NodePtr obj = model.createResource(ce.attribute(resource)); if (isSeq && *pred == *(RDFVocab::self()->li())) { SequencePtr tseq = boost::static_pointer_cast<Sequence>(res); tseq->append(obj); } else model.addStatement(res, pred, obj); } else if (!ce.text().isEmpty() && ce.lastChildElement().isNull()) // Literal { NodePtr obj = model.createLiteral(ce.text()); if (isSeq && *pred == *(RDFVocab::self()->li())) { SequencePtr tseq = boost::static_pointer_cast<Sequence>(res); tseq->append(obj); } else model.addStatement(res, pred, obj); } else // embedded description { QDomElement re = ce.lastChildElement(); QString uri = re.attribute(about); // read recursively NodePtr obj = readResource(model, re); if (isSeq && *pred == *(RDFVocab::self()->li())) { SequencePtr tseq = boost::static_pointer_cast<Sequence>(res); tseq->append(obj); } else model.addStatement(res, pred, obj); } //TODO: bag, reification (nice to have, but not important for basic RSS 1.0) } } return res; }
bool QgsSLDConfigParser::rasterSymbologyFromUserStyle( const QDomElement& userStyleElement, QgsRasterLayer* r ) const { return false; #if 0 //needs to be fixed QgsDebugMsg( "Entering" ); if ( !r ) { return false; } //search raster symbolizer QDomNodeList rasterSymbolizerList = userStyleElement.elementsByTagName( "RasterSymbolizer" ); if ( rasterSymbolizerList.size() < 1 ) { return false; } QDomElement rasterSymbolizerElem = rasterSymbolizerList.at( 0 ).toElement(); //search colormap and entries QDomNodeList colorMapList = rasterSymbolizerElem.elementsByTagName( "ColorMap" ); if ( colorMapList.size() < 1 ) { return false; } QDomElement colorMapElem = colorMapList.at( 0 ).toElement(); //search for color map entries r->setColorShadingAlgorithm( QgsRasterLayer::ColorRampShader ); QgsColorRampShader* myRasterShaderFunction = ( QgsColorRampShader* )r->rasterShader()->rasterShaderFunction(); QList<QgsColorRampShader::ColorRampItem> colorRampItems; QDomNodeList colorMapEntryList = colorMapElem.elementsByTagName( "ColorMapEntry" ); QDomElement currentColorMapEntryElem; bool conversion; int red, green, blue; for ( int i = 0; i < colorMapEntryList.size(); ++i ) { currentColorMapEntryElem = colorMapEntryList.at( i ).toElement(); QgsColorRampShader::ColorRampItem myNewColorRampItem; QString color = currentColorMapEntryElem.attribute( "color" ); if ( color.length() != 7 ) //color string must be in the form #ffffff { continue; } red = color.mid( 1, 2 ).toInt( &conversion, 16 ); if ( !conversion ) { red = 0; } green = color.mid( 3, 2 ).toInt( &conversion, 16 ); if ( !conversion ) { green = 0; } blue = color.mid( 5, 2 ).toInt( &conversion, 16 ); if ( !conversion ) { blue = 0; } myNewColorRampItem.color = QColor( red, green, blue ); QString value = currentColorMapEntryElem.attribute( "quantity" ); myNewColorRampItem.value = value.toDouble(); QgsDebugMsg( "Adding colormap entry" ); colorRampItems.push_back( myNewColorRampItem ); } myRasterShaderFunction->setColorRampItemList( colorRampItems ); //linear interpolation or discrete classification QString interpolation = colorMapElem.attribute( "interpolation" ); if ( interpolation == "linear" ) { myRasterShaderFunction->setColorRampType( QgsColorRampShader::INTERPOLATED ); } else if ( interpolation == "discrete" ) { myRasterShaderFunction->setColorRampType( QgsColorRampShader::DISCRETE ); } //QgsDebugMsg("Setting drawing style"); r->setDrawingStyle( QgsRasterLayer::SingleBandPseudoColor ); //set pseudo color mode return true; #else Q_UNUSED( userStyleElement ); Q_UNUSED( r ); #endif //0 }
void XSPFLoader::gotBody() { qDebug() << Q_FUNC_INFO; QDomDocument xmldoc; bool namespaceProcessing = true; xmldoc.setContent( m_body, namespaceProcessing ); QDomElement docElement( xmldoc.documentElement() ); QString origTitle; QDomNodeList tracklist; QDomElement n = docElement.firstChildElement(); for ( ; !n.isNull(); n = n.nextSiblingElement() ) { if (n.namespaceURI() == m_NS && n.localName() == "title") { origTitle = n.text(); } else if (n.namespaceURI() == m_NS && n.localName() == "creator") { m_creator = n.text(); } else if (n.namespaceURI() == m_NS && n.localName() == "info") { m_info = n.text(); } else if (n.namespaceURI() == m_NS && n.localName() == "trackList") { tracklist = n.childNodes(); } } m_title = origTitle; if ( m_title.isEmpty() ) m_title = tr( "New Playlist" ); if( !m_overrideTitle.isEmpty() ) m_title = m_overrideTitle; bool shownError = false; for ( unsigned int i = 0; i < tracklist.length(); i++ ) { QDomNode e = tracklist.at( i ); QString artist, album, track, duration, annotation, url; QDomElement n = e.firstChildElement(); for ( ; !n.isNull(); n = n.nextSiblingElement() ) { if (n.namespaceURI() == m_NS && n.localName() == "duration") { duration = n.text(); } else if (n.namespaceURI() == m_NS && n.localName() == "annotation") { annotation = n.text(); } else if (n.namespaceURI() == m_NS && n.localName() == "creator") { artist = n.text(); } else if (n.namespaceURI() == m_NS && n.localName() == "album") { album = n.text(); } else if (n.namespaceURI() == m_NS && n.localName() == "title") { track = n.text(); } else if (n.namespaceURI() == m_NS && n.localName() == "url") { url = n.text(); } } if( artist.isEmpty() || track.isEmpty() ) { if( !shownError ) { QMessageBox::warning( 0, tr( "Failed to save tracks" ), tr( "Some tracks in the playlist do not contain an artist and a title. They will be ignored." ), QMessageBox::Ok ); shownError = true; } continue; } query_ptr q = Tomahawk::Query::get( artist, track, album, uuid() ); q->setDuration( duration.toInt() / 1000 ); if( !url.isEmpty() ) q->setResultHint( url ); m_entries << q; } if ( origTitle.isEmpty() && m_entries.isEmpty() ) { if ( m_autoCreate ) { QMessageBox::critical( 0, tr( "XSPF Error" ), tr( "This is not a valid XSPF playlist." ) ); deleteLater(); return; } else { emit failed(); return; } } if ( m_autoCreate ) { m_playlist = Playlist::create( SourceList::instance()->getLocal(), uuid(), m_title, m_info, m_creator, false, m_entries ); deleteLater(); } emit ok( m_playlist ); }
QgsVectorLayer* QgsSLDConfigParser::contourLayerFromRaster( const QDomElement& userStyleElem, QgsRasterLayer* rasterLayer ) const { QgsDebugMsg( "Entering." ); if ( !rasterLayer ) { return nullptr; } //get <ContourSymbolizer> element QDomNodeList contourNodeList = userStyleElem.elementsByTagName( QStringLiteral( "ContourSymbolizer" ) ); if ( contourNodeList.size() < 1 ) { return nullptr; } QDomElement contourSymbolizerElem = contourNodeList.item( 0 ).toElement(); if ( contourSymbolizerElem.isNull() ) { return nullptr; } double equidistance, minValue, maxValue, offset; QString propertyName; equidistance = contourSymbolizerElem.attribute( QStringLiteral( "equidistance" ) ).toDouble(); minValue = contourSymbolizerElem.attribute( QStringLiteral( "minValue" ) ).toDouble(); maxValue = contourSymbolizerElem.attribute( QStringLiteral( "maxValue" ) ).toDouble(); offset = contourSymbolizerElem.attribute( QStringLiteral( "offset" ) ).toDouble(); propertyName = contourSymbolizerElem.attribute( QStringLiteral( "propertyName" ) ); if ( equidistance <= 0.0 ) { return nullptr; } QTemporaryFile* tmpFile1 = new QTemporaryFile(); tmpFile1->open(); mFilesToRemove.push_back( tmpFile1 ); QString tmpBaseName = tmpFile1->fileName(); QString tmpFileName = tmpBaseName + ".shp"; //hack: use gdal_contour first to write into a temporary file /* todo: use GDALContourGenerate( hBand, dfInterval, dfOffset, nFixedLevelCount, adfFixedLevels, bNoDataSet, dfNoData, hLayer, 0, nElevField, GDALTermProgress, nullptr );*/ //do the stuff that is also done in the main method of gdal_contour... /* -------------------------------------------------------------------- */ /* Open source raster file. */ /* -------------------------------------------------------------------- */ GDALRasterBandH hBand; GDALDatasetH hSrcDS; int numberOfLevels = 0; double currentLevel = 0.0; if ( maxValue > minValue ) { //find first level currentLevel = ( int )(( minValue - offset ) / equidistance + 0.5 ) * equidistance + offset; while ( currentLevel <= maxValue ) { ++numberOfLevels; currentLevel += equidistance; } } double *adfFixedLevels = new double[numberOfLevels]; int nFixedLevelCount = numberOfLevels; currentLevel = ( int )(( minValue - offset ) / equidistance + 0.5 ) * equidistance + offset; for ( int i = 0; i < numberOfLevels; ++i ) { adfFixedLevels[i] = currentLevel; currentLevel += equidistance; } int nBandIn = 1; double dfInterval = equidistance, dfNoData = 0.0, dfOffset = offset; int /* b3D = FALSE, */ bNoDataSet = FALSE, bIgnoreNoData = FALSE; hSrcDS = GDALOpen( rasterLayer->source().toUtf8().constData(), GA_ReadOnly ); if ( !hSrcDS ) { delete [] adfFixedLevels; throw QgsMapServiceException( QStringLiteral( "LayerNotDefined" ), QStringLiteral( "Operation request is for a file not available on the server." ) ); } hBand = GDALGetRasterBand( hSrcDS, nBandIn ); if ( !hBand ) { CPLError( CE_Failure, CPLE_AppDefined, "Band %d does not exist on dataset.", nBandIn ); } if ( !bNoDataSet && !bIgnoreNoData ) dfNoData = GDALGetRasterNoDataValue( hBand, &bNoDataSet ); /* -------------------------------------------------------------------- */ /* Try to get a coordinate system from the raster. */ /* -------------------------------------------------------------------- */ OGRSpatialReferenceH hSRS = nullptr; const char *pszWKT = GDALGetProjectionRef( hBand ); if ( pszWKT && strlen( pszWKT ) != 0 ) hSRS = OSRNewSpatialReference( pszWKT ); /* -------------------------------------------------------------------- */ /* Create the outputfile. */ /* -------------------------------------------------------------------- */ OGRDataSourceH hDS; OGRSFDriverH hDriver = OGRGetDriverByName( "ESRI Shapefile" ); OGRFieldDefnH hFld; OGRLayerH hLayer; int nElevField = -1; if ( !hDriver ) { //fprintf( FCGI_stderr, "Unable to find format driver named 'ESRI Shapefile'.\n" ); delete [] adfFixedLevels; throw QgsMapServiceException( QStringLiteral( "LayerNotDefined" ), QStringLiteral( "Operation request is for a file not available on the server." ) ); } hDS = OGR_Dr_CreateDataSource( hDriver, tmpFileName.toUtf8().constData(), nullptr ); if ( !hDS ) { delete [] adfFixedLevels; throw QgsMapServiceException( QStringLiteral( "LayerNotDefined" ), QStringLiteral( "Operation request cannot create data source." ) ); } hLayer = OGR_DS_CreateLayer( hDS, "contour", hSRS, /* b3D ? wkbLineString25D : */ wkbLineString, nullptr ); if ( !hLayer ) { delete [] adfFixedLevels; throw QgsMapServiceException( QStringLiteral( "LayerNotDefined" ), QStringLiteral( "Operation request could not create contour file." ) ); } hFld = OGR_Fld_Create( "ID", OFTInteger ); OGR_Fld_SetWidth( hFld, 8 ); OGR_L_CreateField( hLayer, hFld, FALSE ); OGR_Fld_Destroy( hFld ); if ( !propertyName.isEmpty() ) { hFld = OGR_Fld_Create( propertyName.toUtf8().constData(), OFTReal ); OGR_Fld_SetWidth( hFld, 12 ); OGR_Fld_SetPrecision( hFld, 3 ); OGR_L_CreateField( hLayer, hFld, FALSE ); OGR_Fld_Destroy( hFld ); nElevField = 1; } /* -------------------------------------------------------------------- */ /* Invoke. */ /* -------------------------------------------------------------------- */ GDALContourGenerate( hBand, dfInterval, dfOffset, nFixedLevelCount, adfFixedLevels, bNoDataSet, dfNoData, hLayer, 0, nElevField, GDALTermProgress, nullptr ); delete [] adfFixedLevels; OGR_DS_Destroy( hDS ); GDALClose( hSrcDS ); //todo: store those three files elsewhere... //mark shp, dbf and shx to delete after the request mFilePathsToRemove.push_back( tmpBaseName + ".shp" ); mFilePathsToRemove.push_back( tmpBaseName + ".dbf" ); mFilePathsToRemove.push_back( tmpBaseName + ".shx" ); QgsVectorLayer* contourLayer = new QgsVectorLayer( tmpFileName, QStringLiteral( "layer" ), QStringLiteral( "ogr" ) ); //create renderer QgsFeatureRenderer* theRenderer = rendererFromUserStyle( userStyleElem, contourLayer ); contourLayer->setRenderer( theRenderer ); //add labeling if requested labelSettingsFromUserStyle( userStyleElem, contourLayer ); QgsDebugMsg( "Returning the contour layer" ); return contourLayer; }
void XmlCndInterface::readConditions(const QDomNode &listRoot, FEMCondition::CondType type) { QDomElement cond = listRoot.firstChildElement(); while (!cond.isNull()) { std::string geometry_name ( cond.attribute("geometry").toStdString() ); if (this->_project->getGEOObjects()->exists(geometry_name) >= 0 || this->_project->meshExists(geometry_name)) { FEMCondition* c ( new FEMCondition(geometry_name, type) ); QDomNodeList condProperties = cond.childNodes(); for (int i = 0; i < condProperties.count(); i++) { const QDomNode prop_node (condProperties.at(i)); if (condProperties.at(i).nodeName().compare("Process") == 0) { QDomNodeList processProps = prop_node.childNodes(); for (int j = 0; j < processProps.count(); j++) { const QString prop_name(processProps.at(j).nodeName()); if (prop_name.compare("Type") == 0) c->setProcessType(FiniteElement::convertProcessType(processProps.at(j).toElement().text().toStdString())); else if (prop_name.compare("Variable") == 0) c->setProcessPrimaryVariable(FiniteElement::convertPrimaryVariable(processProps.at(j).toElement().text().toStdString())); } } else if (prop_node.nodeName().compare("Geometry") == 0) { QDomNodeList geoProps = prop_node.childNodes(); GeoLib::GEOTYPE geo_type; std::string geo_obj_name; for (int j = 0; j < geoProps.count(); j++) { const QString prop_name(geoProps.at(j).nodeName()); if (prop_name.compare("Type") == 0) geo_type = GeoLib::convertGeoType(geoProps.at(j).toElement().text().toStdString()); else if (prop_name.compare("Name") == 0) geo_obj_name = geoProps.at(j).toElement().text().toStdString(); } c->initGeometricAttributes(geometry_name, geo_type, geo_obj_name, *(_project->getGEOObjects())); } else if (prop_node.nodeName().compare("Distribution") == 0) { QDomNodeList distProps = prop_node.childNodes(); for (int j = 0; j < distProps.count(); j++) { const QString prop_name(distProps.at(j).nodeName()); if (prop_name.compare("Type") == 0) c->setProcessDistributionType(FiniteElement::convertDisType(distProps.at(j).toElement().text().toStdString())); else if (prop_name.compare("Value") == 0) { std::vector<size_t> disNodes; std::vector<double> disValues; if (c->getProcessDistributionType()==FiniteElement::CONSTANT || c->getProcessDistributionType()==FiniteElement::CONSTANT_NEUMANN) disValues.push_back( distProps.at(j).toElement().text().toDouble() ); else if (c->getProcessDistributionType()==FiniteElement::LINEAR || c->getProcessDistributionType()==FiniteElement::LINEAR_NEUMANN || c->getProcessDistributionType()==FiniteElement::DIRECT) { QString text = distProps.at(j).toElement().text(); QStringList list = text.split(QRegExp("\\t")); size_t count(0); for (QStringList::iterator it=list.begin(); it!=list.end(); ++it) { QString val (it->trimmed()); if (!val.isEmpty()) { if (count%2==0) disNodes.push_back(val.toInt()); else disValues.push_back(val.toDouble()); count++; } } } else ERR("XmlCndInterface::readConditions(): Distribution type not supported."); c->setDisValues(disNodes, disValues); } } } } this->_project->addCondition(c); } else { ERR("XmlCndInterface::readConditions(): No geometry \"%s\" found.", geometry_name.c_str()); } cond = cond.nextSiblingElement(); } }
bool StopSpam::processMuc(int account, const QDomElement& stanza) { if(stanza.tagName() == "presence") { QStringList jidList = stanza.attribute("from").split("/"); int i = mucUsers_.size(); if(findMuc(jidList.first(),jidList.last(), i)) { MucUser &mu = mucUsers_[i]; QDomNodeList nodeList = stanza.elementsByTagName("x"); for(int i = nodeList.size(); i> 0;) { QDomNode node = nodeList.at(--i).firstChild(); while(!node.isNull()) { QDomElement item = node.toElement(); if(item.tagName() == "item") { mu.affiliation = item.attribute("affiliation"); mu.role = item.attribute("role"); mu.jid = item.attribute("jid"); break; } node = node.nextSibling(); } } } else { MucUser mu; mu.mucJid = jidList.first(); mu.nick = jidList.last(); QDomNodeList nodeList = stanza.elementsByTagName("x"); for(int i = nodeList.size(); i> 0;) { QDomNode node = nodeList.at(--i).firstChild(); while(!node.isNull()) { QDomElement item = node.toElement(); if(item.tagName() == "item") { mu.affiliation = item.attribute("affiliation"); mu.role = item.attribute("role"); mu.jid = item.attribute("jid"); break; } node = node.nextSibling(); } } mucUsers_ << mu; } } else if(stanza.tagName() == "message" && stanza.attribute("type") == "chat") { QDomElement subj = stanza.firstChildElement("subject"); if (subj.text() == "StopSpam" || subj.text() == "StopSpam Question") return false; QString valF = stanza.attribute("from"); if (contactInfo->isConference(account, valF)) return false; MucUser mu; QStringList jidList = valF.split("/"); int i = mucUsers_.size(); if(findMuc(jidList.first(),jidList.last(), i)) { mu = mucUsers_[i]; } else { mu.affiliation = ""; mu.jid = ""; mu.mucJid = ""; mu.nick = ""; mu.role = ""; } bool find = false; if(mu.affiliation == "owner" && !Owner) find = true; else if( mu.affiliation == "admin" && !Admin) find = true; else if(mu.affiliation == "none" && !None) find = true; else if(mu.affiliation == "member" && !Member) find = true; if(find) return false; if(mu.role == "moderator" && !Moder) find = true; else if(mu.role == "participant" && !Participant) find = true; else if(mu.role == "visitor" && !Visitor) find = true; if(find) return false; QStringList UnblockedJids = Unblocked.split("\n"); if(UnblockedJids.contains(valF, Qt::CaseInsensitive)) return false; for(int i = 0; i < Jids.size(); i++) { QString jid_ = Jids.at(i); if(jid_.isEmpty()) continue; if(mu.jid.contains(jid_, Qt::CaseInsensitive) || mu.nick.contains(jid_, Qt::CaseInsensitive) || mu.mucJid.contains(jid_, Qt::CaseInsensitive)) { if(!selected[i].toBool()) return false; break; } } QDomElement Body = stanza.firstChildElement("body"); if(Body.isNull()) return false; if(BlockAll) { updateCounter(stanza, false); if(EnableBlockAllMes) stanzaHost->sendMessage(account, valF, BlockAllMes, "StopSpam", "chat"); return true; } QString BodyText = Body.text(); if(BodyText == Answer) { Unblocked += valF + "\n"; QVariant vUnblocked(Unblocked); psiOptions->setPluginOption(constUnblocked, vUnblocked); psiOptions->setPluginOption(constLastUnblock, QVariant(QDate::currentDate().toString("yyyyMMdd"))); stanzaHost->sendMessage(account, valF, Congratulation, "StopSpam", "chat"); updateCounter(stanza, true); return true; } else { int i = BlockedJids.size(); if(findAcc(account, valF, i)) { Blocked &B = BlockedJids[i]; if(B.count < Times) { stanzaHost->sendMessage(account, valF, Question, "StopSpam Question", "chat"); updateCounter(stanza, false); B.count++; B.LastMes = QDateTime::currentDateTime(); return true; } else { if(QDateTime::currentDateTime().secsTo(B.LastMes) >= -ResetTime*60) { updateCounter(stanza, false); return true; } else { B.count = 1; B.LastMes = QDateTime::currentDateTime(); stanzaHost->sendMessage(account, valF, Question, "StopSpam Question", "chat"); updateCounter(stanza, false); return true; } } } else { Blocked B = { account, valF, 1, QDateTime::currentDateTime() }; BlockedJids << B; stanzaHost->sendMessage(account, valF, Question, "StopSpam Question", "chat"); updateCounter(stanza, false); return true; } } } return false; }
void QgsWfsCapabilities::capabilitiesReplyFinished() { const QByteArray &buffer = mResponse; QgsDebugMsg( "parsing capabilities: " + buffer ); // parse XML QString capabilitiesDocError; QDomDocument capabilitiesDocument; if ( !capabilitiesDocument.setContent( buffer, true, &capabilitiesDocError ) ) { mErrorCode = QgsWfsRequest::XmlError; mErrorMessage = capabilitiesDocError; emit gotCapabilities(); return; } QDomElement doc = capabilitiesDocument.documentElement(); // handle exceptions if ( doc.tagName() == QLatin1String( "ExceptionReport" ) ) { QDomNode ex = doc.firstChild(); QString exc = ex.toElement().attribute( QStringLiteral( "exceptionCode" ), QStringLiteral( "Exception" ) ); QDomElement ext = ex.firstChild().toElement(); mErrorCode = QgsWfsRequest::ServerExceptionError; mErrorMessage = exc + ": " + ext.firstChild().nodeValue(); emit gotCapabilities(); return; } mCaps.clear(); //test wfs version mCaps.version = doc.attribute( QStringLiteral( "version" ) ); if ( !mCaps.version.startsWith( QLatin1String( "1.0" ) ) && !mCaps.version.startsWith( QLatin1String( "1.1" ) ) && !mCaps.version.startsWith( QLatin1String( "2.0" ) ) ) { mErrorCode = WFSVersionNotSupported; mErrorMessage = tr( "WFS version %1 not supported" ).arg( mCaps.version ); emit gotCapabilities(); return; } // WFS 2.0 implementation are supposed to implement resultType=hits, and some // implementations (GeoServer) might advertize it, whereas others (MapServer) do not. // WFS 1.1 implementation too I think, but in the examples of the GetCapabilities // response of the WFS 1.1 standard (and in common implementations), this is // explicitly advertized if ( mCaps.version.startsWith( QLatin1String( "2.0" ) ) ) mCaps.supportsHits = true; // Note: for conveniency, we do not use the elementsByTagNameNS() method as // the WFS and OWS namespaces URI are not the same in all versions if ( mCaps.version.startsWith( QLatin1String( "1.0" ) ) ) { QDomElement capabilityElem = doc.firstChildElement( QStringLiteral( "Capability" ) ); if ( !capabilityElem.isNull() ) { QDomElement requestElem = capabilityElem.firstChildElement( QStringLiteral( "Request" ) ); if ( !requestElem.isNull() ) { QDomElement getFeatureElem = requestElem.firstChildElement( QStringLiteral( "GetFeature" ) ); if ( !getFeatureElem.isNull() ) { QDomElement resultFormatElem = getFeatureElem.firstChildElement( QStringLiteral( "ResultFormat" ) ); if ( !resultFormatElem.isNull() ) { QDomElement child = resultFormatElem.firstChildElement(); while ( !child.isNull() ) { mCaps.outputFormats << child.tagName(); child = child.nextSiblingElement(); } } } } } } // find <ows:OperationsMetadata> QDomElement operationsMetadataElem = doc.firstChildElement( QStringLiteral( "OperationsMetadata" ) ); if ( !operationsMetadataElem.isNull() ) { QDomNodeList contraintList = operationsMetadataElem.elementsByTagName( QStringLiteral( "Constraint" ) ); for ( int i = 0; i < contraintList.size(); ++i ) { QDomElement contraint = contraintList.at( i ).toElement(); if ( contraint.attribute( QStringLiteral( "name" ) ) == QLatin1String( "DefaultMaxFeatures" ) /* WFS 1.1 */ ) { QDomElement value = contraint.firstChildElement( QStringLiteral( "Value" ) ); if ( !value.isNull() ) { mCaps.maxFeatures = value.text().toInt(); QgsDebugMsg( QString( "maxFeatures: %1" ).arg( mCaps.maxFeatures ) ); } } else if ( contraint.attribute( QStringLiteral( "name" ) ) == QLatin1String( "CountDefault" ) /* WFS 2.0 (e.g. MapServer) */ ) { QDomElement value = contraint.firstChildElement( QStringLiteral( "DefaultValue" ) ); if ( !value.isNull() ) { mCaps.maxFeatures = value.text().toInt(); QgsDebugMsg( QString( "maxFeatures: %1" ).arg( mCaps.maxFeatures ) ); } } else if ( contraint.attribute( QStringLiteral( "name" ) ) == QLatin1String( "ImplementsResultPaging" ) /* WFS 2.0 */ ) { QDomElement value = contraint.firstChildElement( QStringLiteral( "DefaultValue" ) ); if ( !value.isNull() && value.text() == QLatin1String( "TRUE" ) ) { mCaps.supportsPaging = true; QgsDebugMsg( "Supports paging" ); } } else if ( contraint.attribute( QStringLiteral( "name" ) ) == QLatin1String( "ImplementsStandardJoins" ) || contraint.attribute( QStringLiteral( "name" ) ) == QLatin1String( "ImplementsSpatialJoins" ) /* WFS 2.0 */ ) { QDomElement value = contraint.firstChildElement( QStringLiteral( "DefaultValue" ) ); if ( !value.isNull() && value.text() == QLatin1String( "TRUE" ) ) { mCaps.supportsJoins = true; QgsDebugMsg( "Supports joins" ); } } } // In WFS 2.0, max features can also be set in Operation.GetFeature (e.g. GeoServer) // and we are also interested by resultType=hits for WFS 1.1 QDomNodeList operationList = operationsMetadataElem.elementsByTagName( QStringLiteral( "Operation" ) ); for ( int i = 0; i < operationList.size(); ++i ) { QDomElement operation = operationList.at( i ).toElement(); if ( operation.attribute( QStringLiteral( "name" ) ) == QLatin1String( "GetFeature" ) ) { QDomNodeList operationContraintList = operation.elementsByTagName( QStringLiteral( "Constraint" ) ); for ( int j = 0; j < operationContraintList.size(); ++j ) { QDomElement contraint = operationContraintList.at( j ).toElement(); if ( contraint.attribute( QStringLiteral( "name" ) ) == QLatin1String( "CountDefault" ) ) { QDomElement value = contraint.firstChildElement( QStringLiteral( "DefaultValue" ) ); if ( !value.isNull() ) { mCaps.maxFeatures = value.text().toInt(); QgsDebugMsg( QString( "maxFeatures: %1" ).arg( mCaps.maxFeatures ) ); } break; } } QDomNodeList parameterList = operation.elementsByTagName( QStringLiteral( "Parameter" ) ); for ( int j = 0; j < parameterList.size(); ++j ) { QDomElement parameter = parameterList.at( j ).toElement(); if ( parameter.attribute( QStringLiteral( "name" ) ) == QLatin1String( "resultType" ) ) { QDomNodeList valueList = parameter.elementsByTagName( QStringLiteral( "Value" ) ); for ( int k = 0; k < valueList.size(); ++k ) { QDomElement value = valueList.at( k ).toElement(); if ( value.text() == QLatin1String( "hits" ) ) { mCaps.supportsHits = true; QgsDebugMsg( "Support hits" ); break; } } } else if ( parameter.attribute( QStringLiteral( "name" ) ) == QLatin1String( "outputFormat" ) ) { QDomNodeList valueList = parameter.elementsByTagName( QStringLiteral( "Value" ) ); for ( int k = 0; k < valueList.size(); ++k ) { QDomElement value = valueList.at( k ).toElement(); mCaps.outputFormats << value.text(); } } } break; } } } //go to <FeatureTypeList> QDomElement featureTypeListElem = doc.firstChildElement( QStringLiteral( "FeatureTypeList" ) ); if ( featureTypeListElem.isNull() ) { emit gotCapabilities(); return; } // Parse operations supported for all feature types bool insertCap = false; bool updateCap = false; bool deleteCap = false; // WFS < 2 if ( mCaps.version.startsWith( QLatin1String( "1" ) ) ) { parseSupportedOperations( featureTypeListElem.firstChildElement( QStringLiteral( "Operations" ) ), insertCap, updateCap, deleteCap ); } else // WFS 2.0.0 tested on GeoServer { QDomNodeList operationNodes = doc.elementsByTagName( "Operation" ); for ( int i = 0; i < operationNodes.count(); i++ ) { QDomElement operationElement = operationNodes.at( i ).toElement( ); if ( operationElement.isElement( ) && "Transaction" == operationElement.attribute( "name" ) ) { insertCap = true; updateCap = true; deleteCap = true; } } } // get the <FeatureType> elements QDomNodeList featureTypeList = featureTypeListElem.elementsByTagName( QStringLiteral( "FeatureType" ) ); for ( int i = 0; i < featureTypeList.size(); ++i ) { FeatureType featureType; QDomElement featureTypeElem = featureTypeList.at( i ).toElement(); //Name QDomNodeList nameList = featureTypeElem.elementsByTagName( QStringLiteral( "Name" ) ); if ( nameList.length() > 0 ) { featureType.name = nameList.at( 0 ).toElement().text(); } //Title QDomNodeList titleList = featureTypeElem.elementsByTagName( QStringLiteral( "Title" ) ); if ( titleList.length() > 0 ) { featureType.title = titleList.at( 0 ).toElement().text(); } //Abstract QDomNodeList abstractList = featureTypeElem.elementsByTagName( QStringLiteral( "Abstract" ) ); if ( abstractList.length() > 0 ) { featureType.abstract = abstractList.at( 0 ).toElement().text(); } //DefaultSRS is always the first entry in the feature srs list QDomNodeList defaultCRSList = featureTypeElem.elementsByTagName( QStringLiteral( "DefaultSRS" ) ); if ( defaultCRSList.length() == 0 ) // In WFS 2.0, this is spelled DefaultCRS... defaultCRSList = featureTypeElem.elementsByTagName( QStringLiteral( "DefaultCRS" ) ); if ( defaultCRSList.length() > 0 ) { QString srsname( defaultCRSList.at( 0 ).toElement().text() ); // Some servers like Geomedia advertize EPSG:XXXX even in WFS 1.1 or 2.0 if ( srsname.startsWith( QLatin1String( "EPSG:" ) ) ) mCaps.useEPSGColumnFormat = true; featureType.crslist.append( NormalizeSRSName( srsname ) ); } //OtherSRS QDomNodeList otherCRSList = featureTypeElem.elementsByTagName( QStringLiteral( "OtherSRS" ) ); if ( otherCRSList.length() == 0 ) // In WFS 2.0, this is spelled OtherCRS... otherCRSList = featureTypeElem.elementsByTagName( QStringLiteral( "OtherCRS" ) ); for ( int i = 0; i < otherCRSList.size(); ++i ) { featureType.crslist.append( NormalizeSRSName( otherCRSList.at( i ).toElement().text() ) ); } //Support <SRS> for compatibility with older versions QDomNodeList srsList = featureTypeElem.elementsByTagName( QStringLiteral( "SRS" ) ); for ( int i = 0; i < srsList.size(); ++i ) { featureType.crslist.append( NormalizeSRSName( srsList.at( i ).toElement().text() ) ); } // Get BBox WFS 1.0 way QDomElement latLongBB = featureTypeElem.firstChildElement( QStringLiteral( "LatLongBoundingBox" ) ); if ( latLongBB.hasAttributes() ) { // Despite the name LatLongBoundingBox, the coordinates are supposed to // be expressed in <SRS>. From the WFS schema; // <!-- The LatLongBoundingBox element is used to indicate the edges of // an enclosing rectangle in the SRS of the associated feature type. featureType.bbox = QgsRectangle( latLongBB.attribute( QStringLiteral( "minx" ) ).toDouble(), latLongBB.attribute( QStringLiteral( "miny" ) ).toDouble(), latLongBB.attribute( QStringLiteral( "maxx" ) ).toDouble(), latLongBB.attribute( QStringLiteral( "maxy" ) ).toDouble() ); featureType.bboxSRSIsWGS84 = false; // But some servers do not honour this and systematically reproject to WGS84 // such as GeoServer. See http://osgeo-org.1560.x6.nabble.com/WFS-LatLongBoundingBox-td3813810.html // This is also true of TinyOWS if ( !featureType.crslist.isEmpty() && featureType.bbox.xMinimum() >= -180 && featureType.bbox.yMinimum() >= -90 && featureType.bbox.xMaximum() <= 180 && featureType.bbox.yMaximum() < 90 ) { QgsCoordinateReferenceSystem crs = QgsCoordinateReferenceSystem::fromOgcWmsCrs( featureType.crslist[0] ); if ( !crs.isGeographic() ) { // If the CRS is projected then check that projecting the corner of the bbox, assumed to be in WGS84, // into the CRS, and then back to WGS84, works (check that we are in the validity area) QgsCoordinateReferenceSystem crsWGS84 = QgsCoordinateReferenceSystem::fromOgcWmsCrs( QStringLiteral( "CRS:84" ) ); QgsCoordinateTransform ct( crsWGS84, crs ); QgsPointXY ptMin( featureType.bbox.xMinimum(), featureType.bbox.yMinimum() ); QgsPointXY ptMinBack( ct.transform( ct.transform( ptMin, QgsCoordinateTransform::ForwardTransform ), QgsCoordinateTransform::ReverseTransform ) ); QgsPointXY ptMax( featureType.bbox.xMaximum(), featureType.bbox.yMaximum() ); QgsPointXY ptMaxBack( ct.transform( ct.transform( ptMax, QgsCoordinateTransform::ForwardTransform ), QgsCoordinateTransform::ReverseTransform ) ); QgsDebugMsg( featureType.bbox.toString() ); QgsDebugMsg( ptMinBack.toString() ); QgsDebugMsg( ptMaxBack.toString() ); if ( fabs( featureType.bbox.xMinimum() - ptMinBack.x() ) < 1e-5 && fabs( featureType.bbox.yMinimum() - ptMinBack.y() ) < 1e-5 && fabs( featureType.bbox.xMaximum() - ptMaxBack.x() ) < 1e-5 && fabs( featureType.bbox.yMaximum() - ptMaxBack.y() ) < 1e-5 ) { QgsDebugMsg( "Values of LatLongBoundingBox are consistent with WGS84 long/lat bounds, so as the CRS is projected, assume they are indeed in WGS84 and not in the CRS units" ); featureType.bboxSRSIsWGS84 = true; } } } } else { // WFS 1.1 way QDomElement WGS84BoundingBox = featureTypeElem.firstChildElement( QStringLiteral( "WGS84BoundingBox" ) ); if ( !WGS84BoundingBox.isNull() ) { QDomElement lowerCorner = WGS84BoundingBox.firstChildElement( QStringLiteral( "LowerCorner" ) ); QDomElement upperCorner = WGS84BoundingBox.firstChildElement( QStringLiteral( "UpperCorner" ) ); if ( !lowerCorner.isNull() && !upperCorner.isNull() ) { QStringList lowerCornerList = lowerCorner.text().split( QStringLiteral( " " ), QString::SkipEmptyParts ); QStringList upperCornerList = upperCorner.text().split( QStringLiteral( " " ), QString::SkipEmptyParts ); if ( lowerCornerList.size() == 2 && upperCornerList.size() == 2 ) { featureType.bbox = QgsRectangle( lowerCornerList[0].toDouble(), lowerCornerList[1].toDouble(), upperCornerList[0].toDouble(), upperCornerList[1].toDouble() ); featureType.bboxSRSIsWGS84 = true; } } } } // Parse Operations specific to the type name parseSupportedOperations( featureTypeElem.firstChildElement( QStringLiteral( "Operations" ) ), featureType.insertCap, featureType.updateCap, featureType.deleteCap ); featureType.insertCap |= insertCap; featureType.updateCap |= updateCap; featureType.deleteCap |= deleteCap; mCaps.featureTypes.push_back( featureType ); } Q_FOREACH ( const FeatureType &f, mCaps.featureTypes ) { mCaps.setAllTypenames.insert( f.name ); QString unprefixed( QgsWFSUtils::removeNamespacePrefix( f.name ) ); if ( !mCaps.setAmbiguousUnprefixedTypename.contains( unprefixed ) ) { if ( mCaps.mapUnprefixedTypenameToPrefixedTypename.contains( unprefixed ) ) { mCaps.setAmbiguousUnprefixedTypename.insert( unprefixed ); mCaps.mapUnprefixedTypenameToPrefixedTypename.remove( unprefixed ); } else { mCaps.mapUnprefixedTypenameToPrefixedTypename[unprefixed] = f.name; } } } //go to <Filter_Capabilities> QDomElement filterCapabilitiesElem = doc.firstChildElement( QStringLiteral( "Filter_Capabilities" ) ); if ( !filterCapabilitiesElem.isNull() ) parseFilterCapabilities( filterCapabilitiesElem ); // Hard-coded functions Function f_ST_GeometryFromText( QStringLiteral( "ST_GeometryFromText" ), 1, 2 ); f_ST_GeometryFromText.returnType = QStringLiteral( "gml:AbstractGeometryType" ); f_ST_GeometryFromText.argumentList << Argument( QStringLiteral( "wkt" ), QStringLiteral( "xs:string" ) ); f_ST_GeometryFromText.argumentList << Argument( QStringLiteral( "srsname" ), QStringLiteral( "xs:string" ) ); mCaps.functionList << f_ST_GeometryFromText; Function f_ST_GeomFromGML( QStringLiteral( "ST_GeomFromGML" ), 1 ); f_ST_GeomFromGML.returnType = QStringLiteral( "gml:AbstractGeometryType" ); f_ST_GeomFromGML.argumentList << Argument( QStringLiteral( "gml" ), QStringLiteral( "xs:string" ) ); mCaps.functionList << f_ST_GeomFromGML; Function f_ST_MakeEnvelope( QStringLiteral( "ST_MakeEnvelope" ), 4, 5 ); f_ST_MakeEnvelope.returnType = QStringLiteral( "gml:AbstractGeometryType" ); f_ST_MakeEnvelope.argumentList << Argument( QStringLiteral( "minx" ), QStringLiteral( "xs:double" ) ); f_ST_MakeEnvelope.argumentList << Argument( QStringLiteral( "miny" ), QStringLiteral( "xs:double" ) ); f_ST_MakeEnvelope.argumentList << Argument( QStringLiteral( "maxx" ), QStringLiteral( "xs:double" ) ); f_ST_MakeEnvelope.argumentList << Argument( QStringLiteral( "maxy" ), QStringLiteral( "xs:double" ) ); f_ST_MakeEnvelope.argumentList << Argument( QStringLiteral( "srsname" ), QStringLiteral( "xs:string" ) ); mCaps.functionList << f_ST_MakeEnvelope; emit gotCapabilities(); }
void UserGroupFetcher::handleListXml(QDomNode list) { // QMessageBox::information (0,"assdf",list->toString()); QDomNodeList nodes = list.childNodes(); Group *g = 0; bool creatingGroup = false; if (myGroup&&state) { creatingGroup=true; g=myGroup; } else g = new Group(box); g->twitterList=true; g->user=user; g->pass=pass; for(unsigned int x=0;x<nodes.length();x++) { QDomNode node = nodes.at(x); if (node.nodeName()=="id") { QString id = node.firstChild().nodeValue(); if (box->getGroupById(id)) { Group *oldg = box->getGroupById(id); oldg->twitterList=true; oldg->name=g->name; oldg->full_name=g->full_name; oldg->description=g->description; oldg->member_count=g->member_count; oldg->privateList=g->privateList; oldg->slug=g->slug; oldg->uri=g->uri; oldg->subscriber_count=g->subscriber_count; g=oldg; } g->id=id; } else if (node.nodeName()=="name") { g->name=node.firstChild().nodeValue(); } else if (node.nodeName()=="full_name") { g->full_name=node.firstChild().nodeValue(); } else if (node.nodeName()=="slug") { g->slug=node.firstChild().nodeValue(); } else if (node.nodeName()=="description") { g->description=node.firstChild().nodeValue(); } else if (node.nodeName()=="subscriber_count") { g->subscriber_count=QVariant(node.firstChild().nodeValue()).toInt(); } else if (node.nodeName()=="member_count") { g->member_count=QVariant(node.firstChild().nodeValue()).toInt(); } else if (node.nodeName()=="uri") { g->uri=node.firstChild().nodeValue(); } else if (node.nodeName()=="mode") { g->privateList=(node.firstChild().nodeValue()!="public"); } else if (node.nodeName()=="user") { TweetUser*u = handleUserXml(node,false,0); if (u) g->ownerScreenName=u->screen_name; } } if (!creatingGroup) { /* UserGroupFetcher *newFetcher = new UserGroupFetcher(); newFetcher->setGroup(g); newFetcher->setUser(user); newFetcher->setPass(pass); box->addFetcher(newFetcher,true); newFetcher->activateTimeout(15,0); */ g->updateMembers(); emit haveGroup(g); } else { //QMessageBox::information(0,"",QString::number(myGroup->groupmembers.count())); QStringList members = myGroup->groupmembers; myGroup->groupmembers.clear(); myGroup->updateGroupMembers(members); deleted=true; emit fetcherExpired(this);// my work here is done. ;) } }
QgsFeatureRequest parseFilterElement( const QString &typeName, QDomElement &filterElem, const QgsProject *project ) { QgsFeatureRequest request; QDomNodeList fidNodes = filterElem.elementsByTagName( QStringLiteral( "FeatureId" ) ); QDomNodeList goidNodes = filterElem.elementsByTagName( QStringLiteral( "GmlObjectId" ) ); if ( !fidNodes.isEmpty() ) { QgsFeatureIds fids; QDomElement fidElem; for ( int f = 0; f < fidNodes.size(); f++ ) { fidElem = fidNodes.at( f ).toElement(); if ( !fidElem.hasAttribute( QStringLiteral( "fid" ) ) ) { throw QgsRequestNotWellFormedException( "FeatureId element without fid attribute" ); } QString fid = fidElem.attribute( QStringLiteral( "fid" ) ); if ( fid.contains( QLatin1String( "." ) ) ) { if ( fid.section( QStringLiteral( "." ), 0, 0 ) != typeName ) continue; fid = fid.section( QStringLiteral( "." ), 1, 1 ); } fids.insert( fid.toInt() ); } if ( !fids.isEmpty() ) { request.setFilterFids( fids ); } else { throw QgsRequestNotWellFormedException( QStringLiteral( "No FeatureId element correctly parse against typeName '%1'" ).arg( typeName ) ); } request.setFlags( QgsFeatureRequest::NoFlags ); return request; } else if ( !goidNodes.isEmpty() ) { QgsFeatureIds fids; QDomElement goidElem; for ( int f = 0; f < goidNodes.size(); f++ ) { goidElem = goidNodes.at( f ).toElement(); if ( !goidElem.hasAttribute( QStringLiteral( "id" ) ) && !goidElem.hasAttribute( QStringLiteral( "gml:id" ) ) ) { throw QgsRequestNotWellFormedException( "GmlObjectId element without gml:id attribute" ); } QString fid = goidElem.attribute( QStringLiteral( "id" ) ); if ( fid.isEmpty() ) fid = goidElem.attribute( QStringLiteral( "gml:id" ) ); if ( fid.contains( QLatin1String( "." ) ) ) { if ( fid.section( QStringLiteral( "." ), 0, 0 ) != typeName ) continue; fid = fid.section( QStringLiteral( "." ), 1, 1 ); } fids.insert( fid.toInt() ); } if ( !fids.isEmpty() ) { request.setFilterFids( fids ); } else { throw QgsRequestNotWellFormedException( QStringLiteral( "No GmlObjectId element correctly parse against typeName '%1'" ).arg( typeName ) ); } request.setFlags( QgsFeatureRequest::NoFlags ); return request; } else if ( filterElem.firstChildElement().tagName() == QLatin1String( "BBOX" ) ) { QDomElement bboxElem = filterElem.firstChildElement(); QDomElement childElem = bboxElem.firstChildElement(); while ( !childElem.isNull() ) { if ( childElem.tagName() == QLatin1String( "Box" ) ) { request.setFilterRect( QgsOgcUtils::rectangleFromGMLBox( childElem ) ); } else if ( childElem.tagName() != QLatin1String( "PropertyName" ) ) { QgsGeometry geom = QgsOgcUtils::geometryFromGML( childElem ); request.setFilterRect( geom.boundingBox() ); } childElem = childElem.nextSiblingElement(); } request.setFlags( QgsFeatureRequest::ExactIntersect | QgsFeatureRequest::NoFlags ); return request; } // Apply BBOX through filterRect even inside an And to use spatial index else if ( filterElem.firstChildElement().tagName() == QLatin1String( "And" ) && !filterElem.firstChildElement().firstChildElement( QLatin1String( "BBOX" ) ).isNull() ) { QDomElement childElem = filterElem.firstChildElement().firstChildElement(); while ( !childElem.isNull() ) { QDomElement childFilterElement = filterElem.ownerDocument().createElement( QLatin1String( "Filter" ) ); childFilterElement.appendChild( childElem.cloneNode( true ) ); QgsFeatureRequest childRequest = parseFilterElement( typeName, childFilterElement ); if ( childElem.tagName() == QLatin1String( "BBOX" ) ) { if ( request.filterRect().isEmpty() ) { request.setFilterRect( childRequest.filterRect() ); } else { request.setFilterRect( request.filterRect().intersect( childRequest.filterRect() ) ); } } else { if ( !request.filterExpression() ) { request.setFilterExpression( childRequest.filterExpression()->expression() ); } else { QgsExpressionNode *opLeft = request.filterExpression()->rootNode()->clone(); QgsExpressionNode *opRight = childRequest.filterExpression()->rootNode()->clone(); std::unique_ptr<QgsExpressionNodeBinaryOperator> node = qgis::make_unique<QgsExpressionNodeBinaryOperator>( QgsExpressionNodeBinaryOperator::boAnd, opLeft, opRight ); QgsExpression expr( node->dump() ); request.setFilterExpression( expr ); } } childElem = childElem.nextSiblingElement(); } request.setFlags( QgsFeatureRequest::ExactIntersect | QgsFeatureRequest::NoFlags ); return request; } else { QgsVectorLayer *layer = nullptr; if ( project != nullptr ) { layer = layerByTypeName( project, typeName ); } std::shared_ptr<QgsExpression> filter( QgsOgcUtils::expressionFromOgcFilter( filterElem, layer ) ); if ( filter ) { if ( filter->hasParserError() ) { throw QgsRequestNotWellFormedException( filter->parserErrorString() ); } if ( filter->needsGeometry() ) { request.setFlags( QgsFeatureRequest::NoFlags ); } request.setFilterExpression( filter->expression() ); return request; } } return request; }