int XmlGspInterface::readFile(const QString &fileName) { QFile* file = new QFile(fileName); QFileInfo fi(fileName); QString path = (fi.path().length() > 3) ? QString(fi.path() + "/") : fi.path(); QFileInfo si(QString::fromStdString(_schemaName)); QString schemaPath(si.absolutePath() + "/"); if (!file->open(QIODevice::ReadOnly | QIODevice::Text)) { std::cout << "XmlGspInterface::readFile() - Can't open xml-file " << fileName.toStdString() << "." << "\n"; delete file; return 0; } if (!checkHash(fileName)) { delete file; return 0; } QDomDocument doc("OGS-PROJECT-DOM"); doc.setContent(file); QDomElement docElement = doc.documentElement(); //OpenGeoSysProject if (docElement.nodeName().compare("OpenGeoSysProject")) { std::cout << "XmlGspInterface::readFile() - Unexpected XML root." << "\n"; delete file; return 0; } QDomNodeList fileList = docElement.childNodes(); for(int i = 0; i < fileList.count(); i++) { const QString file_node(fileList.at(i).nodeName()); if (file_node.compare("geo") == 0) { XmlGmlInterface gml(_project, schemaPath.toStdString() + "OpenGeoSysGLI.xsd"); const QDomNodeList childList = fileList.at(i).childNodes(); for(int j = 0; j < childList.count(); j++) { const QDomNode child_node (childList.at(j)); if (child_node.nodeName().compare("file") == 0) { std::cout << "path: " << path.toStdString() << "#" << "\n"; std::cout << "file name: " << (child_node.toElement().text()).toStdString() << "#" << "\n"; gml.readFile(QString(path + child_node.toElement().text())); } } } else if (file_node.compare("stn") == 0) { XmlStnInterface stn(_project, schemaPath.toStdString() + "OpenGeoSysSTN.xsd"); const QDomNodeList childList = fileList.at(i).childNodes(); for(int j = 0; j < childList.count(); j++) if (childList.at(j).nodeName().compare("file") == 0) stn.readFile(QString(path + childList.at(j).toElement().text())); } else if (file_node.compare("msh") == 0) { const std::string msh_name = path.toStdString() + fileList.at(i).toElement().text().toStdString(); FileIO::OGSMeshIO meshIO; MeshLib::CFEMesh* msh = meshIO.loadMeshFromFile(msh_name); QFileInfo fi(QString::fromStdString(msh_name)); std::string name = fi.fileName().toStdString(); _project->addMesh(msh, name); //GridAdapter msh(fileList.at(i).toElement().text().toStdString()); // TODO gridadapter to mesh-models } } return 1; }
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 ); }
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(); }
/** * 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; }
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; }
bool QgsComposerShape::readXml( const QDomElement& itemElem, const QDomDocument& doc ) { mShape = QgsComposerShape::Shape( itemElem.attribute( "shapeType", "0" ).toInt() ); mCornerRadius = itemElem.attribute( "cornerRadius", "0" ).toDouble(); //restore general composer item properties QDomNodeList composerItemList = itemElem.elementsByTagName( "ComposerItem" ); if ( !composerItemList.isEmpty() ) { QDomElement composerItemElem = composerItemList.at( 0 ).toElement(); //rotation if ( !qgsDoubleNear( composerItemElem.attribute( "rotation", "0" ).toDouble(), 0.0 ) ) { //check for old (pre 2.1) rotation attribute setItemRotation( composerItemElem.attribute( "rotation", "0" ).toDouble() ); } _readXml( composerItemElem, doc ); } QDomElement shapeStyleSymbolElem = itemElem.firstChildElement( "symbol" ); if ( !shapeStyleSymbolElem.isNull() ) { delete mShapeStyleSymbol; mShapeStyleSymbol = QgsSymbolLayerUtils::loadSymbol<QgsFillSymbol>( shapeStyleSymbolElem ); } else { //upgrade project file from 2.0 to use symbol styling delete mShapeStyleSymbol; QgsStringMap properties; properties.insert( "color", QgsSymbolLayerUtils::encodeColor( brush().color() ) ); if ( hasBackground() ) { properties.insert( "style", "solid" ); } else { properties.insert( "style", "no" ); } if ( hasFrame() ) { properties.insert( "style_border", "solid" ); } else { properties.insert( "style_border", "no" ); } properties.insert( "color_border", QgsSymbolLayerUtils::encodeColor( pen().color() ) ); properties.insert( "width_border", QString::number( pen().widthF() ) ); //for pre 2.0 projects, shape color and outline were specified in a different element... QDomNodeList outlineColorList = itemElem.elementsByTagName( "OutlineColor" ); if ( !outlineColorList.isEmpty() ) { QDomElement frameColorElem = outlineColorList.at( 0 ).toElement(); bool redOk, greenOk, blueOk, alphaOk, widthOk; int penRed, penGreen, penBlue, penAlpha; double penWidth; penWidth = itemElem.attribute( "outlineWidth" ).toDouble( &widthOk ); penRed = frameColorElem.attribute( "red" ).toDouble( &redOk ); penGreen = frameColorElem.attribute( "green" ).toDouble( &greenOk ); penBlue = frameColorElem.attribute( "blue" ).toDouble( &blueOk ); penAlpha = frameColorElem.attribute( "alpha" ).toDouble( &alphaOk ); if ( redOk && greenOk && blueOk && alphaOk && widthOk ) { properties.insert( "color_border", QgsSymbolLayerUtils::encodeColor( QColor( penRed, penGreen, penBlue, penAlpha ) ) ); properties.insert( "width_border", QString::number( penWidth ) ); } } QDomNodeList fillColorList = itemElem.elementsByTagName( "FillColor" ); if ( !fillColorList.isEmpty() ) { QDomElement fillColorElem = fillColorList.at( 0 ).toElement(); bool redOk, greenOk, blueOk, alphaOk; int fillRed, fillGreen, fillBlue, fillAlpha; fillRed = fillColorElem.attribute( "red" ).toDouble( &redOk ); fillGreen = fillColorElem.attribute( "green" ).toDouble( &greenOk ); fillBlue = fillColorElem.attribute( "blue" ).toDouble( &blueOk ); fillAlpha = fillColorElem.attribute( "alpha" ).toDouble( &alphaOk ); if ( redOk && greenOk && blueOk && alphaOk ) { properties.insert( "color", QgsSymbolLayerUtils::encodeColor( QColor( fillRed, fillGreen, fillBlue, fillAlpha ) ) ); properties.insert( "style", "solid" ); } } if ( itemElem.hasAttribute( "transparentFill" ) ) { //old style (pre 2.0) of specifying that shapes had no fill bool hasOldTransparentFill = itemElem.attribute( "transparentFill", "0" ).toInt(); if ( hasOldTransparentFill ) { properties.insert( "style", "no" ); } } mShapeStyleSymbol = QgsFillSymbol::createSimple( properties ); } emit itemChanged(); return true; }
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; }
void QgsProjectFileTransform::transform1800to1900() { if ( mDom.isNull() ) { return; } QDomNodeList layerItemList = mDom.elementsByTagName( "rasterproperties" ); for ( int i = 0; i < layerItemList.size(); ++i ) { QDomElement rasterPropertiesElem = layerItemList.at( i ).toElement(); QDomNode layerNode = rasterPropertiesElem.parentNode(); QDomElement dataSourceElem = layerNode.firstChildElement( "datasource" ); QDomElement layerNameElem = layerNode.firstChildElement( "layername" ); QgsRasterLayer rasterLayer; // TODO: We have to use more data from project file to read the layer it correctly, // OTOH, we should not read it until it was converted rasterLayer.readXML( layerNode ); convertRasterProperties( mDom, layerNode, rasterPropertiesElem, &rasterLayer ); } //composer: replace mGridAnnotationPosition with mLeftGridAnnotationPosition & co. // and mGridAnnotationDirection with mLeftGridAnnotationDirection & co. QDomNodeList composerMapList = mDom.elementsByTagName( "ComposerMap" ); for ( int i = 0; i < composerMapList.size(); ++i ) { QDomNodeList gridList = composerMapList.at( i ).toElement().elementsByTagName( "Grid" ); for ( int j = 0; j < gridList.size(); ++j ) { QDomNodeList annotationList = gridList.at( j ).toElement().elementsByTagName( "Annotation" ); for ( int k = 0; k < annotationList.size(); ++k ) { QDomElement annotationElem = annotationList.at( k ).toElement(); //position if ( annotationElem.hasAttribute( "position" ) ) { int pos = annotationElem.attribute( "position" ).toInt(); annotationElem.setAttribute( "leftPosition", pos ); annotationElem.setAttribute( "rightPosition", pos ); annotationElem.setAttribute( "topPosition", pos ); annotationElem.setAttribute( "bottomPosition", pos ); annotationElem.removeAttribute( "position" ); } //direction if ( annotationElem.hasAttribute( "direction" ) ) { int dir = annotationElem.attribute( "direction" ).toInt(); if ( dir == 2 ) { annotationElem.setAttribute( "leftDirection", 0 ); annotationElem.setAttribute( "rightDirection", 0 ); annotationElem.setAttribute( "topDirection", 1 ); annotationElem.setAttribute( "bottomDirection", 1 ); } else if ( dir == 3 ) { annotationElem.setAttribute( "leftDirection", 1 ); annotationElem.setAttribute( "rightDirection", 1 ); annotationElem.setAttribute( "topDirection", 0 ); annotationElem.setAttribute( "bottomDirection", 0 ); } else { annotationElem.setAttribute( "leftDirection", dir ); annotationElem.setAttribute( "rightDirection", dir ); annotationElem.setAttribute( "topDirection", dir ); annotationElem.setAttribute( "bottomDirection", dir ); } annotationElem.removeAttribute( "direction" ); } } } } QgsDebugMsg( mDom.toString() ); }
void QgsProjectFileTransform::convertRasterProperties( QDomDocument& doc, QDomNode& parentNode, QDomElement& rasterPropertiesElem, QgsRasterLayer* rlayer ) { QDomElement rasterRendererElem = doc.createElement( "rasterrenderer" ); //convert general properties //invert color rasterRendererElem.setAttribute( "invertColor", "0" ); QDomElement invertColorElem = rasterPropertiesElem.firstChildElement( "mInvertColor" ); if ( !invertColorElem.isNull() ) { if ( invertColorElem.text() == "true" ) { rasterRendererElem.setAttribute( "invertColor", "1" ); } } //opacity rasterRendererElem.setAttribute( "opacity", "1" ); QDomElement transparencyElem = parentNode.firstChildElement( "transparencyLevelInt" ); if ( !transparencyElem.isNull() ) { double transparency = transparencyElem.text().toInt(); rasterRendererElem.setAttribute( "opacity", QString::number( transparency / 255.0 ) ); } //alphaBand was not saved until now (bug) rasterRendererElem.setAttribute( "alphaBand", -1 ); //gray band is used for several renderers int grayBand = rasterBandNumber( rasterPropertiesElem, "mGrayBandName", rlayer ); //convert renderer specific properties QString drawingStyle = rasterPropertiesElem.firstChildElement( "mDrawingStyle" ).text(); if ( drawingStyle == "SingleBandGray" ) { rasterRendererElem.setAttribute( "type", "singlebandgray" ); rasterRendererElem.setAttribute( "grayBand", grayBand ); transformContrastEnhancement( doc, rasterPropertiesElem, rasterRendererElem ); } else if ( drawingStyle == "SingleBandPseudoColor" ) { rasterRendererElem.setAttribute( "type", "singlebandpseudocolor" ); rasterRendererElem.setAttribute( "band", grayBand ); QDomElement newRasterShaderElem = doc.createElement( "rastershader" ); QDomElement newColorRampShaderElem = doc.createElement( "colorrampshader" ); newRasterShaderElem.appendChild( newColorRampShaderElem ); rasterRendererElem.appendChild( newRasterShaderElem ); //switch depending on mColorShadingAlgorithm QString colorShadingAlgorithm = rasterPropertiesElem.firstChildElement( "mColorShadingAlgorithm" ).text(); if ( colorShadingAlgorithm == "PseudoColorShader" || colorShadingAlgorithm == "FreakOutShader" ) { newColorRampShaderElem.setAttribute( "colorRampType", "INTERPOLATED" ); //get minmax from rasterlayer QgsRasterBandStats rasterBandStats = rlayer->bandStatistics( grayBand ); double minValue = rasterBandStats.minimumValue; double maxValue = rasterBandStats.maximumValue; double breakSize = ( maxValue - minValue ) / 3; QStringList colorList; if ( colorShadingAlgorithm == "FreakOutShader" ) { colorList << "#ff00ff" << "#00ffff" << "#ff0000" << "#00ff00"; } else //pseudocolor { colorList << "#0000ff" << "#00ffff" << "#ffff00" << "#ff0000"; } QStringList::const_iterator colorIt = colorList.constBegin(); double boundValue = minValue; for ( ; colorIt != colorList.constEnd(); ++colorIt ) { QDomElement newItemElem = doc.createElement( "item" ); newItemElem.setAttribute( "value", QString::number( boundValue ) ); newItemElem.setAttribute( "label", QString::number( boundValue ) ); newItemElem.setAttribute( "color", *colorIt ); newColorRampShaderElem.appendChild( newItemElem ); boundValue += breakSize; } } else if ( colorShadingAlgorithm == "ColorRampShader" ) { QDomElement customColorRampElem = rasterPropertiesElem.firstChildElement( "customColorRamp" ); QString type = customColorRampElem.firstChildElement( "colorRampType" ).text(); newColorRampShaderElem.setAttribute( "colorRampType", type ); QDomNodeList colorNodeList = customColorRampElem.elementsByTagName( "colorRampEntry" ); QString value, label; QColor newColor; int red, green, blue; QDomElement currentItemElem; for ( int i = 0; i < colorNodeList.size(); ++i ) { currentItemElem = colorNodeList.at( i ).toElement(); value = currentItemElem.attribute( "value" ); label = currentItemElem.attribute( "label" ); red = currentItemElem.attribute( "red" ).toInt(); green = currentItemElem.attribute( "green" ).toInt(); blue = currentItemElem.attribute( "blue" ).toInt(); newColor = QColor( red, green, blue ); QDomElement newItemElem = doc.createElement( "item" ); newItemElem.setAttribute( "value", value ); newItemElem.setAttribute( "label", label ); newItemElem.setAttribute( "color", newColor.name() ); newColorRampShaderElem.appendChild( newItemElem ); } } } else if ( drawingStyle == "PalettedColor" ) { rasterRendererElem.setAttribute( "type", "paletted" ); rasterRendererElem.setAttribute( "band", grayBand ); QDomElement customColorRampElem = rasterPropertiesElem.firstChildElement( "customColorRamp" ); QDomNodeList colorRampEntryList = customColorRampElem.elementsByTagName( "colorRampEntry" ); QDomElement newColorPaletteElem = doc.createElement( "colorPalette" ); int red = 0; int green = 0; int blue = 0; int value = 0; QDomElement colorRampEntryElem; for ( int i = 0; i < colorRampEntryList.size(); ++i ) { colorRampEntryElem = colorRampEntryList.at( i ).toElement(); QDomElement newPaletteElem = doc.createElement( "paletteEntry" ); value = ( int )( colorRampEntryElem.attribute( "value" ).toDouble() ); newPaletteElem.setAttribute( "value", value ); red = colorRampEntryElem.attribute( "red" ).toInt(); green = colorRampEntryElem.attribute( "green" ).toInt(); blue = colorRampEntryElem.attribute( "blue" ).toInt(); newPaletteElem.setAttribute( "color", QColor( red, green, blue ).name() ); newColorPaletteElem.appendChild( newPaletteElem ); } rasterRendererElem.appendChild( newColorPaletteElem ); } else if ( drawingStyle == "MultiBandColor" ) { rasterRendererElem.setAttribute( "type", "multibandcolor" ); //red band, green band, blue band int redBand = rasterBandNumber( rasterPropertiesElem, "mRedBandName", rlayer ); int greenBand = rasterBandNumber( rasterPropertiesElem, "mGreenBandName", rlayer ); int blueBand = rasterBandNumber( rasterPropertiesElem, "mBlueBandName", rlayer ); rasterRendererElem.setAttribute( "redBand", redBand ); rasterRendererElem.setAttribute( "greenBand", greenBand ); rasterRendererElem.setAttribute( "blueBand", blueBand ); transformContrastEnhancement( doc, rasterPropertiesElem, rasterRendererElem ); } else { return; } //replace rasterproperties element with rasterrenderer element if ( !parentNode.isNull() ) { parentNode.replaceChild( rasterRendererElem, rasterPropertiesElem ); } }
bool SM_ModelBackend::loadFromDomDoc (QDomDocument &doc) { QMessageBox msgBox; // let us check if we have a valid subnetmap QDomElement docElem = doc.documentElement(); if (docElem.nodeName()=="SubnetMap") { if (docElem.hasAttribute("fileformat")) { if ((docElem.attribute("fileformat")).toInt()!=2) { msgBox.setText("Warning: the SubnetMap you were trying to load has the wrong format. This Version of SubnetMapper can only read format version 2."); msgBox.setIcon(QMessageBox::Warning); msgBox.setDetailedText("The fileformat attribute of the SubnetMap node has a version number that is not equal to 2. Update SubnetMapper to the most recent version to read this file."); msgBox.exec(); return false; }; } } else return false; // now we know its one of ours. // we can clear all data now, but we do emit only the message to notify // everyone about the emptied model. The change-signals wil be emitted // at the end of this function. This makes sure that no widget will work // without a valid reason at this point. clearData(true); emit modelEmptied(); QDomNodeList subnetNodes = docElem.elementsByTagName("subnet"); // qDebug("SM_DataModel::loadFromDomDoc(): found %u subnet nodes in the document.",subnetNodes.count()); for (int i=0;i<subnetNodes.count();i++){ QDomElement currentSubnetNode=subnetNodes.at(i).toElement(); QDomElement addressNode = currentSubnetNode.firstChildElement("address"); QDomElement netmaskNode = currentSubnetNode.firstChildElement("netmask"); QDomElement colorNode = currentSubnetNode.firstChildElement("color"); QDomElement descriptionNode = currentSubnetNode.firstChildElement("description"); QDomElement notesNode = currentSubnetNode.firstChildElement("notes"); QDomElement identifierNode = currentSubnetNode.firstChildElement("identifier"); if (currentSubnetNode.hasAttribute("ipversion")) { if (currentSubnetNode.attribute("ipversion")=="IPv4") { Subnet_v4 *newSubnet = new Subnet_v4(this); QString mom=netmaskNode.text(); newSubnet->setNM(mom); mom=addressNode.text(); newSubnet->setIP(mom); mom=identifierNode.text(); newSubnet->setIdentifier(mom); mom=descriptionNode.text(); newSubnet->setDescription(mom); mom=notesNode.text(); newSubnet->setNotes(mom); QColor momColor= QColor(colorNode.text()); newSubnet->setColor(momColor); SubnetList.append(newSubnet); Subnet4List.append(newSubnet); } else if (currentSubnetNode.attribute("ipversion")=="IPv6") { Subnet_v6 *newSubnet = new Subnet_v6(this); QString mom=netmaskNode.text(); //qDebug("SM_ModelBackend::loadFromDomDoc(): parsed IPv6 Netmask: %s",qPrintable(mom.toUtf8())); newSubnet->setNM(mom); mom=addressNode.text(); //qDebug("SM_ModelBackend::loadFromDomDoc(): parsed IPv6 IP: %s",qPrintable(mom.toUtf8())); newSubnet->setIP(mom); mom=identifierNode.text(); newSubnet->setIdentifier(mom); mom=descriptionNode.text(); newSubnet->setDescription(mom); mom=notesNode.text(); newSubnet->setNotes(mom); QColor momColor= QColor(colorNode.text()); newSubnet->setColor(momColor); SubnetList.append(newSubnet); Subnet6List.append(newSubnet); } else { msgBox.setText("Warning: Subnet "+QString::number(i)+" was invalid! Subnet will be skipped..."); msgBox.setIcon(QMessageBox::Warning); msgBox.setDetailedText("The Subnet was not clearly specified, the ipversion attribute is invalid."+ identifierNode.text()+"\n"+ addressNode.text()+"\n"+ netmaskNode.text()+"\n"+ descriptionNode.text()+"\n"+ notesNode.text()+"\n"+ colorNode.text()+"\n" ); msgBox.exec(); } } else { msgBox.setText("Warning: Subnet "+QString::number(i)+" was invalid! Subnet will be skipped..."); msgBox.setIcon(QMessageBox::Warning); msgBox.setDetailedText("The Subnet was not clearly specified, the ipversion attribute is missing."+ identifierNode.text()+"\n"+ addressNode.text()+"\n"+ netmaskNode.text()+"\n"+ descriptionNode.text()+"\n"+ notesNode.text()+"\n"+ colorNode.text()+"\n" ); msgBox.exec(); } } sortData(); emit data4Changed(); emit data6Changed(); emit dataChanged(); // uncomment for debugging purposes, prints all objects in model dumpAllSubnets(); return true; }
void QgsProjectFileTransform::transform0110to1000() { if ( ! mDom.isNull() ) { QDomNodeList layerList = mDom.elementsByTagName( "maplayer" ); for ( int i = 0; i < layerList.size(); ++i ) { QDomElement layerElem = layerList.at( i ).toElement(); QString typeString = layerElem.attribute( "type" ); if ( typeString != "vector" ) { continue; } //datasource QDomNode dataSourceNode = layerElem.namedItem( "datasource" ); if ( dataSourceNode.isNull() ) { return; } QString dataSource = dataSourceNode.toElement().text(); //provider key QDomNode providerNode = layerElem.namedItem( "provider" ); if ( providerNode.isNull() ) { return; } QString providerKey = providerNode.toElement().text(); //create the layer to get the provider for int->fieldName conversion QgsVectorLayer* theLayer = new QgsVectorLayer( dataSource, "", providerKey, false ); if ( !theLayer->isValid() ) { delete theLayer; return; } QgsVectorDataProvider* theProvider = theLayer->dataProvider(); if ( !theProvider ) { return; } QgsFieldMap theFieldMap = theProvider->fields(); //read classificationfield QDomNodeList classificationFieldList = layerElem.elementsByTagName( "classificationfield" ); for ( int j = 0; j < classificationFieldList.size(); ++j ) { QDomElement classificationFieldElem = classificationFieldList.at( j ).toElement(); int fieldNumber = classificationFieldElem.text().toInt(); QgsFieldMap::const_iterator field_it = theFieldMap.find( fieldNumber ); if ( field_it != theFieldMap.constEnd() ) { QDomText fieldName = mDom.createTextNode( field_it.value().name() ); QDomNode nameNode = classificationFieldElem.firstChild(); classificationFieldElem.replaceChild( fieldName, nameNode ); } } } } }
void TagColorEditor::askGradientChoice() { QString homePath = QDir::homePath(); QFileInfo sfi(homePath, ".drishtigradients.xml"); QString stopsflnm = sfi.absoluteFilePath(); if (!sfi.exists()) copyGradientFile(stopsflnm); QDomDocument document; QFile f(stopsflnm); if (f.open(QIODevice::ReadOnly)) { document.setContent(&f); f.close(); } QStringList glist; QDomElement main = document.documentElement(); QDomNodeList dlist = main.childNodes(); for(int i=0; i<dlist.count(); i++) { if (dlist.at(i).nodeName() == "gradient") { QDomNodeList cnode = dlist.at(i).childNodes(); for(int j=0; j<cnode.count(); j++) { QDomElement dnode = cnode.at(j).toElement(); if (dnode.nodeName() == "name") glist << dnode.text(); } } } bool ok; QString gstr = QInputDialog::getItem(0, "Color Gradient", "Color Gradient", glist, 0, false, &ok); if (!ok) return; int cno = -1; for(int i=0; i<dlist.count(); i++) { if (dlist.at(i).nodeName() == "gradient") { QDomNodeList cnode = dlist.at(i).childNodes(); for(int j=0; j<cnode.count(); j++) { QDomElement dnode = cnode.at(j).toElement(); if (dnode.tagName() == "name" && dnode.text() == gstr) { cno = i; break; } } } } if (cno < 0) return; QGradientStops stops; QDomNodeList cnode = dlist.at(cno).childNodes(); for(int j=0; j<cnode.count(); j++) { QDomElement de = cnode.at(j).toElement(); if (de.tagName() == "gradientstops") { QString str = de.text(); QStringList strlist = str.split(" ", QString::SkipEmptyParts); for(int j=0; j<strlist.count()/5; j++) { float pos, r,g,b,a; pos = strlist[5*j].toFloat(); r = strlist[5*j+1].toInt(); g = strlist[5*j+2].toInt(); b = strlist[5*j+3].toInt(); a = strlist[5*j+4].toInt(); stops << QGradientStop(pos, QColor(r,g,b,a)); } } } int mapSize = QInputDialog::getInt(0, "Number of Colors", "Number of Colors", 50, 2, 255, 1, &ok); if (!ok) mapSize = 50; QGradientStops gstops; gstops = StaticFunctions::resampleGradientStops(stops, mapSize); uchar *colors = Global::tagColors(); for(int i=0; i<gstops.size(); i++) { float pos = gstops[i].first; QColor color = gstops[i].second; int r = color.red(); int g = color.green(); int b = color.blue(); colors[4*i+0] = r; colors[4*i+1] = g; colors[4*i+2] = b; } colors[0] = 0; colors[1] = 0; colors[2] = 0; colors[3] = 0; setColors(); }
bool QgsComposerItem::_readXML( const QDomElement& itemElem, const QDomDocument& doc ) { Q_UNUSED( doc ); if ( itemElem.isNull() ) { return false; } //rotation mRotation = itemElem.attribute( "rotation", "0" ).toDouble(); //uuid mUuid = itemElem.attribute( "uuid", QUuid::createUuid().toString() ); //id QString id = itemElem.attribute( "id", "" ); setId( id ); //frame QString frame = itemElem.attribute( "frame" ); if ( frame.compare( "true", Qt::CaseInsensitive ) == 0 ) { mFrame = true; } else { mFrame = false; } //frame QString background = itemElem.attribute( "background" ); if ( background.compare( "true", Qt::CaseInsensitive ) == 0 ) { mBackground = true; } else { mBackground = false; } //position lock for mouse moves/resizes QString positionLock = itemElem.attribute( "positionLock" ); if ( positionLock.compare( "true", Qt::CaseInsensitive ) == 0 ) { mItemPositionLocked = true; } else { mItemPositionLocked = false; } //position double x, y, width, height; bool xOk, yOk, widthOk, heightOk, positionModeOK; x = itemElem.attribute( "x" ).toDouble( &xOk ); y = itemElem.attribute( "y" ).toDouble( &yOk ); width = itemElem.attribute( "width" ).toDouble( &widthOk ); height = itemElem.attribute( "height" ).toDouble( &heightOk ); mLastUsedPositionMode = ( ItemPositionMode )itemElem.attribute( "positionMode" ).toInt( &positionModeOK ); if ( !positionModeOK ) { mLastUsedPositionMode = UpperLeft; } if ( !xOk || !yOk || !widthOk || !heightOk ) { return false; } mLastValidViewScaleFactor = itemElem.attribute( "lastValidViewScaleFactor", "-1" ).toDouble(); setSceneRect( QRectF( x, y, width, height ) ); setZValue( itemElem.attribute( "zValue" ).toDouble() ); //pen QDomNodeList frameColorList = itemElem.elementsByTagName( "FrameColor" ); if ( frameColorList.size() > 0 ) { QDomElement frameColorElem = frameColorList.at( 0 ).toElement(); bool redOk, greenOk, blueOk, alphaOk, widthOk; int penRed, penGreen, penBlue, penAlpha; double penWidth; penWidth = itemElem.attribute( "outlineWidth" ).toDouble( &widthOk ); penRed = frameColorElem.attribute( "red" ).toDouble( &redOk ); penGreen = frameColorElem.attribute( "green" ).toDouble( &greenOk ); penBlue = frameColorElem.attribute( "blue" ).toDouble( &blueOk ); penAlpha = frameColorElem.attribute( "alpha" ).toDouble( &alphaOk ); if ( redOk && greenOk && blueOk && alphaOk && widthOk ) { QPen framePen( QColor( penRed, penGreen, penBlue, penAlpha ) ); framePen.setWidthF( penWidth ); setPen( framePen ); } } //brush QDomNodeList bgColorList = itemElem.elementsByTagName( "BackgroundColor" ); if ( bgColorList.size() > 0 ) { QDomElement bgColorElem = bgColorList.at( 0 ).toElement(); bool redOk, greenOk, blueOk, alphaOk; int bgRed, bgGreen, bgBlue, bgAlpha; bgRed = bgColorElem.attribute( "red" ).toDouble( &redOk ); bgGreen = bgColorElem.attribute( "green" ).toDouble( &greenOk ); bgBlue = bgColorElem.attribute( "blue" ).toDouble( &blueOk ); bgAlpha = bgColorElem.attribute( "alpha" ).toDouble( &alphaOk ); if ( redOk && greenOk && blueOk && alphaOk ) { QColor brushColor( bgRed, bgGreen, bgBlue, bgAlpha ); setBrush( QBrush( brushColor ) ); } } //blend mode setBlendMode( QgsMapRenderer::getCompositionMode(( QgsMapRenderer::BlendMode ) itemElem.attribute( "blendMode", "0" ).toUInt() ) ); //transparency setTransparency( itemElem.attribute( "transparency" , "0" ).toInt() ); return true; }
/** * Loads the current config file (m_configFileName). */ void CreateSceFile::loadConfigFile(void) { if(!m_configFileName.isEmpty()) { setGuiElementsToDefault(); setTitle(m_configFileName); if(!m_configFileName.isEmpty()) { QFile file(m_configFileName); QDomDocument doc("SceConfiguration"); if (file.open(QFile::ReadOnly)) { file.close(); if (!doc.setContent(&file)) { if(!file.readAll().isEmpty()) { QMessageBox::critical(this, "parse error", "could not parse " + m_configFileName); m_configFileName = ""; setTitle(m_configFileName); emit configHasToBeSavedSignal(); } } else { QDomElement docElem = doc.documentElement(); ui->filesTableWidget->blockSignals(true); QDomNodeList nodeList = docElem.elementsByTagName("ScriptWindowState"); QDomNode nodeItem = nodeList.at(0); ui->withScriptWindowCheckBox->setChecked((nodeItem.attributes().namedItem("withScriptWindow").nodeValue() == "1")); ui->notMinimized->setChecked((nodeItem.attributes().namedItem("notMinimized").nodeValue() == "1")); ui->fileLineEdit->setText(MainWindow::convertToAbsolutePath(m_configFileName, nodeItem.attributes().namedItem("sceFileName").nodeValue())); QStringList versionList = nodeItem.attributes().namedItem("minScVersion").nodeValue().split("."); if(versionList.length() == 2) { ui->minScVersionMajor->setValue(versionList[0].toUInt()); ui->minScVersionMinor->setValue(versionList[1].toUInt()); } nodeList = docElem.elementsByTagName("File"); for (int i = 0; i < nodeList.size(); i++) { nodeItem = nodeList.at(i); QString subDirectory = nodeItem.attributes().namedItem("subDirectory").nodeValue(); QString type = (nodeItem.attributes().namedItem("type").nodeValue()); QString source = MainWindow::convertToAbsolutePath(m_configFileName, nodeItem.attributes().namedItem("source").nodeValue()); addTableRow(subDirectory, type, source); } nodeList = docElem.elementsByTagName("ScriptArgument"); for (int i = 0; i < nodeList.size(); i++) { nodeItem = nodeList.at(i); QString value = nodeItem.attributes().namedItem("value").nodeValue(); ui->argumentsListWidget->addItem(value); } ui->filesTableWidget->blockSignals(false); resizeTableColumnsSlot(); QStringList showStrList = m_configFileName.split("/"); statusBar()->showMessage(showStrList[showStrList.size() - 1] + " loaded", 5000); setMenuState(); } } } else { QMessageBox::critical(this, "could not open file", m_configFileName); m_configFileName = ""; setTitle(m_configFileName); emit configHasToBeSavedSignal(); } } }
void ScreenWidget::loadPressed() { QString fileName = QFileDialog::getOpenFileName(this, tr("Load Scene"), "",tr("DSS XML Scene File (*.xml);;All Files (*)")); if (fileName.isEmpty()) { return; } else { QDomDocument doc("loadedscene"); QFile file(fileName); if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) { return; } if (!doc.setContent(&file)) { file.close(); return; } file.close(); QDomElement scene = doc.documentElement(); qDebug()<<scene.text(); QDomNode field=scene.firstChildElement("field"); if (field.isElement()) { this->scene->addField(field.firstChildElement("width").text().toUInt(),field.firstChildElement("height").text().toUInt()); } QDomNode targetEntity = scene.firstChildElement("targetEntity"); if (targetEntity.isElement()) { TargetEntity* newTargetEntity = new TargetEntity(); Point2i targetPos(targetEntity.firstChildElement("x").text().toInt(),targetEntity.firstChildElement("y").text().toInt()); this->scene->setTargetEntity(newTargetEntity,targetPos); } QDomNode entities = scene.firstChildElement("entities"); if (entities.isElement()) { QDomNodeList entityList =entities.toElement().elementsByTagName("entity"); for(int i=0;i<entityList.count();i++) { QDomElement entity = entityList.at(i).toElement(); int type = entity.firstChildElement("type").text().toInt(); Point2i entityPos(entity.firstChildElement("x").text().toInt(),entity.firstChildElement("y").text().toInt()); this->scene->addEntityAtPosition(type,entityPos); } } /* for(int i=0;i<fieldList.count();i++) { QDomElement field = fieldList.at(i).toElement(); qDebug()<<field.attribute("width"); qDebug()<<field.attribute("height"); QDomNodeList lll=e1.elementsByTagName("a"); qDebug(QString::number(lll.count()).toAscii()); for(int j=0;j<lll.count();j++) { QDomElement e2 = lll.at(j).toElement(); qDebug(e2.tagName().toAscii()+" "+e2.attribute("ITEM").toAscii()); QDomNodeList llll=e2.elementsByTagName("b"); for(int k=0;k<llll.count();k++) { QDomElement e3 = llll.at(k).toElement(); qDebug(e3.tagName().toAscii()+" "+e3.text().toAscii()); } } } */ } }
void QgsProjectFileTransform::transformContrastEnhancement( QDomDocument& doc, const QDomElement& rasterproperties, QDomElement& rendererElem ) { if ( rasterproperties.isNull() || rendererElem.isNull() ) { return; } double minimumValue = 0; double maximumValue = 0; QDomElement contrastMinMaxElem = rasterproperties.firstChildElement( "contrastEnhancementMinMaxValues" ); if ( contrastMinMaxElem.isNull() ) { return; } QDomElement contrastEnhancementAlgorithmElem = rasterproperties.firstChildElement( "mContrastEnhancementAlgorithm" ); if ( contrastEnhancementAlgorithmElem.isNull() ) { return; } //convert enhancement name to enumeration int algorithmEnum = 0; QString algorithmString = contrastEnhancementAlgorithmElem.text(); if ( algorithmString == "StretchToMinimumMaximum" ) { algorithmEnum = 1; } else if ( algorithmString == "StretchAndClipToMinimumMaximum" ) { algorithmEnum = 2; } else if ( algorithmString == "ClipToMinimumMaximum" ) { algorithmEnum = 3; } else if ( algorithmString == "UserDefinedEnhancement" ) { algorithmEnum = 4; } QDomNodeList minMaxEntryList = contrastMinMaxElem.elementsByTagName( "minMaxEntry" ); QStringList enhancementNameList; if ( minMaxEntryList.size() == 1 ) { enhancementNameList << "contrastEnhancement"; } if ( minMaxEntryList.size() == 3 ) { enhancementNameList << "redContrastEnhancement" << "greenContrastEnhancement" << "blueContrastEnhancement"; } if ( minMaxEntryList.size() > enhancementNameList.size() ) { return; } QDomElement minMaxEntryElem; for ( int i = 0; i < minMaxEntryList.size(); ++i ) { minMaxEntryElem = minMaxEntryList.at( i ).toElement(); QDomElement minElem = minMaxEntryElem.firstChildElement( "min" ); if ( minElem.isNull() ) { return; } minimumValue = minElem.text().toDouble(); QDomElement maxElem = minMaxEntryElem.firstChildElement( "max" ); if ( maxElem.isNull() ) { return; } maximumValue = maxElem.text().toDouble(); QDomElement newContrastEnhancementElem = doc.createElement( enhancementNameList.at( i ) ); QDomElement newMinValElem = doc.createElement( "minValue" ); QDomText minText = doc.createTextNode( QString::number( minimumValue ) ); newMinValElem.appendChild( minText ); newContrastEnhancementElem.appendChild( newMinValElem ); QDomElement newMaxValElem = doc.createElement( "maxValue" ); QDomText maxText = doc.createTextNode( QString::number( maximumValue ) ); newMaxValElem.appendChild( maxText ); newContrastEnhancementElem.appendChild( newMaxValElem ); QDomElement newAlgorithmElem = doc.createElement( "algorithm" ); QDomText newAlgorithmText = doc.createTextNode( QString::number( algorithmEnum ) ); newAlgorithmElem.appendChild( newAlgorithmText ); newContrastEnhancementElem.appendChild( newAlgorithmElem ); rendererElem.appendChild( newContrastEnhancementElem ); } }
void MessageTreeWidget::importSms() { QString filename = QFileDialog::getOpenFileName(NULL, "Open File",".","Sms (*.xml)"); if(!filename.isEmpty()) { QFile file1(strMessagePathOpen); QFile file2(filename); QFile file3(strMessagePathOpen); if (!file1.open(QIODevice::ReadOnly)) return ; if (!file2.open(QIODevice::ReadOnly)) return ; QDomDocument doc1;//文档1 QDomDocument doc2;//文档2 if (!doc1.setContent(&file1)) { file1.close(); return; } if (!doc2.setContent(&file2)) { file2.close(); return ; } QDomElement docElem1 = doc1.documentElement(); QDomElement docElem2 = doc2.documentElement(); QDomNodeList list1 = doc1.elementsByTagName("SmsSum"); //以标签名进行查找 QDomElement firstElement; for(int i=0; i<list1.count(); i++) { QDomElement e = list1.at(i).toElement(); QString str= e.attribute("term"); if(str.compare("信息")==0) { firstElement = e; break; } } QDomNodeList list = doc2.elementsByTagName("Sms"); //以标签名进行查找 for(int j=0; j< list.count(); j++) { QDomElement e = list.at(j).toElement(); QDomElement tmp = e.cloneNode(true).toElement(); QString strContent = tmp.text(); bool key = keydetect(strContent); if(!key) firstElement.appendChild(tmp);//加入以后list 内已经删除了 } if(!file3.open(QIODevice::WriteOnly | QIODevice::Truncate)) return ; QTextStream out(&file3); doc1.save(out,4); //将文档保存到文件,4为子元素缩进字符数 file3.close(); emit updateTreeAllItem(); QMessageBox *message=new QMessageBox(QMessageBox::NoIcon, "导入短信", "导入成功"); message->show(); } }
//得到音乐(xml格式) void DownloadThread::slot_GetMusicXML(QNetworkReply *replay) { QTextCodec *codec = QTextCodec::codecForName("utf8");//转换成utf8编码格式 QString musicStr = codec ->toUnicode(replay ->readAll()); //没有连接到网络 if (musicStr == "") { QMessageBox::information(NULL, tr("信息"), tr("下载超时,请检查您的网络或者本机防火墙设置!"), QMessageBox::Yes); QString musicTitle = m_musicArtist + "-" + m_musicName; emit sig_DelCurrentMusicMapItem(musicTitle); return; } QString errorStr; int errorLine; int errorColumn; QDomDocument doc; if (!doc.setContent(musicStr, false, &errorStr, &errorLine, &errorColumn)) { qDebug() << "在第" << errorLine << "行,第" << errorColumn << "列,读取字符串到doc中错误:" << errorStr; QMessageBox::information(NULL, tr("信息"), tr("没有找到该歌曲!"), QMessageBox::Yes); return; } QDomElement root = doc.documentElement();//获取根元素 if (root.tagName() != "result") { QMessageBox::information(NULL, tr("信息"), tr("没有找到该歌曲!"), QMessageBox::Yes); return; } //获取音乐url QString sFirstPartUrl; //前半部分 QString sLastPartUrl; //后半部分 QDomNodeList nodeList = root.childNodes();//获得root所有子节点的列表 for (int i = 0; i < nodeList.count(); ++i) { QDomNode node = nodeList.at(i); if (!node.isNull())//如果节点不为空 { if (node.isElement())//如果节点是元素 { QDomElement element = node.toElement();//转换成元素 if (element.tagName() == "count") { qDebug() << "element.text() = " << element.text(); if (element.text() == "0")//返回元素文本 { QMessageBox::information(NULL, tr("信息"), tr("没有找到该歌曲!"), QMessageBox::Yes); return; } } else if (element.tagName() == "url") { QDomNodeList nodeList2 = element.childNodes();//获得url所有子节点的列表 for (int i = 0; i < nodeList2.count(); ++i) { QDomNode node2 = nodeList2.at(i); if (!node2.isNull())//如果节点不为空 { if (node2.isElement())//如果节点是元素 { QDomElement element2 = node2.toElement();//转换成元素 if (element2.tagName() == "encode") { //qDebug() << element2.text(); sFirstPartUrl = element2.text(); } else if (element2.tagName() == "decode") { //qDebug() << element2.text(); sLastPartUrl = element2.text(); break; } } else { QMessageBox::information(NULL, tr("信息"), tr("没有找到该歌曲!"), QMessageBox::Yes); return; } } else { QMessageBox::information(NULL, tr("信息"), tr("没有找到该歌曲!"), QMessageBox::Yes); return; } } break; } } else { QMessageBox::information(NULL, tr("信息"), tr("没有找到该歌曲!"), QMessageBox::Yes); return; } } else { QMessageBox::information(NULL, tr("信息"), tr("没有找到该歌曲!"), QMessageBox::Yes); return; } } //判断是否包含xcode,防止歌曲下载错误! if (!sLastPartUrl.contains("xcode")) { QMessageBox::information(NULL, tr("信息"), tr("没有找到该歌曲!"), QMessageBox::Yes); return; } //音乐url QString musicUrl = sFirstPartUrl + sLastPartUrl; //qDebug() << musicUrl; #ifdef _WIN32_WINNT QString WINPATH = CZPlayerConfig::getValue("MUSICDIR_WIN").toString(); QString musicFilePath = WINPATH + "/" + m_musicArtist + " - " + m_musicName + ".mp3"; #else QString X11PATH = QDir::homePath() + CZPlayerConfig::getValue("MUSICDIR_X11").toString(); QString musicFilePath = X11PATH + "/" + m_musicArtist + " - " + m_musicName + ".mp3"; #endif //插入下载列表 int currentRows = m_downloadList ->rowCount();//返回列表中的行数 m_downloadList ->insertRow(currentRows);//从下载列表中的当前行插入 //进度条 progressBar = new QProgressBar; progressBar ->setObjectName(tr("progressBar")); timer ->start(1000); time ->start(); //歌曲名称 musicTitleItem = new QTableWidgetItem; musicTitleItem ->setText(m_musicArtist + "-" + m_musicName); musicTitleItem ->setTextAlignment(Qt::AlignCenter); musicTitleItem ->setToolTip(m_musicArtist + "-" + m_musicName); //歌曲状态 musicStatusItem = new QTableWidgetItem; musicStatusItem ->setTextAlignment(Qt::AlignCenter); musicStatusItem ->setText(tr("正在下载")); //大小 musicSizeItem = new QTableWidgetItem; musicSizeItem ->setTextAlignment(Qt::AlignCenter); //网速 speedItem = new QTableWidgetItem; speedItem ->setTextAlignment(Qt::AlignCenter); m_downloadList ->setItem(currentRows, 0, musicTitleItem); m_downloadList ->setItem(currentRows, 1, musicStatusItem); m_downloadList ->setItem(currentRows, 2, musicSizeItem); m_downloadList ->setItem(currentRows, 3, speedItem); m_downloadList ->setCellWidget(currentRows, 4, progressBar); static int index = 0; threadMap.insert(make_pair(index, this)); listMap.insert(make_pair(index, currentRows)); //emit musicListMap(listMap); m_downloadList ->setMusicListMap(listMap); ++index; this ->getMusicFromURL(musicUrl, musicFilePath); replay ->deleteLater();//最后要释放reply对象 }
bool QgsComposerTable::tableReadXML( const QDomElement& itemElem, const QDomDocument& doc ) { if ( itemElem.isNull() ) { return false; } if ( !QgsFontUtils::setFromXmlChildNode( mHeaderFont, itemElem, "headerFontProperties" ) ) { mHeaderFont.fromString( itemElem.attribute( "headerFont", "" ) ); } mHeaderFontColor = QgsSymbolLayerV2Utils::decodeColor( itemElem.attribute( "headerFontColor", "0,0,0,255" ) ); mHeaderHAlignment = QgsComposerTable::HeaderHAlignment( itemElem.attribute( "headerHAlignment", "0" ).toInt() ); if ( !QgsFontUtils::setFromXmlChildNode( mContentFont, itemElem, "contentFontProperties" ) ) { mContentFont.fromString( itemElem.attribute( "contentFont", "" ) ); } mContentFontColor = QgsSymbolLayerV2Utils::decodeColor( itemElem.attribute( "contentFontColor", "0,0,0,255" ) ); mLineTextDistance = itemElem.attribute( "lineTextDist", "1.0" ).toDouble(); mGridStrokeWidth = itemElem.attribute( "gridStrokeWidth", "0.5" ).toDouble(); mShowGrid = itemElem.attribute( "showGrid", "1" ).toInt(); //grid color if ( itemElem.hasAttribute( "gridColor" ) ) { mGridColor = QgsSymbolLayerV2Utils::decodeColor( itemElem.attribute( "gridColor", "0,0,0,255" ) ); } else { //old style grid color int gridRed = itemElem.attribute( "gridColorRed", "0" ).toInt(); int gridGreen = itemElem.attribute( "gridColorGreen", "0" ).toInt(); int gridBlue = itemElem.attribute( "gridColorBlue", "0" ).toInt(); int gridAlpha = itemElem.attribute( "gridColorAlpha", "255" ).toInt(); mGridColor = QColor( gridRed, gridGreen, gridBlue, gridAlpha ); } //restore column specifications qDeleteAll( mColumns ); mColumns.clear(); QDomNodeList columnsList = itemElem.elementsByTagName( "displayColumns" ); if ( columnsList.size() > 0 ) { QDomElement columnsElem = columnsList.at( 0 ).toElement(); QDomNodeList columnEntryList = columnsElem.elementsByTagName( "column" ); for ( int i = 0; i < columnEntryList.size(); ++i ) { QDomElement columnElem = columnEntryList.at( i ).toElement(); QgsComposerTableColumn* column = new QgsComposerTableColumn; column->readXML( columnElem ); mColumns.append( column ); } } //restore general composer item properties QDomNodeList composerItemList = itemElem.elementsByTagName( "ComposerItem" ); if ( composerItemList.size() > 0 ) { QDomElement composerItemElem = composerItemList.at( 0 ).toElement(); _readXML( composerItemElem, doc ); } return true; }
Tellico::Data::CollPtr BoardGameGeekImporter::collection() { if(m_coll) { return m_coll; } if(m_xsltURL.isEmpty() || !m_xsltURL.isValid()) { setStatusMessage(i18n("A valid XSLT file is needed to import the file.")); return Data::CollPtr(); } if(!m_widget) { myWarning() << "no widget!"; return Data::CollPtr(); } m_user = m_userEdit->text().trimmed(); if(m_user.isEmpty()) { setStatusMessage(i18n("A valid user ID must be entered.")); return Data::CollPtr(); } XSLTHandler handler(m_xsltURL); if(!handler.isValid()) { setStatusMessage(i18n("Tellico encountered an error in XSLT processing.")); return Data::CollPtr(); } m_ownedOnly = m_checkOwned->isChecked(); // first get the bgg id list QUrl u(QString::fromLatin1(BGG_COLLECTION_URL)); QUrlQuery q; q.addQueryItem(QLatin1String("username"), m_user); q.addQueryItem(QLatin1String("subtype"), QLatin1String("boardgame")); q.addQueryItem(QLatin1String("brief"), QLatin1String("1")); if(m_ownedOnly) { q.addQueryItem(QLatin1String("own"), QLatin1String("1")); } u.setQuery(q); QStringList idList; QDomDocument dom = FileHandler::readXMLDocument(u, false, true); // could return HTTP 202 while the caching system generates the file // see http://boardgamegeek.com/thread/1188687/export-collections-has-been-updated-xmlapi-develop // also has a root node of message. Try 5 times, waiting by 2 seconds each time int loopCount = 0; while(loopCount < 5 && dom.documentElement().tagName() == QLatin1String("message")) { // wait 2 seconds and try again QTime dieTime = QTime::currentTime().addSecs(2); while(QTime::currentTime() < dieTime) { QCoreApplication::processEvents(QEventLoop::AllEvents, 100); } dom = FileHandler::readXMLDocument(u, false, true); ++loopCount; } QDomNodeList items = dom.documentElement().elementsByTagName(QLatin1String("item")); for(int i = 0; i < items.count(); ++i) { if(!items.at(i).isElement()) { continue; } const QString id = items.at(i).toElement().attribute(QLatin1String("objectid")); if(!id.isEmpty()) { idList += id; } } if(idList.isEmpty()) { myLog() << "No items found"; return Data::CollPtr(); } const bool showProgress = options() & ImportProgress; if(showProgress) { // use 10 as the amount for reading the ids emit signalTotalSteps(this, 10 + 100); emit signalProgress(this, 10); } m_coll = new Data::BoardGameCollection(true); for(int j = 0; j < idList.size() && !m_cancelled; j += BGG_STEPSIZE) { QStringList ids; const int maxSize = qMin(j+BGG_STEPSIZE, idList.size()); for(int k = j; k < maxSize; ++k) { ids += idList.at(k); } #if 0 const QString xmlData = text(ids); myWarning() << "Remove debug from boardgamegeekimporter.cpp"; QFile f(QLatin1String("/tmp/test.xml")); if(f.open(QIODevice::WriteOnly)) { QTextStream t(&f); t.setCodec("UTF-8"); t << xmlData; } f.close(); #endif QString str = handler.applyStylesheet(text(ids)); // QString str = handler.applyStylesheet(xmlData); // myDebug() << str; Import::TellicoImporter imp(str); imp.setOptions(imp.options() ^ Import::ImportShowImageErrors); Data::CollPtr c = imp.collection(); // assume we always want the 3 extra fields defined in boardgamegeek2tellico.xsl if(!m_coll->hasField(QLatin1String("bggid"))) { m_coll->addField(Data::FieldPtr(new Data::Field(*c->fieldByName(QLatin1String("bggid"))))); m_coll->addField(Data::FieldPtr(new Data::Field(*c->fieldByName(QLatin1String("boardgamegeek-link"))))); Data::FieldPtr f(new Data::Field(*c->fieldByName(QLatin1String("artist")))); // also, let's assume that the artist field title should be illustrator instead of musician f->setTitle(i18nc("Comic Book Illustrator", "Artist")); m_coll->addField(f); } m_coll->addEntries(imp.collection()->entries()); setStatusMessage(imp.statusMessage()); if(showProgress) { emit signalProgress(this, 10 + 100*j/idList.size()); qApp->processEvents(); } } KConfigGroup config(KSharedConfig::openConfig(), QLatin1String("ImportOptions - BoardGameGeek")); config.writeEntry("User ID", m_user); config.writeEntry("Owned", m_ownedOnly); if(m_cancelled) { m_coll = Data::CollPtr(); } return m_coll; }
// 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(); }
QSet<QString> QgsServerProjectParser::findRestrictedLayers() const { QSet<QString> restrictedLayerSet; if ( !mXMLDoc ) { return restrictedLayerSet; } //names of unpublished layers / groups QDomElement propertiesElem = mXMLDoc->documentElement().firstChildElement( "properties" ); if ( !propertiesElem.isNull() ) { QDomElement wmsLayerRestrictionElem = propertiesElem.firstChildElement( "WMSRestrictedLayers" ); if ( !wmsLayerRestrictionElem.isNull() ) { QStringList restrictedLayersAndGroups; QDomNodeList wmsLayerRestrictionValues = wmsLayerRestrictionElem.elementsByTagName( "value" ); for ( int i = 0; i < wmsLayerRestrictionValues.size(); ++i ) { restrictedLayerSet.insert( wmsLayerRestrictionValues.at( i ).toElement().text() ); } } } //get legend dom element if ( restrictedLayerSet.size() < 1 || !mXMLDoc ) { return restrictedLayerSet; } QDomElement legendElem = mXMLDoc->documentElement().firstChildElement( "legend" ); if ( legendElem.isNull() ) { return restrictedLayerSet; } //go through all legend groups and insert names of subgroups / sublayers if there is a match QDomNodeList legendGroupList = legendElem.elementsByTagName( "legendgroup" ); for ( int i = 0; i < legendGroupList.size(); ++i ) { //get name QDomElement groupElem = legendGroupList.at( i ).toElement(); QString groupName = groupElem.attribute( "name" ); if ( restrictedLayerSet.contains( groupName ) ) //match: add names of subgroups and sublayers to set { //embedded group? -> also get names of subgroups and sublayers from embedded projects if ( groupElem.attribute( "embedded" ) == "1" ) { sublayersOfEmbeddedGroup( convertToAbsolutePath( groupElem.attribute( "project" ) ), groupName, restrictedLayerSet ); } else //local group { QDomNodeList subgroupList = groupElem.elementsByTagName( "legendgroup" ); for ( int j = 0; j < subgroupList.size(); ++j ) { restrictedLayerSet.insert( subgroupList.at( j ).toElement().attribute( "name" ) ); } QDomNodeList sublayerList = groupElem.elementsByTagName( "legendlayer" ); for ( int k = 0; k < sublayerList.size(); ++k ) { restrictedLayerSet.insert( sublayerList.at( k ).toElement().attribute( "name" ) ); } } } } // wmsLayerRestrictionValues contains LayerIDs if ( mUseLayerIDs ) { QDomNodeList legendLayerList = legendElem.elementsByTagName( "legendlayer" ); for ( int i = 0; i < legendLayerList.size(); ++i ) { //get name QDomElement layerElem = legendLayerList.at( i ).toElement(); QString layerName = layerElem.attribute( "name" ); if ( restrictedLayerSet.contains( layerName ) ) //match: add layer id { // get legend layer file element QDomNodeList layerfileList = layerElem.elementsByTagName( "legendlayerfile" ); if ( layerfileList.size() > 0 ) { // add layer id restrictedLayerSet.insert( layerfileList.at( 0 ).toElement().attribute( "layerid" ) ); } } } } return restrictedLayerSet; }
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 QgsServerProjectParser::serviceCapabilities( QDomElement& parentElement, QDomDocument& doc, const QString& service, bool sia2045 ) const { QDomElement propertiesElement = propertiesElem(); if ( propertiesElement.isNull() ) { QgsConfigParserUtils::fallbackServiceCapabilities( parentElement, doc ); return; } QDomElement serviceElem = doc.createElement( "Service" ); QDomElement serviceCapabilityElem = propertiesElement.firstChildElement( "WMSServiceCapabilities" ); if ( serviceCapabilityElem.isNull() || serviceCapabilityElem.text().compare( "true", Qt::CaseInsensitive ) != 0 ) { QgsConfigParserUtils::fallbackServiceCapabilities( parentElement, doc ); return; } //Service name QDomElement wmsNameElem = doc.createElement( "Name" ); QDomText wmsNameText = doc.createTextNode( service ); wmsNameElem.appendChild( wmsNameText ); serviceElem.appendChild( wmsNameElem ); //WMS title QDomElement titleElem = propertiesElement.firstChildElement( "WMSServiceTitle" ); if ( !titleElem.isNull() ) { QDomElement wmsTitleElem = doc.createElement( "Title" ); QDomText wmsTitleText = doc.createTextNode( titleElem.text() ); wmsTitleElem.appendChild( wmsTitleText ); serviceElem.appendChild( wmsTitleElem ); } //WMS abstract QDomElement abstractElem = propertiesElement.firstChildElement( "WMSServiceAbstract" ); if ( !abstractElem.isNull() ) { QDomElement wmsAbstractElem = doc.createElement( "Abstract" ); QDomText wmsAbstractText = doc.createTextNode( abstractElem.text() ); wmsAbstractElem.appendChild( wmsAbstractText ); serviceElem.appendChild( wmsAbstractElem ); } //keyword list QDomElement keywordListElem = propertiesElement.firstChildElement( "WMSKeywordList" ); QDomElement wmsKeywordElem = doc.createElement( "KeywordList" ); //add default keyword QDomElement keywordElem = doc.createElement( "Keyword" ); keywordElem.setAttribute( "vocabulary", "ISO" ); QDomText keywordText = doc.createTextNode( "infoMapAccessService" ); if ( service.compare( "WFS", Qt::CaseInsensitive ) == 0 ) keywordText = doc.createTextNode( "infoFeatureAccessService" ); else if ( service.compare( "WCS", Qt::CaseInsensitive ) == 0 ) keywordText = doc.createTextNode( "infoCoverageAccessService" ); keywordElem.appendChild( keywordText ); wmsKeywordElem.appendChild( keywordElem ); serviceElem.appendChild( wmsKeywordElem ); //add config keywords if ( !keywordListElem.isNull() && !keywordListElem.text().isEmpty() ) { QDomNodeList keywordList = keywordListElem.elementsByTagName( "value" ); for ( int i = 0; i < keywordList.size(); ++i ) { keywordElem = doc.createElement( "Keyword" ); keywordText = doc.createTextNode( keywordList.at( i ).toElement().text() ); keywordElem.appendChild( keywordText ); if ( sia2045 ) { keywordElem.setAttribute( "vocabulary", "SIA_Geo405" ); } wmsKeywordElem.appendChild( keywordElem ); } } //OnlineResource element is mandatory according to the WMS specification QDomElement wmsOnlineResourceElem = propertiesElement.firstChildElement( "WMSOnlineResource" ); QDomElement onlineResourceElem = doc.createElement( "OnlineResource" ); onlineResourceElem.setAttribute( "xmlns:xlink", "http://www.w3.org/1999/xlink" ); onlineResourceElem.setAttribute( "xlink:type", "simple" ); if ( !wmsOnlineResourceElem.isNull() ) { onlineResourceElem.setAttribute( "xlink:href", wmsOnlineResourceElem.text() ); } serviceElem.appendChild( onlineResourceElem ); if ( service.compare( "WMS", Qt::CaseInsensitive ) == 0 ) //no contact information in WFS 1.0 and WCS 1.0 { //Contact information QDomElement contactInfoElem = doc.createElement( "ContactInformation" ); //Contact person primary QDomElement contactPersonPrimaryElem = doc.createElement( "ContactPersonPrimary" ); //Contact person QDomElement contactPersonElem = propertiesElement.firstChildElement( "WMSContactPerson" ); QString contactPersonString; if ( !contactPersonElem.isNull() ) { contactPersonString = contactPersonElem.text(); } QDomElement wmsContactPersonElem = doc.createElement( "ContactPerson" ); QDomText contactPersonText = doc.createTextNode( contactPersonString ); wmsContactPersonElem.appendChild( contactPersonText ); contactPersonPrimaryElem.appendChild( wmsContactPersonElem ); //Contact organisation QDomElement contactOrganizationElem = propertiesElement.firstChildElement( "WMSContactOrganization" ); QString contactOrganizationString; if ( !contactOrganizationElem.isNull() ) { contactOrganizationString = contactOrganizationElem.text(); } QDomElement wmsContactOrganizationElem = doc.createElement( "ContactOrganization" ); QDomText contactOrganizationText = doc.createTextNode( contactOrganizationString ); wmsContactOrganizationElem.appendChild( contactOrganizationText ); contactPersonPrimaryElem.appendChild( wmsContactOrganizationElem ); contactInfoElem.appendChild( contactPersonPrimaryElem ); //phone QDomElement phoneElem = propertiesElement.firstChildElement( "WMSContactPhone" ); if ( !phoneElem.isNull() ) { QDomElement wmsPhoneElem = doc.createElement( "ContactVoiceTelephone" ); QDomText wmsPhoneText = doc.createTextNode( phoneElem.text() ); wmsPhoneElem.appendChild( wmsPhoneText ); contactInfoElem.appendChild( wmsPhoneElem ); } //mail QDomElement mailElem = propertiesElement.firstChildElement( "WMSContactMail" ); if ( !mailElem.isNull() ) { QDomElement wmsMailElem = doc.createElement( "ContactElectronicMailAddress" ); QDomText wmsMailText = doc.createTextNode( mailElem.text() ); wmsMailElem.appendChild( wmsMailText ); contactInfoElem.appendChild( wmsMailElem ); } serviceElem.appendChild( contactInfoElem ); } //Fees QDomElement feesElem = propertiesElement.firstChildElement( "WMSFees" ); QDomElement wmsFeesElem = doc.createElement( "Fees" ); QDomText wmsFeesText = doc.createTextNode( "conditions unknown" ); // default value if access conditions are unknown if ( !feesElem.isNull() && feesElem.text() != "" ) { wmsFeesText = doc.createTextNode( feesElem.text() ); } wmsFeesElem.appendChild( wmsFeesText ); serviceElem.appendChild( wmsFeesElem ); //AccessConstraints QDomElement accessConstraintsElem = propertiesElement.firstChildElement( "WMSAccessConstraints" ); QDomElement wmsAccessConstraintsElem = doc.createElement( "AccessConstraints" ); QDomText wmsAccessConstraintsText = doc.createTextNode( "None" ); // default value if access constraints are unknown if ( !accessConstraintsElem.isNull() && accessConstraintsElem.text() != "" ) { wmsAccessConstraintsText = doc.createTextNode( accessConstraintsElem.text() ); } wmsAccessConstraintsElem.appendChild( wmsAccessConstraintsText ); serviceElem.appendChild( wmsAccessConstraintsElem ); //max width, max height for WMS if ( service.compare( "WMS", Qt::CaseInsensitive ) == 0 ) { QString version = doc.documentElement().attribute( "version" ); if ( version != "1.1.1" ) { //max width QDomElement mwElem = propertiesElement.firstChildElement( "WMSMaxWidth" ); if ( !mwElem.isNull() ) { QDomElement maxWidthElem = doc.createElement( "MaxWidth" ); QDomText maxWidthText = doc.createTextNode( mwElem.text() ); maxWidthElem.appendChild( maxWidthText ); serviceElem.appendChild( maxWidthElem ); } //max height QDomElement mhElem = propertiesElement.firstChildElement( "WMSMaxHeight" ); if ( !mhElem.isNull() ) { QDomElement maxHeightElem = doc.createElement( "MaxHeight" ); QDomText maxHeightText = doc.createTextNode( mhElem.text() ); maxHeightElem.appendChild( maxHeightText ); serviceElem.appendChild( maxHeightElem ); } } } parentElement.appendChild( serviceElem ); }
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; }
QStringList QgsServerProjectParser::supportedOutputCrsList() const { QStringList crsList; if ( !mXMLDoc ) { return crsList; } QDomElement qgisElem = mXMLDoc->documentElement(); if ( qgisElem.isNull() ) { return crsList; } QDomElement propertiesElem = qgisElem.firstChildElement( "properties" ); if ( propertiesElem.isNull() ) { return crsList; } QDomElement wmsCrsElem = propertiesElem.firstChildElement( "WMSCrsList" ); if ( !wmsCrsElem.isNull() ) { QDomNodeList valueList = wmsCrsElem.elementsByTagName( "value" ); for ( int i = 0; i < valueList.size(); ++i ) { crsList.append( valueList.at( i ).toElement().text() ); } } else { QDomElement wmsEpsgElem = propertiesElem.firstChildElement( "WMSEpsgList" ); if ( !wmsEpsgElem.isNull() ) { QDomNodeList valueList = wmsEpsgElem.elementsByTagName( "value" ); bool conversionOk; for ( int i = 0; i < valueList.size(); ++i ) { int epsgNr = valueList.at( i ).toElement().text().toInt( &conversionOk ); if ( conversionOk ) { crsList.append( QString( "EPSG:%1" ).arg( epsgNr ) ); } } } else { //no CRS restriction defined in the project. Provide project CRS, wgs84 and pseudo mercator QString projectCrsId = projectCRS().authid(); crsList.append( projectCrsId ); if ( projectCrsId.compare( "EPSG:4326", Qt::CaseInsensitive ) != 0 ) { crsList.append( QString( "EPSG:%1" ).arg( 4326 ) ); } if ( projectCrsId.compare( "EPSG:3857", Qt::CaseInsensitive ) != 0 ) { crsList.append( QString( "EPSG:%1" ).arg( 3857 ) ); } } } return crsList; }
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(); } }
InvoiceData XmlDataLayer::invoiceSelectData(QString name, int type) { qDebug() << __FILE__ << __LINE__ << __FUNCTION__; InvoiceData o_invData; QDomDocument doc(sett().getInoiveDocName()); QDomElement root; QDomElement nabywca; QDomElement product; QString fName = name; QFile file(sett().getInvoicesDir() + fName); if (!file.open(QIODevice::ReadOnly)) { qDebug("file doesn't exist"); return o_invData; } else { QTextStream stream(&file); if (!doc.setContent(stream.readAll())) { file.close(); return o_invData; } } root = doc.documentElement(); o_invData.frNr = root.attribute("no"); o_invData.sellingDate = QDate::fromString(root.attribute("sellingDate"), sett().getDateFormat()); o_invData.productDate = QDate::fromString(root.attribute("issueDate"), sett().getDateFormat()); QDomNode tmp; tmp = root.firstChild(); tmp = tmp.toElement().nextSibling(); // nabywca nabywca = tmp.toElement(); o_invData.customer = nabywca.attribute("name") + "," + nabywca.attribute( "city") + "," + nabywca.attribute("street") + "," + QObject::trUtf8("NIP: ") + nabywca.attribute("tic"); /* not required + ", " + nabywca.attribute("account") + ", " + nabywca.attribute("phone") + ", " + nabywca.attribute( "email") + ", " + nabywca.attribute("www")) */ // kontrName->setCursorPosition(1); tmp = tmp.toElement().nextSibling(); // product product = tmp.toElement(); o_invData.discount = product.attribute("discount").toInt(); tmp = tmp.toElement().nextSibling(); QDomElement additional = tmp.toElement(); o_invData.additText = additional.attribute("text"); int curPayment = sett().value("payments").toString().split("|").indexOf(additional.attribute("paymentType")); if (curPayment == sett().value("payments").toString().split("|").count() - 1) { // disconnect(platCombo, SIGNAL(currentIndexChanged (QString)), this, SLOT(payTextChanged(QString))); // platCombo->setCurrentIndex(curPayment); // ; // = new CustomPaymData(); o_invData.custPaym.payment1 = additional.attribute("payment1"); o_invData.custPaym.amount1 = additional.attribute("amount1").toDouble(); o_invData.custPaym.date1 = QDate::fromString(additional.attribute("liabDate1"), sett().getDateFormat()); o_invData.custPaym.payment2 = additional.attribute("payment2"); o_invData.custPaym.amount2 = additional.attribute("amount2").toDouble(); o_invData.custPaym.date2 = QDate::fromString(additional.attribute("liabDate2"), sett().getDateFormat()); // connect(platCombo, SIGNAL(currentIndexChanged (QString)), this, SLOT(payTextChanged(QString))); } else { // platCombo->setCurrentIndex(curPayment); } o_invData.liabDate = QDate::fromString(additional.attribute("liabDate"), sett().getDateFormat()); int curCurrency = sett().value("waluty").toString().split("|").indexOf(additional.attribute("currency")); o_invData.currencyTypeId = curCurrency; QFile db(sett().getInvoicesDir() + name); if (!db.open(QIODevice::ReadOnly | QIODevice::Text)) { qDebug("file doesn't exist"); return o_invData; } QXmlQuery query; QString res; query.setFocus(&db); query.setQuery("//product"); if ( ! query.isValid()) return o_invData; query.evaluateTo(&res); db.close(); QDomDocument productsDOMDocument; productsDOMDocument.setContent("" + res + ""); QDomNodeList products = productsDOMDocument.elementsByTagName("product"); for (int i = 0; i < products.count(); i++) { QDomElement product = products.at(i).toElement(); o_invData.products[i] = ProductData(product.attribute("id").toInt(), product.attribute("name"), product.attribute("code"), product.attribute("PKWiU"), product.attribute("quantity").toDouble(), product.attribute("quantityType"), product.attribute("discount").toDouble(), product.attribute("price").toDouble(), product.attribute("nett").toDouble(), product.attribute("vatBucket").toInt(), product.attribute("gross").toDouble(), additional.attribute("currency")); } return o_invData; }
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; }
/** Upgrade from <= 1.7 library to 1.8 DB format */ void LegacyLibraryImporter::import() { // TODO(XXX) SETTINGS_PATH may change in new Mixxx Versions. Here we need // the SETTINGS_PATH from Mixxx V <= 1.7 QString settingPath17 = QDir::homePath().append("/").append(SETTINGS_PATH); QString trackXML = settingPath17.append("mixxxtrack.xml"); QFile file(trackXML); QDomDocument doc("TrackList"); if(!file.open(QIODevice::ReadOnly)) { //qDebug() << "Could not import legacy 1.7 XML library: " << trackXML; return; } QString* errorMsg = NULL; int* errorLine = NULL; int* errorColumn = NULL; qDebug() << "Starting upgrade from 1.7 library..."; QHash<int, QString> playlistHashTable; //Maps track indices onto track locations QList<LegacyPlaylist> legacyPlaylists; // <= 1.7 playlists if (doc.setContent(&file, false, errorMsg, errorLine, errorColumn)) { QDomNodeList playlistList = doc.elementsByTagName("Playlist"); QDomNode playlist; for (int i = 0; i < playlistList.size(); i++) { LegacyPlaylist legPlaylist; playlist = playlistList.at(i); QString name = playlist.firstChildElement("Name").text(); legPlaylist.name = name; //Store the IDs in the hash table so we can map them to track locations later, //and also store them in-order in a temporary playlist struct. QDomElement listNode = playlist.firstChildElement("List").toElement(); QDomNodeList trackIDs = listNode.elementsByTagName("Id"); for (int j = 0; j < trackIDs.size(); j++) { int id = trackIDs.at(j).toElement().text().toInt(); if (!playlistHashTable.contains(id)) playlistHashTable.insert(id, ""); legPlaylist.indexes.push_back(id); //Save this track id. } //Save this playlist in our list. legacyPlaylists.push_back(legPlaylist); } QDomNodeList trackList = doc.elementsByTagName("Track"); QDomNode track; for (int i = 0; i < trackList.size(); i++) { //blah, can't figure out how to use an iterator with QDomNodeList track = trackList.at(i); TrackInfoObject trackInfo17(track); //Only add the track to the DB if the file exists on disk, //because Mixxx <= 1.7 had no logic to deal with detecting deleted //files. if (trackInfo17.exists()) { //Create a TrackInfoObject by directly parsing //the actual MP3/OGG/whatever because 1.7 didn't parse //genre and album tags (so the imported TIO doesn't have //those fields). emit(progress("Upgrading Mixxx 1.7 Library: " + trackInfo17.getTitle())); // Read the metadata we couldn't support in <1.8 from file. QFileInfo fileInfo(trackInfo17.getLocation()); //Ensure we have the absolute file path stored trackInfo17.setLocation(fileInfo.absoluteFilePath()); TrackInfoObject trackInfoNew(trackInfo17.getLocation()); trackInfo17.setGenre(trackInfoNew.getGenre()); trackInfo17.setAlbum(trackInfoNew.getAlbum()); trackInfo17.setYear(trackInfoNew.getYear()); trackInfo17.setType(trackInfoNew.getType()); trackInfo17.setTrackNumber(trackInfoNew.getTrackNumber()); trackInfo17.setKeys(trackInfoNew.getKeys()); trackInfo17.setHeaderParsed(true); // Import the track's saved cue point if it is non-zero. float fCuePoint = trackInfo17.getCuePoint(); if (fCuePoint != 0.0f) { Cue* pCue = trackInfo17.addCue(); pCue->setType(Cue::CUE); pCue->setPosition(fCuePoint); } // Provide a no-op deleter b/c this Track is on the stack. TrackPointer pTrack(&trackInfo17, &doNothing); m_trackDao.saveTrack(pTrack); //Check if this track is used in a playlist anywhere. If it is, save the //track location. (The "id" of a track in 1.8 is a database index, so it's totally //different. Using the track location is the best way for us to identify the song.) int id = trackInfo17.getId(); if (playlistHashTable.contains(id)) playlistHashTable[id] = trackInfo17.getLocation(); } } //Create the imported playlists QListIterator<LegacyPlaylist> it(legacyPlaylists); LegacyPlaylist current; while (it.hasNext()) { current = it.next(); emit(progress("Upgrading Mixxx 1.7 Playlists: " + current.name)); //Create the playlist with the imported name. //qDebug() << "Importing playlist:" << current.name; int playlistId = m_playlistDao.createPlaylist(current.name); //For each track ID in the XML... QList<int> trackIDs = current.indexes; for (int i = 0; i < trackIDs.size(); i++) { QString trackLocation; int id = trackIDs[i]; //qDebug() << "track ID:" << id; //Try to resolve the (XML's) track ID to a track location. if (playlistHashTable.contains(id)) { trackLocation = playlistHashTable[id]; //qDebug() << "Resolved to:" << trackLocation; } //Get the database's track ID (NOT the XML's track ID!) int dbTrackId = m_trackDao.getTrackId(trackLocation); if (dbTrackId >= 0) { // Add it to the database's playlist. // TODO(XXX): Care if the append succeeded. m_playlistDao.appendTrackToPlaylist(dbTrackId, playlistId); } } } QString upgrade_filename = settingPath17.append("DBUPGRADED"); //now create stub so that the library is not readded next time program loads QFile upgradefile(upgrade_filename); if (!upgradefile.open(QIODevice::WriteOnly | QIODevice::Text)) qDebug() << "Couldn't open" << upgrade_filename << "for writing"; else { file.write("",0); file.close(); } } else { qDebug() << errorMsg << " line: " << errorLine << " column: " << errorColumn; } file.close(); }