def testQgsSvgMarkerSymbolLayer(self): """ Create a new style from a .sld file and match test """ mTestName = 'QgsSvgMarkerSymbolLayer' mFilePath = QDir.toNativeSeparators('%s/symbol_layer/%s.sld' % (unitTestDataPath(), mTestName)) mDoc = QDomDocument(mTestName) mFile = QFile(mFilePath) mFile.open(QIODevice.ReadOnly) mDoc.setContent(mFile, True) mFile.close() mSymbolLayer = QgsSvgMarkerSymbolLayer.createFromSld(mDoc.elementsByTagName('PointSymbolizer').item(0).toElement()) mExpectedValue = type(QgsSvgMarkerSymbolLayer("")) mValue = type(mSymbolLayer) mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue) assert mExpectedValue == mValue, mMessage mExpectedValue = 'skull.svg' mValue = os.path.basename(mSymbolLayer.path()) print(("VALUE", mSymbolLayer.path())) mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue) assert mExpectedValue == mValue, mMessage mExpectedValue = 12 mValue = mSymbolLayer.size() mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue) assert mExpectedValue == mValue, mMessage mExpectedValue = 45 mValue = mSymbolLayer.angle() mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue) assert mExpectedValue == mValue, mMessage
def testQgsCentroidFillSymbolLayerV2(self): """ Create a new style from a .sld file and match test """ mTestName = 'QgsCentroidFillSymbolLayerV2' mFilePath = QDir.toNativeSeparators('%s/symbol_layer/%s.sld' % (unitTestDataPath(), mTestName)) mDoc = QDomDocument(mTestName) mFile = QFile(mFilePath) mFile.open(QIODevice.ReadOnly) mDoc.setContent(mFile, True) mFile.close() mSymbolLayer = QgsCentroidFillSymbolLayerV2.createFromSld( mDoc.elementsByTagName('PointSymbolizer').item(0).toElement()) mExpectedValue = type(QgsCentroidFillSymbolLayerV2()) mValue = type(mSymbolLayer) mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue) assert mExpectedValue == mValue, mMessage mExpectedValue = u'regular_star' mValue = mSymbolLayer.subSymbol().symbolLayer(0).name() mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue) assert mExpectedValue == mValue, mMessage mExpectedValue = u'#55aaff' mValue = mSymbolLayer.subSymbol().symbolLayer(0).color().name() mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue) assert mExpectedValue == mValue, mMessage mExpectedValue = u'#00ff00' mValue = mSymbolLayer.subSymbol().symbolLayer(0).borderColor().name() mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue) assert mExpectedValue == mValue, mMessage
def testQgsSVGFillSymbolLayer(self): """ Create a new style from a .sld file and match test """ mTestName = 'QgsSVGFillSymbolLayer' mFilePath = QDir.toNativeSeparators('%s/symbol_layer/%s.sld' % (unitTestDataPath(), mTestName)) mDoc = QDomDocument(mTestName) mFile = QFile(mFilePath) mFile.open(QIODevice.ReadOnly) mDoc.setContent(mFile, True) mFile.close() mSymbolLayer = QgsSVGFillSymbolLayer.createFromSld( mDoc.elementsByTagName('PolygonSymbolizer').item(0).toElement()) mExpectedValue = type(QgsSVGFillSymbolLayer("")) mValue = type(mSymbolLayer) mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue) assert mExpectedValue == mValue, mMessage mExpectedValue = 'accommodation_camping.svg' mValue = os.path.basename(mSymbolLayer.svgFilePath()) mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue) assert mExpectedValue == mValue, mMessage mExpectedValue = 6 mValue = mSymbolLayer.patternWidth() mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue) assert mExpectedValue == mValue, mMessage
def on_btnLoad_clicked(self): fileName, _ = QFileDialog.getOpenFileName(None, self.tr('Import Colors and elevations from XML'), QDir.homePath(), self.tr('XML files (*.xml *.XML)')) if fileName == '': return doc = QDomDocument() with codecs.open(fileName, 'r', encoding='utf-8') as f: content = f.read() if not doc.setContent(content): QMessageBox.critical(None, self.tr('Error parsing XML'), self.tr('The XML file could not be loaded')) return self.reliefClassTree.clear() reliefColorList = doc.elementsByTagName('ReliefColor') for i in range(reliefColorList.length()): elem = reliefColorList.at(i).toElement() item = QTreeWidgetItem() item.setText(0, elem.attribute('MinElevation')) item.setText(1, elem.attribute('MaxElevation')) item.setBackground(2, QBrush(QColor(int(elem.attribute('red')), int(elem.attribute('green')), int(elem.attribute('blue'))))) self.reliefClassTree.addTopLevelItem(item)
def testQgsSimpleLineSymbolLayerV2(self): """ Create a new style from a .sld file and match test """ mTestName = "QgsSimpleLineSymbolLayerV2" mFilePath = QDir.toNativeSeparators("%s/symbol_layer/%s.sld" % (unitTestDataPath(), mTestName)) mDoc = QDomDocument(mTestName) mFile = QFile(mFilePath) mFile.open(QIODevice.ReadOnly) mDoc.setContent(mFile, True) mFile.close() mSymbolLayer = QgsSimpleLineSymbolLayerV2.createFromSld( mDoc.elementsByTagName("LineSymbolizer").item(0).toElement() ) mExpectedValue = type(QgsSimpleLineSymbolLayerV2()) mValue = type(mSymbolLayer) mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue) assert mExpectedValue == mValue, mMessage mExpectedValue = u"#aa007f" mValue = mSymbolLayer.color().name() mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue) assert mExpectedValue == mValue, mMessage mExpectedValue = 1.26 mValue = mSymbolLayer.width() mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue) assert mExpectedValue == mValue, mMessage mExpectedValue = Qt.RoundCap mValue = mSymbolLayer.penCapStyle() mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue) assert mExpectedValue == mValue, mMessage mExpectedValue = Qt.MiterJoin mValue = mSymbolLayer.penJoinStyle() mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue) assert mExpectedValue == mValue, mMessage mExpectedValue = True mValue = mSymbolLayer.useCustomDashPattern() mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue) assert mExpectedValue == mValue, mMessage mExpectedValue = [5.0, 2.0] mValue = mSymbolLayer.customDashVector() mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue) assert mExpectedValue == mValue, mMessage
def createEllipseSymbolLayer(self): # No way to build it programmatically... mTestName = 'QgsEllipseSymbolLayer' mFilePath = QDir.toNativeSeparators( '%s/symbol_layer/%s.sld' % (unitTestDataPath(), mTestName)) mDoc = QDomDocument(mTestName) mFile = QFile(mFilePath) mFile.open(QIODevice.ReadOnly) mDoc.setContent(mFile, True) mFile.close() mSymbolLayer = QgsEllipseSymbolLayer.createFromSld( mDoc.elementsByTagName('PointSymbolizer').item(0).toElement()) return mSymbolLayer
def testQgsMarkerLineSymbolLayerV2(self): """ Create a new style from a .sld file and match test """ mTestName = "QgsMarkerLineSymbolLayerV2" mFilePath = QDir.toNativeSeparators("%s/symbol_layer/%s.sld" % (unitTestDataPath(), mTestName)) mDoc = QDomDocument(mTestName) mFile = QFile(mFilePath) mFile.open(QIODevice.ReadOnly) mDoc.setContent(mFile, True) mFile.close() mSymbolLayer = QgsMarkerLineSymbolLayerV2.createFromSld( mDoc.elementsByTagName("LineSymbolizer").item(0).toElement() ) mExpectedValue = type(QgsMarkerLineSymbolLayerV2()) mValue = type(mSymbolLayer) mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue) assert mExpectedValue == mValue, mMessage mExpectedValue = QgsMarkerLineSymbolLayerV2.CentralPoint mValue = mSymbolLayer.placement() mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue) assert mExpectedValue == mValue, mMessage mExpectedValue = u"circle" mValue = mSymbolLayer.subSymbol().symbolLayer(0).name() mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue) assert mExpectedValue == mValue, mMessage mExpectedValue = u"#000000" mValue = mSymbolLayer.subSymbol().symbolLayer(0).borderColor().name() mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue) assert mExpectedValue == mValue, mMessage mExpectedValue = u"#ff0000" mValue = mSymbolLayer.subSymbol().symbolLayer(0).color().name() mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue) assert mExpectedValue == mValue, mMessage # test colors, need to make sure colors are passed/retrieved from subsymbol mSymbolLayer.setColor(QColor(150, 50, 100)) self.assertEqual(mSymbolLayer.color(), QColor(150, 50, 100)) self.assertEqual(mSymbolLayer.subSymbol().color(), QColor(150, 50, 100)) mSymbolLayer.subSymbol().setColor(QColor(250, 150, 200)) self.assertEqual(mSymbolLayer.subSymbol().color(), QColor(250, 150, 200)) self.assertEqual(mSymbolLayer.color(), QColor(250, 150, 200))
def testQgsLinePatternFillSymbolLayer(self): """ Create a new style from a .sld file and match test """ mTestName = "QgsLinePatternFillSymbolLayer" mFilePath = QDir.toNativeSeparators("%s/symbol_layer/%s.sld" % (unitTestDataPath(), mTestName)) mDoc = QDomDocument(mTestName) mFile = QFile(mFilePath) mFile.open(QIODevice.ReadOnly) mDoc.setContent(mFile, True) mFile.close() mSymbolLayer = QgsLinePatternFillSymbolLayer.createFromSld( mDoc.elementsByTagName("PolygonSymbolizer").item(0).toElement() ) mExpectedValue = type(QgsLinePatternFillSymbolLayer()) mValue = type(mSymbolLayer) mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue) assert mExpectedValue == mValue, mMessage mExpectedValue = u"#ff55ff" mValue = mSymbolLayer.color().name() mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue) assert mExpectedValue == mValue, mMessage mExpectedValue = 1.5 mValue = mSymbolLayer.lineWidth() mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue) assert mExpectedValue == mValue, mMessage mExpectedValue = 4 mValue = mSymbolLayer.distance() mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue) assert mExpectedValue == mValue, mMessage mExpectedValue = 57 mValue = mSymbolLayer.lineAngle() mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue) assert mExpectedValue == mValue, mMessage # test colors, need to make sure colors are passed/retrieved from subsymbol mSymbolLayer.setColor(QColor(150, 50, 100)) self.assertEqual(mSymbolLayer.color(), QColor(150, 50, 100)) self.assertEqual(mSymbolLayer.subSymbol().color(), QColor(150, 50, 100)) mSymbolLayer.subSymbol().setColor(QColor(250, 150, 200)) self.assertEqual(mSymbolLayer.subSymbol().color(), QColor(250, 150, 200)) self.assertEqual(mSymbolLayer.color(), QColor(250, 150, 200))
def testQgsPointPatternFillSymbolLayerSld(self): """ Create a new style from a .sld file and match test """ # at the moment there is an empty createFromSld implementation # that return nulls mTestName = "QgsPointPatternFillSymbolLayer" mFilePath = QDir.toNativeSeparators("%s/symbol_layer/%s.sld" % (unitTestDataPath(), mTestName)) mDoc = QDomDocument(mTestName) mFile = QFile(mFilePath) mFile.open(QIODevice.ReadOnly) mDoc.setContent(mFile, True) mFile.close() mSymbolLayer = QgsPointPatternFillSymbolLayer.createFromSld( mDoc.elementsByTagName("PolygonSymbolizer").item(0).toElement() ) mExpectedValue = type(QgsPointPatternFillSymbolLayer()) mValue = type(mSymbolLayer) mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue) assert mExpectedValue == mValue, mMessage mExpectedValue = u"triangle" mValue = mSymbolLayer.subSymbol().symbolLayer(0).name() mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue) assert mExpectedValue == mValue, mMessage mExpectedValue = u"#ffaa00" mValue = mSymbolLayer.subSymbol().symbolLayer(0).color().name() mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue) assert mExpectedValue == mValue, mMessage mExpectedValue = u"#ff007f" mValue = mSymbolLayer.subSymbol().symbolLayer(0).borderColor().name() mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue) assert mExpectedValue == mValue, mMessage mExpectedValue = 5 mValue = mSymbolLayer.subSymbol().symbolLayer(0).angle() mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue) assert mExpectedValue == mValue, mMessage mExpectedValue = 3 mValue = mSymbolLayer.subSymbol().symbolLayer(0).size() mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue) assert mExpectedValue == mValue, mMessage
def testQgsCentroidFillSymbolLayer(self): """ Create a new style from a .sld file and match test """ mTestName = 'QgsCentroidFillSymbolLayer' mFilePath = QDir.toNativeSeparators('%s/symbol_layer/%s.sld' % (unitTestDataPath(), mTestName)) mDoc = QDomDocument(mTestName) mFile = QFile(mFilePath) mFile.open(QIODevice.ReadOnly) mDoc.setContent(mFile, True) mFile.close() mSymbolLayer = QgsCentroidFillSymbolLayer.createFromSld( mDoc.elementsByTagName('PointSymbolizer').item(0).toElement()) mExpectedValue = type(QgsCentroidFillSymbolLayer()) mValue = type(mSymbolLayer) mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue) assert mExpectedValue == mValue, mMessage mExpectedValue = QgsSimpleMarkerSymbolLayerBase.Star mValue = mSymbolLayer.subSymbol().symbolLayer(0).shape() mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue) assert mExpectedValue == mValue, mMessage mExpectedValue = '#55aaff' mValue = mSymbolLayer.subSymbol().symbolLayer(0).color().name() mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue) assert mExpectedValue == mValue, mMessage mExpectedValue = '#00ff00' mValue = mSymbolLayer.subSymbol().symbolLayer(0).strokeColor().name() mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue) assert mExpectedValue == mValue, mMessage mExpectedValue = False mValue = mSymbolLayer.pointOnAllParts() mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue) assert mExpectedValue == mValue, mMessage # test colors, need to make sure colors are passed/retrieved from subsymbol mSymbolLayer.setColor(QColor(150, 50, 100)) self.assertEqual(mSymbolLayer.color(), QColor(150, 50, 100)) self.assertEqual(mSymbolLayer.subSymbol().color(), QColor(150, 50, 100)) mSymbolLayer.subSymbol().setColor(QColor(250, 150, 200)) self.assertEqual(mSymbolLayer.subSymbol().color(), QColor(250, 150, 200)) self.assertEqual(mSymbolLayer.color(), QColor(250, 150, 200))
def testQgsEllipseSymbolLayerV2(self): """ Create a new style from a .sld file and match test """ mTestName = "QgsEllipseSymbolLayerV2" mFilePath = QDir.toNativeSeparators("%s/symbol_layer/%s.sld" % (unitTestDataPath(), mTestName)) mDoc = QDomDocument(mTestName) mFile = QFile(mFilePath) mFile.open(QIODevice.ReadOnly) mDoc.setContent(mFile, True) mFile.close() mSymbolLayer = QgsEllipseSymbolLayerV2.createFromSld( mDoc.elementsByTagName("PointSymbolizer").item(0).toElement() ) mExpectedValue = type(QgsEllipseSymbolLayerV2()) mValue = type(mSymbolLayer) mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue) assert mExpectedValue == mValue, mMessage mExpectedValue = u"circle" mValue = mSymbolLayer.symbolName() mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue) assert mExpectedValue == mValue, mMessage mExpectedValue = u"#ffff7f" mValue = mSymbolLayer.fillColor().name() mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue) assert mExpectedValue == mValue, mMessage mExpectedValue = u"#aaaaff" mValue = mSymbolLayer.outlineColor().name() mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue) assert mExpectedValue == mValue, mMessage mExpectedValue = 7 mValue = mSymbolLayer.symbolWidth() mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue) assert mExpectedValue == mValue, mMessage mExpectedValue = 5 mValue = mSymbolLayer.symbolHeight() mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue) assert mExpectedValue == mValue, mMessage
def testQgsFontMarkerSymbolLayerV2(self): """ Create a new style from a .sld file and match test """ mTestName = "QgsFontMarkerSymbolLayerV2" mFilePath = QDir.toNativeSeparators("%s/symbol_layer/%s.sld" % (unitTestDataPath(), mTestName)) mDoc = QDomDocument(mTestName) mFile = QFile(mFilePath) mFile.open(QIODevice.ReadOnly) mDoc.setContent(mFile, True) mFile.close() mSymbolLayer = QgsFontMarkerSymbolLayerV2.createFromSld( mDoc.elementsByTagName("PointSymbolizer").item(0).toElement() ) mExpectedValue = type(QgsFontMarkerSymbolLayerV2()) mValue = type(mSymbolLayer) mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue) assert mExpectedValue == mValue, mMessage mExpectedValue = u"Arial" mValue = mSymbolLayer.fontFamily() mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue) assert mExpectedValue == mValue, mMessage mExpectedValue = u"M" mValue = mSymbolLayer.character() mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue) assert mExpectedValue == mValue, mMessage mExpectedValue = 6.23 mValue = mSymbolLayer.size() mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue) assert mExpectedValue == mValue, mMessage mExpectedValue = 3 mValue = mSymbolLayer.angle() mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue) assert mExpectedValue == mValue, mMessage
def testQgsSimpleFillSymbolLayerV2(self): """Create a new style from a .sld file and match test. """ mTestName = "QgsSimpleFillSymbolLayerV2" mFilePath = QDir.toNativeSeparators("%s/symbol_layer/%s.sld" % (unitTestDataPath(), mTestName)) mDoc = QDomDocument(mTestName) mFile = QFile(mFilePath) mFile.open(QIODevice.ReadOnly) mDoc.setContent(mFile, True) mFile.close() mSymbolLayer = QgsSimpleFillSymbolLayerV2.createFromSld( mDoc.elementsByTagName("PolygonSymbolizer").item(0).toElement() ) mExpectedValue = type(QgsSimpleFillSymbolLayerV2()) mValue = type(mSymbolLayer) mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue) assert mExpectedValue == mValue, mMessage mExpectedValue = Qt.SolidPattern mValue = mSymbolLayer.brushStyle() mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue) assert mExpectedValue == mValue, mMessage mExpectedValue = u"#ffaa7f" mValue = mSymbolLayer.borderColor().name() mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue) assert mExpectedValue == mValue, mMessage mExpectedValue = Qt.DotLine mValue = mSymbolLayer.borderStyle() mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue) assert mExpectedValue == mValue, mMessage mExpectedValue = 0.26 mValue = mSymbolLayer.borderWidth() mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue) assert mExpectedValue == mValue, mMessage
def testQgsLinePatternFillSymbolLayer(self): """ Create a new style from a .sld file and match test """ mTestName = 'QgsLinePatternFillSymbolLayer' mFilePath = QDir.toNativeSeparators('%s/symbol_layer/%s.sld' % (unitTestDataPath(), mTestName)) mDoc = QDomDocument(mTestName) mFile = QFile(mFilePath) mFile.open(QIODevice.ReadOnly) mDoc.setContent(mFile, True) mFile.close() mSymbolLayer = QgsLinePatternFillSymbolLayer.createFromSld( mDoc.elementsByTagName('PolygonSymbolizer').item(0).toElement()) mExpectedValue = type(QgsLinePatternFillSymbolLayer()) mValue = type(mSymbolLayer) mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue) assert mExpectedValue == mValue, mMessage mExpectedValue = u'#ff55ff' mValue = mSymbolLayer.color().name() mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue) assert mExpectedValue == mValue, mMessage mExpectedValue = 1.5 mValue = mSymbolLayer.lineWidth() mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue) assert mExpectedValue == mValue, mMessage mExpectedValue = 4 mValue = mSymbolLayer.distance() mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue) assert mExpectedValue == mValue, mMessage mExpectedValue = 57 mValue = mSymbolLayer.lineAngle() mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue) assert mExpectedValue == mValue, mMessage
def testQgsFontMarkerSymbolLayer(self): """ Create a new style from a .sld file and match test """ mTestName = 'QgsFontMarkerSymbolLayer' mFilePath = QDir.toNativeSeparators('%s/symbol_layer/%s.sld' % (unitTestDataPath(), mTestName)) mDoc = QDomDocument(mTestName) mFile = QFile(mFilePath) mFile.open(QIODevice.ReadOnly) mDoc.setContent(mFile, True) mFile.close() mSymbolLayer = QgsFontMarkerSymbolLayer.createFromSld( mDoc.elementsByTagName('PointSymbolizer').item(0).toElement()) mExpectedValue = type(QgsFontMarkerSymbolLayer()) mValue = type(mSymbolLayer) mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue) assert mExpectedValue == mValue, mMessage mExpectedValue = 'Arial' mValue = mSymbolLayer.fontFamily() mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue) assert mExpectedValue == mValue, mMessage mExpectedValue = "M" mValue = mSymbolLayer.character() mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue) assert mExpectedValue == mValue, mMessage mExpectedValue = 6.23 mValue = mSymbolLayer.size() mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue) assert mExpectedValue == mValue, mMessage mExpectedValue = 3 mValue = mSymbolLayer.angle() mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue) assert mExpectedValue == mValue, mMessage
def testQgsSimpleFillSymbolLayer(self): """Create a new style from a .sld file and match test. """ mTestName = 'QgsSimpleFillSymbolLayer' mFilePath = QDir.toNativeSeparators('%s/symbol_layer/%s.sld' % (unitTestDataPath(), mTestName)) mDoc = QDomDocument(mTestName) mFile = QFile(mFilePath) mFile.open(QIODevice.ReadOnly) mDoc.setContent(mFile, True) mFile.close() mSymbolLayer = QgsSimpleFillSymbolLayer.createFromSld( mDoc.elementsByTagName('PolygonSymbolizer').item(0).toElement()) mExpectedValue = type(QgsSimpleFillSymbolLayer()) mValue = type(mSymbolLayer) mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue) assert mExpectedValue == mValue, mMessage mExpectedValue = Qt.SolidPattern mValue = mSymbolLayer.brushStyle() mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue) assert mExpectedValue == mValue, mMessage mExpectedValue = '#ffaa7f' mValue = mSymbolLayer.strokeColor().name() mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue) assert mExpectedValue == mValue, mMessage mExpectedValue = Qt.DotLine mValue = mSymbolLayer.strokeStyle() mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue) assert mExpectedValue == mValue, mMessage mExpectedValue = 0.26 mValue = mSymbolLayer.strokeWidth() mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue) assert mExpectedValue == mValue, mMessage
def _reply_finished(self, reply: QNetworkReply): """ Triggered when a reply is finished """ self.button_refresh_contributors.setEnabled(True) content = reply.readAll() if not content: return doc = QDomDocument() doc.setContent(content) contributor_elements = doc.elementsByTagName('Contributor') contributors = [] for e in range(contributor_elements.length()): contributor_element = contributor_elements.at(e).toElement() contributors.append(contributor_element.text()) SERVICE_MANAGER.set_contributors(self.service_type, self.service_id, contributors) self._update_contributor_list(contributors)
def testQgsSvgMarkerSymbolLayer(self): """ Create a new style from a .sld file and match test """ mTestName = 'QgsSvgMarkerSymbolLayer' mFilePath = QDir.toNativeSeparators('%s/symbol_layer/%s.sld' % (unitTestDataPath(), mTestName)) mDoc = QDomDocument(mTestName) mFile = QFile(mFilePath) mFile.open(QIODevice.ReadOnly) mDoc.setContent(mFile, True) mFile.close() mSymbolLayer = QgsSvgMarkerSymbolLayer.createFromSld( mDoc.elementsByTagName('PointSymbolizer').item(0).toElement()) mExpectedValue = type(QgsSvgMarkerSymbolLayer()) mValue = type(mSymbolLayer) mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue) assert mExpectedValue == mValue, mMessage mExpectedValue = 'skull.svg' mValue = os.path.basename(mSymbolLayer.path()) print(("VALUE", mSymbolLayer.path())) mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue) assert mExpectedValue == mValue, mMessage mExpectedValue = 12 mValue = mSymbolLayer.size() mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue) assert mExpectedValue == mValue, mMessage mExpectedValue = 45 mValue = mSymbolLayer.angle() mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue) assert mExpectedValue == mValue, mMessage
class EntityImporter(): """ class constructor """ def __init__(self, instance): """ Initialize variables """ self.instance = instance self.instance_doc = QDomDocument() self.set_instance_document(self.instance) self.key_watch = 0 def set_instance_document(self, file_p): """ :param file_p: str :return: file :rtype QFile """ file_path = QFile(file_p) if file_path.open(QIODevice.ReadOnly): self.instance_doc.setContent(file_path) def entity_attributes_from_instance(self, entity): """ Get particular entity attributes from the instance document param: table short_name type: string return: table column name and column data :rtype: dictionary """ attributes = {} nodes = self.instance_doc.elementsByTagName(entity) entity_nodes = nodes.item(0).childNodes() if entity_nodes: for j in range(entity_nodes.count()): node_val = entity_nodes.item(j).toElement() attributes[node_val.nodeName()] = node_val.text().rstrip() return attributes def social_tenure_definition_captured(self): """ Let find find out if str is defined for the particular data collection file instance. if exist, bool the result :return: """ has_str_defined = False try: attributes = self.entity_attributes_from_instance('social_tenure') if attributes is not None or len(attributes) > 0: has_str_defined = True except: pass return has_str_defined def process_social_tenure(self, attributes, ids): """ Save social tenure entity. It has to be saved separately because its need to be saved last and its handled differently :return: """ if attributes and ids: entity_add = Save2DB('social_tenure', attributes, ids) entity_add.objects_from_supporting_doc(self.instance) entity_add.save_to_db()
class ConfigurationUtils(): PROFILE = 'Profile' SOCIAL_TENURE = 'SocialTenure' CONFIGURATION = 'Configuration' def __init__(self, document): """ A utility class for STDM configuration. :param document: The configuration :type document: QDomDocument """ self.file_handler = FilePaths() self.log_file_path = '{}/logs/migration.log'.format( self.file_handler.localPath() ) self.document = document def append_log(self, info): """ Append info to a single file :param info: update information to save to file :type info: str """ info_file = open(self.log_file_path, "a") time_stamp = datetime.datetime.now().strftime( '%d-%m-%Y %H:%M:%S' ) info_file.write('\n') info_file.write('{} - '.format(time_stamp)) info_file.write(info) info_file.write('\n') info_file.close() def check_config_file_exists(self, config_file): """ Checks if config file exists :returns True if folder exists else False :rtype bool """ if os.path.isfile(os.path.join( self.file_handler.localPath(), config_file) ): return True else: return False def read_stc(self, config_file_name): """ Reads provided config file :returns QDomDocument, QDomDocument.documentElement() :rtype tuple """ config_file_path = os.path.join( self.file_handler.localPath(), config_file_name ) config_file_path = QFile(config_file_path) config_file = os.path.basename(config_file_name) if self.check_config_file_exists(config_file): self.document = QDomDocument() status, msg, line, col = self.document.setContent(config_file_path) if not status: error_message = 'Configuration file cannot be loaded: {0}'. \ format(msg) self.append_log(str(error_message)) raise ConfigurationException(error_message) self.doc_element = self.document.documentElement() def find_node(self, name): """ Get nodes inside a document by a tag name. :param document: The xml document :type document: QDomDocument :param name: the tag name :type name: String :return: The nodes list :rtype: List """ node_list = self.document.elementsByTagName(name) nodes = [] for i in range(node_list.length()): node = node_list.item(i) nodes.append(node) return nodes def add_attribute_to_nodes(self, nodes, attr, value): """ Adds an attribute with value to node lists. :param nodes: List of nodes :type nodes: QNodeList :param attr: The attribute text :type attr: String :param value: The value of the attribute. :type value: String :return: :rtype: """ for node in nodes: element = node.toElement() element.setAttribute(attr, value) def add_attribute_by_node_name(self, node_name, attr, value): """ Add attribute with value to nodes by node name. :param node_name: The name of the node. :type node_name: Strong :param attr: The attribute text :type attr: String :param value: The value of the attribute. :type value: String :return: :rtype: """ nodes = self.find_node(node_name) self.add_attribute_to_nodes(nodes, attr, value) def profile_first_child(self, tag_name): """ Gets the first child of profile node with a specified tag name. :param tag_name: The tag name to be used to search the child. :type tag_name: String :return: Dictionary of parent (profile node) and the child element. :rtype: OrderedDict """ profile_nodes = self.find_node(self.PROFILE) first_child = OrderedDict() for profile_node in profile_nodes: profile_child = profile_node.firstChildElement( tag_name ) first_child[profile_node] = profile_child return first_child def social_tenure_elements(self): """ Get all social tenure element in a dom_document. :return: List of social tenure element :rtype: OrderedDict """ social_tenure_nodes = self.profile_first_child( self.SOCIAL_TENURE ) return social_tenure_nodes def run(self): nodes = self.find_node('Entity') self.add_attribute_to_nodes(nodes, 'Test', 'One')
def xmlDownloaded(self): """ populate the plugins object with the fetched data """ reply = self.sender() reposName = reply.property('reposName') if reply.error() != QNetworkReply.NoError: # fetching failed self.mRepositories[reposName]["state"] = 3 self.mRepositories[reposName]["error"] = reply.errorString() if reply.error() == QNetworkReply.OperationCanceledError: self.mRepositories[reposName]["error"] += "\n\n" + QCoreApplication.translate("QgsPluginInstaller", "If you haven't canceled the download manually, it was most likely caused by a timeout. In this case consider increasing the connection timeout value in QGIS options window.") elif reply.attribute(QNetworkRequest.HttpStatusCodeAttribute) == 301: redirectionUrl = reply.attribute(QNetworkRequest.RedirectionTargetAttribute) if redirectionUrl.isRelative(): redirectionUrl = reply.url().resolved(redirectionUrl) redirectionCounter = reply.property('redirectionCounter') + 1 if redirectionCounter > 4: self.mRepositories[reposName]["state"] = 3 self.mRepositories[reposName]["error"] = QCoreApplication.translate("QgsPluginInstaller", "Too many redirections") else: # Fire a new request and exit immediately in order to quietly destroy the old one self.requestFetching(reposName, redirectionUrl, redirectionCounter) reply.deleteLater() return else: reposXML = QDomDocument() content = reply.readAll() # Fix lonely ampersands in metadata a = QByteArray() a.append("& ") b = QByteArray() b.append("& ") content = content.replace(a, b) reposXML.setContent(content) pluginNodes = reposXML.elementsByTagName("pyqgis_plugin") if pluginNodes.size(): for i in range(pluginNodes.size()): fileName = pluginNodes.item(i).firstChildElement("file_name").text().strip() if not fileName: fileName = QFileInfo(pluginNodes.item(i).firstChildElement("download_url").text().strip().split("?")[0]).fileName() name = fileName.partition(".")[0] experimental = False if pluginNodes.item(i).firstChildElement("experimental").text().strip().upper() in ["TRUE", "YES"]: experimental = True deprecated = False if pluginNodes.item(i).firstChildElement("deprecated").text().strip().upper() in ["TRUE", "YES"]: deprecated = True trusted = False if pluginNodes.item(i).firstChildElement("trusted").text().strip().upper() in ["TRUE", "YES"]: trusted = True icon = pluginNodes.item(i).firstChildElement("icon").text().strip() if icon and not icon.startswith("http"): icon = "http://{}/{}".format(QUrl(self.mRepositories[reposName]["url"]).host(), icon) if pluginNodes.item(i).toElement().hasAttribute("plugin_id"): plugin_id = pluginNodes.item(i).toElement().attribute("plugin_id") else: plugin_id = None plugin = { "id": name, "plugin_id": plugin_id, "name": pluginNodes.item(i).toElement().attribute("name"), "version_available": pluginNodes.item(i).toElement().attribute("version"), "description": pluginNodes.item(i).firstChildElement("description").text().strip(), "about": pluginNodes.item(i).firstChildElement("about").text().strip(), "author_name": pluginNodes.item(i).firstChildElement("author_name").text().strip(), "homepage": pluginNodes.item(i).firstChildElement("homepage").text().strip(), "download_url": pluginNodes.item(i).firstChildElement("download_url").text().strip(), "category": pluginNodes.item(i).firstChildElement("category").text().strip(), "tags": pluginNodes.item(i).firstChildElement("tags").text().strip(), "changelog": pluginNodes.item(i).firstChildElement("changelog").text().strip(), "author_email": pluginNodes.item(i).firstChildElement("author_email").text().strip(), "tracker": pluginNodes.item(i).firstChildElement("tracker").text().strip(), "code_repository": pluginNodes.item(i).firstChildElement("repository").text().strip(), "downloads": pluginNodes.item(i).firstChildElement("downloads").text().strip(), "average_vote": pluginNodes.item(i).firstChildElement("average_vote").text().strip(), "rating_votes": pluginNodes.item(i).firstChildElement("rating_votes").text().strip(), "icon": icon, "experimental": experimental, "deprecated": deprecated, "trusted": trusted, "filename": fileName, "installed": False, "available": True, "status": "not installed", "error": "", "error_details": "", "version_installed": "", "zip_repository": reposName, "library": "", "readonly": False } qgisMinimumVersion = pluginNodes.item(i).firstChildElement("qgis_minimum_version").text().strip() if not qgisMinimumVersion: qgisMinimumVersion = "2" qgisMaximumVersion = pluginNodes.item(i).firstChildElement("qgis_maximum_version").text().strip() if not qgisMaximumVersion: qgisMaximumVersion = qgisMinimumVersion[0] + ".99" # if compatible, add the plugin to the list if not pluginNodes.item(i).firstChildElement("disabled").text().strip().upper() in ["TRUE", "YES"]: if isCompatible(pyQgisVersion(), qgisMinimumVersion, qgisMaximumVersion): # add the plugin to the cache plugins.addFromRepository(plugin) self.mRepositories[reposName]["state"] = 2 else: # no plugin metadata found self.mRepositories[reposName]["state"] = 3 if reply.attribute(QNetworkRequest.HttpStatusCodeAttribute) == 200: self.mRepositories[reposName]["error"] = QCoreApplication.translate("QgsPluginInstaller", "Server response is 200 OK, but doesn't contain plugin metatada. This is most likely caused by a proxy or a wrong repository URL. You can configure proxy settings in QGIS options.") else: self.mRepositories[reposName]["error"] = QCoreApplication.translate("QgsPluginInstaller", "Status code:") + " {} {}".format( reply.attribute(QNetworkRequest.HttpStatusCodeAttribute), reply.attribute(QNetworkRequest.HttpReasonPhraseAttribute) ) self.repositoryFetched.emit(reposName) # is the checking done? if not self.fetchingInProgress(): self.checkingDone.emit() reply.deleteLater()
def parse_wadl( content: QByteArray, # pylint:disable=too-many-locals,too-many-branches,too-many-statements service_type: str, wadl_url: str) -> Dict: """ Parses a WADL document and converts to a service configuration """ doc = QDomDocument() doc.setContent(content) resources_elements = doc.elementsByTagName('resources') assert resources_elements.length() == 1 resources_element = resources_elements.at(0).toElement() query_element = None request_element = None resource_elements = resources_element.elementsByTagName('resource') for e in range(resource_elements.length()): resource_element = resource_elements.at(e).toElement() method_element = resource_element.firstChildElement( 'method').toElement() if method_element.isNull(): continue request_element = method_element.firstChildElement( 'request').toElement() if request_element.isNull(): continue query_element = resource_element break assert query_element assert not request_element.isNull() param_elements = request_element.elementsByTagName('param') min_latitude = None max_latitude = None min_longitude = None max_longitude = None settings = {} if service_type != ServiceManager.FDSNSTATION: settings = { v: False for _, v in WadlServiceParser.PARAM_MAP.items() } for e in range(param_elements.length()): param_element = param_elements.at(e).toElement() param_name = param_element.attribute('name') if param_name in WadlServiceParser.PARAM_MAP: mapped_name = WadlServiceParser.PARAM_MAP[param_name] if mapped_name in settings: settings[mapped_name] = True continue if param_name == 'minlatitude': min_latitude = float(param_element.attribute( 'default', '-180')) elif param_name == 'maxlatitude': max_latitude = float(param_element.attribute('default', '180')) elif param_name == 'minlongitude': min_longitude = float(param_element.attribute( 'default', '-90')) elif param_name == 'maxlongitude': max_longitude = float(param_element.attribute('default', '90')) elif param_name == 'format': option_elements = param_element.elementsByTagName('option') for o in range(option_elements.length()): option_element = option_elements.at(o).toElement() option_name = option_element.attribute('value') if option_name in WadlServiceParser.PARAM_MAP: mapped_name = WadlServiceParser.PARAM_MAP[option_name] if mapped_name in settings: settings[mapped_name] = True continue endpoint = resources_element.attribute('base') if not endpoint.endswith('/'): endpoint += '/' if endpoint.startswith('/'): base_url = wadl_url[:wadl_url.index('/', wadl_url.index(':') + 3)] endpoint = base_url + endpoint resource_path = resource_element.attribute('path') + "?" if resource_path.startswith('/'): resource_path = resource_path[1:] endpoint += resource_path return { "endpointurl": endpoint, "boundingbox": [ min_longitude if min_longitude is not None else -180, min_latitude if min_latitude is not None else -90, max_longitude if max_longitude is not None else 180, max_latitude if max_latitude is not None else 90 ], "settings": settings }
def xmlDownloaded(self): """ populate the plugins object with the fetched data """ reply = self.sender() reposName = reply.property('reposName') if reply.error() != QNetworkReply.NoError: # fetching failed self.mRepositories[reposName]["state"] = 3 self.mRepositories[reposName]["error"] = reply.errorString() if reply.error() == QNetworkReply.OperationCanceledError: self.mRepositories[reposName][ "error"] += "\n\n" + QCoreApplication.translate( "QgsPluginInstaller", "If you haven't canceled the download manually, it was most likely caused by a timeout. In this case consider increasing the connection timeout value in QGIS options window." ) elif reply.attribute(QNetworkRequest.HttpStatusCodeAttribute) == 301: redirectionUrl = reply.attribute( QNetworkRequest.RedirectionTargetAttribute) if redirectionUrl.isRelative(): redirectionUrl = reply.url().resolved(redirectionUrl) redirectionCounter = reply.property('redirectionCounter') + 1 if redirectionCounter > 4: self.mRepositories[reposName]["state"] = 3 self.mRepositories[reposName][ "error"] = QCoreApplication.translate( "QgsPluginInstaller", "Too many redirections") else: # Fire a new request and exit immediately in order to quietly destroy the old one self.requestFetching(reposName, redirectionUrl, redirectionCounter) reply.deleteLater() return else: reposXML = QDomDocument() content = reply.readAll() # Fix lonely ampersands in metadata a = QByteArray() a.append("& ") b = QByteArray() b.append("& ") content = content.replace(a, b) reposXML.setContent(content) pluginNodes = reposXML.elementsByTagName("pyqgis_plugin") if pluginNodes.size(): for i in range(pluginNodes.size()): fileName = pluginNodes.item(i).firstChildElement( "file_name").text().strip() if not fileName: fileName = QFileInfo( pluginNodes.item(i).firstChildElement( "download_url").text().strip().split("?") [0]).fileName() name = fileName.partition(".")[0] experimental = False if pluginNodes.item(i).firstChildElement( "experimental").text().strip().upper() in [ "TRUE", "YES" ]: experimental = True deprecated = False if pluginNodes.item(i).firstChildElement( "deprecated").text().strip().upper() in [ "TRUE", "YES" ]: deprecated = True trusted = False if pluginNodes.item(i).firstChildElement( "trusted").text().strip().upper() in [ "TRUE", "YES" ]: trusted = True icon = pluginNodes.item(i).firstChildElement( "icon").text().strip() if icon and not icon.startswith("http"): icon = "http://{}/{}".format( QUrl(self.mRepositories[reposName]["url"]).host(), icon) if pluginNodes.item(i).toElement().hasAttribute( "plugin_id"): plugin_id = pluginNodes.item(i).toElement().attribute( "plugin_id") else: plugin_id = None plugin = { "id": name, "plugin_id": plugin_id, "name": pluginNodes.item(i).toElement().attribute("name"), "version_available": pluginNodes.item(i).toElement().attribute("version"), "description": pluginNodes.item(i).firstChildElement( "description").text().strip(), "about": pluginNodes.item(i).firstChildElement( "about").text().strip(), "author_name": pluginNodes.item(i).firstChildElement( "author_name").text().strip(), "homepage": pluginNodes.item(i).firstChildElement( "homepage").text().strip(), "download_url": pluginNodes.item(i).firstChildElement( "download_url").text().strip(), "category": pluginNodes.item(i).firstChildElement( "category").text().strip(), "tags": pluginNodes.item(i).firstChildElement( "tags").text().strip(), "changelog": pluginNodes.item(i).firstChildElement( "changelog").text().strip(), "author_email": pluginNodes.item(i).firstChildElement( "author_email").text().strip(), "tracker": pluginNodes.item(i).firstChildElement( "tracker").text().strip(), "code_repository": pluginNodes.item(i).firstChildElement( "repository").text().strip(), "downloads": pluginNodes.item(i).firstChildElement( "downloads").text().strip(), "average_vote": pluginNodes.item(i).firstChildElement( "average_vote").text().strip(), "rating_votes": pluginNodes.item(i).firstChildElement( "rating_votes").text().strip(), "icon": icon, "experimental": experimental, "deprecated": deprecated, "trusted": trusted, "filename": fileName, "installed": False, "available": True, "status": "not installed", "error": "", "error_details": "", "version_installed": "", "zip_repository": reposName, "library": "", "readonly": False } qgisMinimumVersion = pluginNodes.item(i).firstChildElement( "qgis_minimum_version").text().strip() if not qgisMinimumVersion: qgisMinimumVersion = "2" qgisMaximumVersion = pluginNodes.item(i).firstChildElement( "qgis_maximum_version").text().strip() if not qgisMaximumVersion: qgisMaximumVersion = qgisMinimumVersion[0] + ".99" # if compatible, add the plugin to the list if not pluginNodes.item(i).firstChildElement( "disabled").text().strip().upper() in [ "TRUE", "YES" ]: if isCompatible(pyQgisVersion(), qgisMinimumVersion, qgisMaximumVersion): # add the plugin to the cache plugins.addFromRepository(plugin) self.mRepositories[reposName]["state"] = 2 else: # no plugin metadata found self.mRepositories[reposName]["state"] = 3 if reply.attribute( QNetworkRequest.HttpStatusCodeAttribute) == 200: self.mRepositories[reposName][ "error"] = QCoreApplication.translate( "QgsPluginInstaller", "Server response is 200 OK, but doesn't contain plugin metatada. This is most likely caused by a proxy or a wrong repository URL. You can configure proxy settings in QGIS options." ) else: self.mRepositories[reposName][ "error"] = QCoreApplication.translate( "QgsPluginInstaller", "Status code:") + " {} {}".format( reply.attribute( QNetworkRequest.HttpStatusCodeAttribute), reply.attribute( QNetworkRequest.HttpReasonPhraseAttribute)) self.repositoryFetched.emit(reposName) # is the checking done? if not self.fetchingInProgress(): self.checkingDone.emit() reply.deleteLater()
cfg = layer.editFormConfig().widgetConfig(idx) for key in cfg.keys(): trans = get_table_translation(cur, cfg[key]) if trans: cfg[trans] = cfg[key] del cfg[key] layer.editFormConfig().setWidgetConfig(idx, cfg) # update styles from other project if 'style_file' in config_data: errMsg = '' file = QFile(config_data['style_file']) file.open(QFile.ReadOnly | QFile.Text) doc = QDomDocument() doc.setContent(file) root = doc.elementsByTagName('qgis.custom.style') nodes = root.at(0).childNodes() for i in range(0, nodes.count()): elem = nodes.at(i).toElement() if elem.tagName() != 'layer' or not elem.hasAttribute('id'): continue layer_id = elem.attribute('id') if layer_id not in style_layer_ids: print('skipping ', layer_id) layer = QgsProject.instance().mapLayer(layer_id) if not layer: print('layer not found', layer_id) continue print('loading', layer_id) style = elem.firstChild() style.removeChild(style.firstChildElement('edittypes'))
def load(self): repoUrl = pluginSetting('repoUrl') repoPath = os.path.abspath(repoUrl) repoFile = os.path.join(repoPath, 'plugins.xml') repoXML = QDomDocument() with codecs.open(repoFile, 'r', encoding='utf-8') as f: content = f.read() repoXML.setContent(content) pluginNodes = repoXML.elementsByTagName('pyqgis_plugin') if pluginNodes.size(): for i in range(pluginNodes.size()): fileName = pluginNodes.item(i).firstChildElement('file_name').text().strip() if not fileName: fileName = QFileInfo(pluginNodes.item(i).firstChildElement('download_url').text().strip().split('?')[0]).fileName() name = fileName.partition('.')[0] experimental = False if pluginNodes.item(i).firstChildElement('experimental').text().strip().upper() in ['TRUE', 'YES']: experimental = True deprecated = False if pluginNodes.item(i).firstChildElement('deprecated').text().strip().upper() in ['TRUE', 'YES']: deprecated = True icon = pluginNodes.item(i).firstChildElement('icon').text().strip() if pluginNodes.item(i).toElement().hasAttribute('plugin_id'): plugin_id = pluginNodes.item(i).toElement().attribute('plugin_id') else: plugin_id = None plugin = { 'id': name, 'plugin_id': plugin_id, 'name': pluginNodes.item(i).toElement().attribute('name'), 'version_available': pluginNodes.item(i).toElement().attribute('version'), 'description': pluginNodes.item(i).firstChildElement('description').text().strip(), 'about': pluginNodes.item(i).firstChildElement('about').text().strip(), 'author_name': pluginNodes.item(i).firstChildElement('author_name').text().strip(), 'homepage': pluginNodes.item(i).firstChildElement('homepage').text().strip(), 'download_url': 'file:///{}'.format(os.path.join(repoPath, fileName)), 'category': pluginNodes.item(i).firstChildElement('category').text().strip(), 'tags': pluginNodes.item(i).firstChildElement('tags').text().strip(), 'changelog': pluginNodes.item(i).firstChildElement('changelog').text().strip(), 'author_email': pluginNodes.item(i).firstChildElement('author_email').text().strip(), 'tracker': pluginNodes.item(i).firstChildElement('tracker').text().strip(), 'code_repository': pluginNodes.item(i).firstChildElement('repository').text().strip(), 'downloads': pluginNodes.item(i).firstChildElement('downloads').text().strip(), 'average_vote': pluginNodes.item(i).firstChildElement('average_vote').text().strip(), 'rating_votes': pluginNodes.item(i).firstChildElement('rating_votes').text().strip(), 'icon': icon, 'experimental': experimental, 'deprecated': deprecated, 'filename': fileName, 'installed': False, 'available': True, 'status': 'not installed', 'error': '', 'error_details': '', 'version_installed': '', "zip_repository": boundlessRepoName, 'library': '', 'readonly': False } qgisMinimumVersion = pluginNodes.item(i).firstChildElement('qgis_minimum_version').text().strip() if not qgisMinimumVersion: qgisMinimumVersion = '2' qgisMaximumVersion = pluginNodes.item(i).firstChildElement('qgis_maximum_version').text().strip() if not qgisMaximumVersion: qgisMaximumVersion = qgisMinimumVersion[0] + '.99' # If compatible, add the plugin to the list if not pluginNodes.item(i).firstChildElement('disabled').text().strip().upper() in ['TRUE', 'YES']: if isCompatible(QGis.QGIS_VERSION, qgisMinimumVersion, qgisMaximumVersion): # Add the plugin to the cache repo = boundlessRepoName try: self.repoCache[repo] += [plugin] except: self.repoCache[repo] = [plugin]
class InstanceUUIDExtractor(): """ Class constructor """ def __init__(self, path): """ Initatlize class variables """ self.file_path = path self.file = None self.new_list = [] self.doc = QDomDocument() self.node = QDomNode() def set_file_path(self, path): """ Update the path based on the new file being read :param path: :return: """ self.file_path = path def unset_path(self): """Clear the current document path""" self.file_path = None def set_document(self): """ :return: """ self.file = QFile(self.file_path) if self.file.open(QIODevice.ReadOnly): self.doc.setContent(self.file) self.file.close() def update_document(self): '''Update the current instance by clearing the document in the cache ''' self.doc.clear() self.set_document() def on_file_passed(self): """ Pass the raw file to an xml document object and format the its filename to GeoODK standards :return: """ try: self.set_document() self.read_uuid_element() self.doc.clear() self.file.close() self.rename_file() except: pass def read_uuid_element(self): """ get the uuid element and text from the xml document from the mobile divice """ node = self.doc.elementsByTagName("meta") for i in range(node.count()): node = node.item(i).firstChild().toElement() self.node = node.text() return self.node def document_entities(self, profile): """ Get entities in the document :return: """ self.set_document() node_list = [] nodes = self.doc.elementsByTagName(profile) node = nodes.item(0).childNodes() if node: for j in range(node.count()): node_val = node.item(j) node_list.append(node_val.nodeName()) return node_list def profile_entity_nodes(self, profile): ''' Fetch and return QDomNodeList for entities of a profile :rtype: QDomNodeList ''' self.set_document() nodes = self.doc.elementsByTagName(profile) return nodes.item(0).childNodes() def document_entities_with_data(self, profile, selected_entities): """ Get entities in the dom document matching user selected entities :rtype: OrderedDict """ instance_data = OrderedDict() self.set_document() nodes = self.doc.elementsByTagName(profile) entity_nodes = nodes.item(0).childNodes() for attrs in range(entity_nodes.count()): if entity_nodes.item(attrs).nodeName() in selected_entities: name_entity = entity_nodes.item(attrs).nodeName() attr_nodes = self.doc.elementsByTagName(name_entity) instance_data[attr_nodes] = name_entity return instance_data def attribute_data_from_nodelist(self, args_list): """ process nodelist data before Importing attribute data into db """ repeat_instance_data = OrderedDict() attribute_data = OrderedDict() for attr_nodes, entity in args_list.items(): '''The assuption is that there are repeated entities from mobile sub forms. handle them separately''' if attr_nodes.count() > 1: for i in range(attr_nodes.count()): attrib_node = attr_nodes.at(i).childNodes() attr_list = OrderedDict() for j in range(attrib_node.count()): field_name = attrib_node.at(j).nodeName() field_value = attrib_node.at(j).toElement().text() attr_list[field_name] = field_value repeat_instance_data['{}'.format(i) + entity] = attr_list else: '''Entities must appear onces in the form''' node_list_var = OrderedDict() attr_node = attr_nodes.at(0).childNodes() for j in range(attr_node.count()): field_name = attr_node.at(j).nodeName() field_value = attr_node.at(j).toElement().text() node_list_var[field_name] = field_value attribute_data[entity] = node_list_var return attribute_data, repeat_instance_data def read_attribute_data_from_node(self, node, entity_name): """Read attribute data from a node item""" node_list_var = OrderedDict() attributes = OrderedDict() attr_node = node.at(0).childNodes() for j in range(attr_node.count()): field_name = attr_node.at(j).nodeName() field_value = attr_node.at(j).toElement().text() node_list_var[field_name] = field_value attributes[entity_name] = node_list_var return attributes def str_definition(self, instance=None): """ Check if the instance file has entry social tenure :return: """ if instance: self.set_file_path(instance) self.set_document() attributes = {} nodes = self.doc.elementsByTagName('social_tenure') entity_nodes = nodes.item(0).childNodes() if entity_nodes: for j in range(entity_nodes.count()): node_val = entity_nodes.item(j).toElement() attributes[node_val.nodeName()] = node_val.text().rstrip() return attributes def has_str_captured_in_instance(self, instance): """ Bool if the str inclusion is required based on whether is captured or not :return: """ count = len(self.str_definition(instance)) return True if count > 1 else False def entity_atrributes(self): """ Get collected data from the entity in the document :return: """ pass def uuid_element(self): """ Format the guuid from the file :return: """ return self.node.replace(":", "") def rename_file(self): """ Remane the existing instance file with Guuid from the mobile divice to conform with GeoODk naming convention :return: """ if isinstance(self.file, QFile): dir_n, file_n = os.path.split(self.file_path) os.chdir(dir_n) if not file_n.startswith(UUID): new_file_name = self.uuid_element() + ".xml" isrenamed = self.file.setFileName(new_file_name) os.rename(file_n, new_file_name) self.new_list.append(new_file_name) return isrenamed else: self.new_list.append(self.file.fileName()) self.file.close() else: return def file_list(self): """ check through the list of document to ensure they are complete file path """ complete_file = [] for fi in self.new_list: if os.path.isfile(fi): complete_file.append(fi) else: continue return complete_file def close_document(self): '''Close all the open documents and unset current paths''' self.file_path = None self.doc.clear() self.new_list = None
def processAlgorithm(self, parameters, context, feedback): output = {self.OUTPUT_STATUS: 0, self.OUTPUT_STRING: ''} # Parameters connection_name_central = parameters[self.CONNECTION_NAME_CENTRAL] # store parameters ls = lizsyncConfig() ls.setVariable('postgresql:central/name', connection_name_central) ls.save() # Get current project file project = context.project() input_path = project.absoluteFilePath() output_path = input_path.replace('.qgs', '_mobile.qgs') output_directory = project.baseName() + '_mobile/' # Save to new file feedback.pushInfo(tr('Save mobile project')) if os.path.isfile(output_path): os.remove(output_path) try: shutil.copy(input_path, output_path) except IOError as e: msg = tr('Unable to copy the current project file') msg += ' ' + e raise QgsProcessingException(msg) except Exception as e: msg = tr('Unexpected error') + ' ' + sys.exc_info() msg += ' ' + e raise QgsProcessingException(msg) feedback.pushInfo(tr('* Mobile project saved')) feedback.pushInfo('') # Read mobile project file as XML feedback.pushInfo(tr('Read XML from saved project')) content = None with open(input_path, 'r') as f: content = f.read() dom = QDomDocument() dom.setContent(content) feedback.pushInfo(tr('* XML successfully read')) feedback.pushInfo('') # Get layers and layers id pg_layers = self.parameterAsLayerList(parameters, self.PG_LAYERS, context) pg_layers = [ layer for layer in pg_layers if layer.providerType() == 'postgres' ] pg_ids = [layer.id() for layer in pg_layers] pg_changed = [] gpkg_layers = self.parameterAsLayerList(parameters, self.GPKG_LAYERS, context) gpkg_ids = [layer.id() for layer in gpkg_layers] gpkg_changed = [] # Loop for each layer and change datasource if needed feedback.pushInfo( tr('Change the datasource of layers to make the QGIS project portable' )) nodelist = dom.elementsByTagName('maplayer') for node in (nodelist.at(i) for i in range(nodelist.count())): # Get layer id, name, datasource and provider layerid = node.firstChildElement('id').text() layername = node.firstChildElement('layername').text() datasource = node.firstChildElement('datasource').text() # PostgreSQL if layerid in pg_ids: # Replace datasource by field localhost datasource new_source, msg = self.replacePostgresqlDatasource( connection_name_central, datasource, layername) if not new_source: raise QgsProcessingException(msg) if new_source != datasource: node.firstChildElement( 'datasource').firstChild().setNodeValue(new_source) # Add to the list pg_changed.append(layername) # GeoPackage # We do not change the datasource for PostgreSQL layers chosen for editing # To avoid misconfiguration if layerid in gpkg_ids and layerid not in pg_ids: # Replace datasource with the geopackage file path and layer name new_source = './{}/layers.gpkg|layername={}'.format( output_directory, layername) node.firstChildElement('datasource').firstChild().setNodeValue( new_source) # We must also change the provider into ogr node.firstChildElement('provider').firstChild().setNodeValue( 'ogr') # Add to the list gpkg_changed.append(layername) feedback.pushInfo('') # Write XML content back if pg_changed or gpkg_changed: # Convert XML to string content = dom.toString() # Log changed layers feedback.pushInfo( tr('PostgreSQL layers to edit in the field') + ':') for layer in pg_changed: feedback.pushInfo('* {}'.format(layer)) feedback.pushInfo('') feedback.pushInfo(tr('Other layers converted to GeoPackage') + ':') for layer in gpkg_changed: feedback.pushInfo('* {}'.format(layer)) # Write file with open(output_path, 'w') as f: f.write(content) feedback.pushInfo('') if not pg_changed: msg = tr( 'No PostgreSQL layers datasource could be changed to target the clone database' ) raise QgsProcessingException(msg) # Log msg = tr( 'The current QGIS project mobile version has been successfully saved. Please send it to your field device.' ) feedback.pushInfo(msg) feedback.pushInfo(output_path) output = {self.OUTPUT_STATUS: 1, self.OUTPUT_STRING: msg} return output
def adjust(self): """ Export data to GNU Gama xml, adjust the network and read result :returns: result list of adjusment from GNU Gama """ # fix = 0 free network fix = 0 adj = 0 for p, s in self.points: if s == 'FIX': fix += 1 else: adj += 1 if adj == 0 or len(self.observations) == 0: # no unknowns or observations return None doc = QDomDocument() doc.appendChild( doc.createComment( 'Gama XML created by SurveyingCalculation plugin for QGIS')) gama_local = doc.createElement('gama-local') gama_local.setAttribute('version', '2.0') doc.appendChild(gama_local) network = doc.createElement('network') network.setAttribute('axes-xy', 'ne') network.setAttribute('angles', 'left-handed') gama_local.appendChild(network) description = doc.createElement('description') if self.dimension == 1: description.appendChild(doc.createTextNode('GNU Gama 1D network')) elif self.dimension == 2: description.appendChild(doc.createTextNode('GNU Gama 2D network')) elif self.dimension == 3: description.appendChild(doc.createTextNode('GNU Gama 3D network')) network.appendChild(description) parameters = doc.createElement('parameters') parameters.setAttribute('sigma-apr', '1') parameters.setAttribute('conf-pr', str(self.probability)) parameters.setAttribute('tol-abs', '1000') parameters.setAttribute('sigma-act', 'aposteriori') parameters.setAttribute('update-constrained-coordinates', 'yes') network.appendChild(parameters) points_observations = doc.createElement('points-observations') points_observations.setAttribute( 'distance-stdev', str(self.stdev_dist) + ' ' + str(self.stdev_dist1)) points_observations.setAttribute('direction-stdev', str(self.stdev_angle)) points_observations.setAttribute('angle-stdev', str(math.sqrt(self.stdev_angle * 2))) points_observations.setAttribute('zenith-angle-stdev', str(self.stdev_angle)) network.appendChild(points_observations) for p, s in self.points: if self.dimension == 1: tmp = doc.createElement('point') tmp.setAttribute('id', p.id) if p.z is not None: tmp.setAttribute('z', str(p.z)) if s == 'FIX': tmp.setAttribute('fix', 'z') else: if fix == 0: tmp.setAttribute('adj', 'Z') else: tmp.setAttribute('adj', 'z') points_observations.appendChild(tmp) elif self.dimension == 2: tmp = doc.createElement('point') tmp.setAttribute('id', p.id) if p.e is not None and p.n is not None: tmp.setAttribute('y', str(p.e)) tmp.setAttribute('x', str(p.n)) if s == 'FIX': tmp.setAttribute('fix', 'xy') else: if fix == 0: # free network tmp.setAttribute('adj', 'XY') else: tmp.setAttribute('adj', 'xy') points_observations.appendChild(tmp) elif self.dimension == 3: tmp = doc.createElement('point') tmp.setAttribute('id', p.id) if p.e is not None and p.n is not None: tmp.setAttribute('y', str(p.e)) tmp.setAttribute('x', str(p.n)) if p.z is not None: tmp.setAttribute('z', str(p.z)) if s == 'FIX': tmp.setAttribute('fix', 'xyz') else: if fix == 0: tmp.setAttribute('adj', 'XYZ') else: tmp.setAttribute('adj', 'xyz') points_observations.appendChild(tmp) if self.dimension == 1: hd = doc.createElement('height-differences') points_observations.appendChild(hd) for o in self.observations: if o.station == 'station': # station record st_id = o.point_id if o.th is None: ih = 0 else: ih = o.th if self.dimension in [2, 3]: sta = doc.createElement('obs') sta.setAttribute('from', o.point_id) points_observations.appendChild(sta) else: # observation if self.dimension == 2: # horizontal network if o.hz is not None: tmp = doc.createElement('direction') tmp.setAttribute('to', o.point_id) tmp.setAttribute('val', str(o.hz.get_angle('GON'))) sta.appendChild(tmp) if o.d is not None: # horizontal distance hd = o.horiz_dist() if hd is not None: tmp = doc.createElement('distance') tmp.setAttribute('to', o.point_id) tmp.setAttribute('val', str(hd)) sta.appendChild(tmp) elif self.dimension == 1: # elevations only 1d if o.th is None: th = 0 else: th = o.th if o.d is not None and o.v is not None: tmp = doc.createElement('dh') tmp.setAttribute('from', st_id) tmp.setAttribute('to', o.point_id) # TODO hibaterjedes tmp.setAttribute('stdev', '1') sz = math.sin(o.v.get_angle()) w = self.stdev_dist + self.stdev_dist1 * o.d.d / 1000 ro_cc = 200 * 100 * 100 / math.pi if o.d.mode == 'SD': cz = math.cos(o.v.get_angle()) tmp.setAttribute('val', str(o.d.d * cz + ih - th)) tmp.setAttribute( 'stdev', str( math.sqrt(cz**2 * w**2 + (o.d.d * 1000)**2 * sz**2 * (self.stdev_angle / RO_CC)**2))) else: tz = math.tan(o.v.get_angle()) tmp.setAttribute( 'val', str(o.d.d / math.tan(o.v.get_angle()) + ih - th)) tmp.setAttribute( 'stdev', str( math.sqrt((1 / tz)**2 * w**2 + (o.d.d * 1000)**2 * (o.d.d * 1000)**2 * (1 / sz**2)**2 * (self.stdev_angle / RO_CC)**2))) hd.appendChild(tmp) elif self.dimension == 3: # 3d if o.th is None: th = 0 else: th = o.th if o.hz is not None: tmp = doc.createElement('direction') tmp.setAttribute('to', o.point_id) tmp.setAttribute('val', str(o.hz.get_angle('GON'))) sta.appendChild(tmp) if o.d is not None: if o.d.mode == 'SD': tmp = doc.createElement('s-distance') tmp.setAttribute('val', str(o.d.d)) tmp.setAttribute('from_dh', str(ih)) tmp.setAttribute('to_dh', str(th)) else: tmp = doc.createElement('distance') tmp.setAttribute('val', str(o.d.d)) tmp.setAttribute('to', o.point_id) sta.appendChild(tmp) if o.v is not None: tmp = doc.createElement('z-angle') tmp.setAttribute('to', o.point_id) tmp.setAttribute('val', str(o.v.get_angle('GON'))) tmp.setAttribute('from_dh', str(ih)) tmp.setAttribute('to_dh', str(th)) sta.appendChild(tmp) else: # unknown dimension return None # generate temp file name tmpf = QTemporaryFile(QDir.temp().absoluteFilePath('w')) tmpf.open(QIODevice.WriteOnly) tmpf.close() tmp_name = tmpf.fileName() f = QFile(tmp_name + '.xml') if f.open(QIODevice.WriteOnly): f.write(doc.toByteArray()) f.close() # run gama-local if self.gama_prog is None: return None status = QProcess.execute(self.gama_prog, [ tmp_name + '.xml', '--angles', '360', '--text', tmp_name + '.txt', '--xml', tmp_name + 'out.xml' ]) if status != 0: return None xmlParser = QXmlSimpleReader() xmlFile = QFile(tmp_name + 'out.xml') xmlInputSource = QXmlInputSource(xmlFile) doc.setContent(xmlInputSource, xmlParser) f_txt = QFile(tmp_name + '.txt') f_txt.open(QIODevice.ReadOnly) res = f_txt.readAll().data() f_txt.close() # store coordinates adj_nodes = doc.elementsByTagName('adjusted') if adj_nodes.count() < 1: return res adj_node = adj_nodes.at(0) for i in range(len(adj_node.childNodes())): pp = adj_node.childNodes().at(i) if pp.nodeName() == 'point': for ii in range(len(pp.childNodes())): ppp = pp.childNodes().at(ii) if ppp.nodeName() == 'id': p = Point(ppp.firstChild().nodeValue()) elif ppp.nodeName() == 'Y' or ppp.nodeName() == 'y': p.e = float(ppp.firstChild().nodeValue()) elif ppp.nodeName() == 'X' or ppp.nodeName() == 'x': p.n = float(ppp.firstChild().nodeValue()) elif ppp.nodeName() == 'Z' or ppp.nodeName() == 'z': p.z = float(ppp.firstChild().nodeValue()) ScPoint(p).store_coord(self.dimension) # remove input xml and output xml tmpf.remove() f_txt.remove() f.remove() xmlFile.remove() return res