Esempio n. 1
0
    def testSubstitutionMap(self):
        """Test that we can use degree symbols in substitutions.
        """
        # Create a point and convert it to text containing a degree symbol.
        myPoint = QgsPoint(12.3, -33.33)
        myCoordinates = myPoint.toDegreesMinutesSeconds(2)
        myTokens = myCoordinates.split(',')
        myLongitude = myTokens[0]
        myLatitude = myTokens[1]
        myText = 'Latitude: %s, Longitude: %s' % (myLatitude, myLongitude)

        # Load the composition with the substitutions
        myComposition = QgsComposition(self.iface.mapCanvas().mapSettings())
        mySubstitutionMap = {'replace-me': myText}
        myFile = os.path.join(TEST_DATA_DIR, 'template-for-substitution.qpt')
        with open(myFile) as f:
            myTemplateContent = f.read()
        myDocument = QDomDocument()
        myDocument.setContent(myTemplateContent)
        myComposition.loadFromTemplate(myDocument, mySubstitutionMap)

        # We should be able to get map0
        myMap = myComposition.getComposerMapById(0)
        myMessage = ('Map 0 could not be found in template %s', myFile)
        assert myMap is not None, myMessage
Esempio n. 2
0
    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
Esempio n. 3
0
    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
Esempio n. 4
0
    def testSymbolSizeAfterReload(self):
        # create a layer
        layer = createLayerWithOnePoint()

        # load a sld with marker size
        sld = 'symbol_layer/QgsSvgMarkerSymbolLayer.sld'
        mFilePath = os.path.join(TEST_DATA_DIR, sld)
        layer.loadSldStyle(mFilePath)

        # get the size and unit of the symbol
        sl = layer.renderer().symbol().symbolLayers()[0]
        first_size = sl.size()
        first_unit = sl.outputUnit()  # in pixels

        # export sld into a qdomdocument with namespace processing activated
        doc = QDomDocument()
        msg = ""
        layer.exportSldStyle(doc, msg)
        doc.setContent(doc.toString(), True)
        self.assertTrue(msg == "")

        # reload the same sld
        root = doc.firstChildElement("StyledLayerDescriptor")
        el = root.firstChildElement("NamedLayer")
        layer.readSld(el, msg)

        # extract the size and unit of symbol
        sl = layer.renderer().symbol().symbolLayers()[0]
        second_size = sl.size()
        second_unit = sl.outputUnit()

        # size and unit should be the same after export and reload the same
        # sld description
        self.assertEqual(first_size, second_size)
        self.assertEqual(first_unit, second_unit)
Esempio n. 5
0
    def testLayerDataSourceReset(self):
        """When adding a layer with the same id to the store make sure
        the data source is also updated in case the layer validity has
        changed from False to True"""

        p = QgsProject()
        store = p.layerStore()
        vl1 = createLayer('valid')
        vl2 = QgsVectorLayer('/not_a_valid_path.shp', 'invalid', 'ogr')
        self.assertTrue(vl1.isValid())
        self.assertFalse(vl2.isValid())
        store.addMapLayers([vl1, vl2])
        self.assertEqual(store.validCount(), 1)
        self.assertEqual(len(store.mapLayers()), 2)

        # Re-add the bad layer
        store.addMapLayers([vl2])
        self.assertEqual(store.validCount(), 1)
        self.assertEqual(len(store.mapLayers()), 2)

        doc = QDomDocument()
        doc.setContent('<maplayer><provider encoding="UTF-8">ogr</provider><layername>fixed</layername><id>%s</id></maplayer>' % vl2.id())
        layer_node = QDomNode(doc.firstChild())
        self.assertTrue(vl2.writeXml(layer_node, doc, QgsReadWriteContext()))
        datasource_node = doc.createElement("datasource")
        datasource_node.appendChild(doc.createTextNode(os.path.join(TEST_DATA_DIR, 'points.shp')))
        layer_node.appendChild(datasource_node)
        p.readLayer(layer_node)
        self.assertEqual(store.validCount(), 2)
        self.assertEqual(len(store.mapLayers()), 2)
        self.assertEqual(store.mapLayers()[vl2.id()].name(), 'fixed')
Esempio n. 6
0
    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
Esempio n. 7
0
 def processAlgorithm(self, parameters, context, feedback):
     layer = self.parameterAsRasterLayer(parameters, self.INPUT, context)
     style = self.parameterAsFile(parameters, self.STYLE, context)
     with open(style) as f:
         xml = "".join(f.readlines())
     d = QDomDocument()
     d.setContent(xml)
     layer.importNamedStyle(d)
     layer.triggerRepaint()
     return {self.INPUT: layer}
    def __init__(self, parent=None, xml=None):
        super(XmlDialog, self).__init__(parent)
        self.setupUi(self)

        # self.setWindowTitle(wfs.identification.title)

        document = QDomDocument()
        document.setContent(xml)
        model = DomDocumentModel(document)
        self.treeView.setModel(model)
Esempio n. 9
0
    def testPrintMapFromTemplate(self):
        """Test that we can get a map to render in the template."""
        myPath = os.path.join(TEST_DATA_DIR, 'landsat.tif')
        myFileInfo = QFileInfo(myPath)
        myRasterLayer = QgsRasterLayer(myFileInfo.filePath(),
                                       myFileInfo.completeBaseName())
        myRenderer = QgsMultiBandColorRenderer(
            myRasterLayer.dataProvider(), 2, 3, 4
        )
        #mRasterLayer.setRenderer( rasterRenderer )
        myPipe = myRasterLayer.pipe()
        assert myPipe.set(myRenderer), "Cannot set pipe renderer"

        QgsMapLayerRegistry.instance().addMapLayers([myRasterLayer])

        myMapRenderer = QgsMapRenderer()
        myLayerStringList = []
        myLayerStringList.append(myRasterLayer.id())
        myMapRenderer.setLayerSet(myLayerStringList)
        myMapRenderer.setProjectionsEnabled(False)

        myComposition = QgsComposition(myMapRenderer)
        myFile = os.path.join(TEST_DATA_DIR, 'template-for-substitution.qpt')
        with open(myFile) as f:
            myTemplateContent = f.read()
        myDocument = QDomDocument()
        myDocument.setContent(myTemplateContent)
        myComposition.loadFromTemplate(myDocument)

        # now render the map, first zooming to the raster extents
        myMap = myComposition.getComposerMapById(0)
        myMessage = ('Map 0 could not be found in template %s', myFile)
        assert myMap is not None, myMessage

        myExtent = myRasterLayer.extent()
        myMap.setNewExtent(myExtent)

        myImagePath = os.path.join(str(QDir.tempPath()),
                                   'template_map_render_python.png')

        myPageNumber = 0
        myImage = myComposition.printPageAsRaster(myPageNumber)
        myImage.save(myImagePath)
        assert os.path.exists(myImagePath), 'Map render was not created.'

        # Not sure if this is a predictable way to test but its quicker than
        # rendering.
        myFileSize = QFileInfo(myImagePath).size()
        myExpectedFileSize = 100000
        myMessage = ('Expected file size to be greater than %s, got %s'
                     ' for %s' %
                     (myExpectedFileSize, myFileSize, myImagePath))
        assert myFileSize > myExpectedFileSize, myMessage
	def applyScalarRenderSettings(self, layer, datasetGroupIndex, file, type, save_type='xml'):
		"""
		Applies scalar renderer settings to a datagroup based on a color ramp properties.
		
		:param layer: QgsMeshLayer
		:param datasetGroupIndex: int
		:param file: str
		:param type: str -> 'ramp'
						    'map'
		:return: bool -> True for successful, False for unsuccessful
		"""

		rs = layer.rendererSettings()
		rsScalar = rs.scalarSettings(datasetGroupIndex)
		
		if type == 'ramp':
			if rsScalar.colorRampShader().colorRampItemList():
				minValue = rsScalar.colorRampShader().colorRampItemList()[0].value
				maxValue = rsScalar.colorRampShader().colorRampItemList()[-1].value
				shader = rsScalar.colorRampShader()
				doc = QDomDocument()
				xml = QFile(file)
				statusOK, errorStr, errorLine, errorColumn = doc.setContent(xml, True)
				if statusOK:
					element = doc.documentElement()
					shader.readXml(element)
					shader.setMinimumValue(minValue)
					shader.setMaximumValue(maxValue)
					shader.setColorRampType(0)
					shader.classifyColorRamp(5, -1, QgsRectangle(), None)
					rsScalar.setColorRampShader(shader)
				else:
					return False
			else:
				return False
		elif type == 'map':
			doc = QDomDocument()
			xml = QFile(file) if save_type == 'xml' else file
			statusOK, errorStr, errorLine, errorColumn = doc.setContent(xml, True)
			if statusOK:
				element = doc.documentElement()
				rsScalar.readXml(element)
			else:
				return False
		else:
			return False
			
		rs.setScalarSettings(datasetGroupIndex, rsScalar)
		layer.setRendererSettings(rs)
		
		return True
Esempio n. 11
0
    def export_view(self):
        '''
        Export current view to PDF
        '''
        # Load template from file
        s = QSettings()
        f = s.value("cadastre/composerTemplateFile", '', type=str)
        if not os.path.exists(f):
            f = os.path.join(str(Path(__file__).resolve().parent), 'composers', 'paysage_a4.qpt')
            s.setValue("cadastre/composerTemplateFile", f)

        QApplication.setOverrideCursor(Qt.WaitCursor)
        template_content = None
        with open(f, 'rt', encoding="utf-8") as ff:
            template_content = ff.read()
        if not template_content:
            return
        d = QDomDocument()
        d.setContent(template_content)

        c = QgsPrintLayout(QgsProject.instance())
        c.loadFromTemplate(d, QgsReadWriteContext() )

        # Set scale and extent
        cm=c.referenceMap()
        canvas = self.iface.mapCanvas()
        extent = canvas.extent()
        scale = canvas.scale()
        if extent:
            cm.zoomToExtent(extent)
        if scale:
            cm.setScale(scale)

        # Export
        tempDir = s.value("cadastre/tempDir", '%s' % tempfile.gettempdir(), type=str)
        self.targetDir = tempfile.mkdtemp('', 'cad_export_', tempDir)
        temp = int(time()*100)
        temppath = os.path.join(tempDir, 'export_cadastre_%s.pdf' % temp)

        exporter = QgsLayoutExporter(c)
        exportersettings = QgsLayoutExporter.PdfExportSettings()
        exportersettings.dpi = 300
        exportersettings.forceVectorOutput = True
        exportersettings.rasterizeWholeImage = False #rasterizeWholeImage = false
        exporter.exportToPdf(temppath, exportersettings )

        QApplication.restoreOverrideCursor()

        if os.path.exists(temppath):
            cadastre_common.openFile(temppath)
Esempio n. 12
0
    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
Esempio n. 13
0
    def testNoSubstitutionMap(self):
        """Test that we can get a map if we use no text substitutions."""
        myComposition = QgsComposition(self.iface.mapCanvas().mapSettings())
        myFile = os.path.join(TEST_DATA_DIR, 'template-for-substitution.qpt')
        with open(myFile) as f:
            myTemplateContent = f.read()
        myDocument = QDomDocument()
        myDocument.setContent(myTemplateContent)
        myComposition.loadFromTemplate(myDocument)

        # We should be able to get map0
        myMap = myComposition.getComposerMapById(0)
        myMessage = ('Map 0 could not be found in template %s', myFile)
        assert myMap is not None, myMessage
    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
Esempio n. 15
0
 def testComposerHtmlAccessor(self):
     """Test that we can retrieve the ComposerHtml instance given an item.
     """
     myComposition = QgsComposition(self.iface.mapCanvas().mapSettings())
     mySubstitutionMap = {'replace-me': 'Foo bar'}
     myFile = os.path.join(TEST_DATA_DIR, 'template.qpt')
     with open(myFile, 'rt') as myTemplateFile:
         myTemplateContent = myTemplateFile.read()
     myDocument = QDomDocument()
     myDocument.setContent(myTemplateContent)
     myComposition.loadFromTemplate(myDocument, mySubstitutionMap)
     myItem = myComposition.getComposerItemById('html-test')
     myComposerHtml = myComposition.getComposerHtmlByItem(myItem)
     myMessage = 'Could not retrieve the composer html given an item'
     self.assertIsNotNone(myComposerHtml, myMessage)
Esempio n. 16
0
 def testComposerHtmlAccessor(self):
     """Test that we can retrieve the ComposerHtml instance given an item.
     """
     myComposition = QgsComposition(self.iface.mapCanvas().mapRenderer())
     mySubstitutionMap = {"replace-me": "Foo bar"}
     myFile = os.path.join(TEST_DATA_DIR, "template.qpt")
     with open(myFile, "rt") as myTemplateFile:
         myTemplateContent = myTemplateFile.read()
     myDocument = QDomDocument()
     myDocument.setContent(myTemplateContent)
     myComposition.loadFromTemplate(myDocument, mySubstitutionMap)
     myItem = myComposition.getComposerItemById("html-test")
     myComposerHtml = myComposition.getComposerHtmlByItem(myItem)
     myMessage = "Could not retrieve the composer html given an item"
     self.assertIsNotNone(myComposerHtml, myMessage)
Esempio n. 17
0
    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))
Esempio n. 18
0
    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 _change_data_source(self, layer, datasource, provider_key):
        """Due to the fact that a project r/w context is not available inside
        the map layers classes, the original style and subset string restore
        happens in app, this function replicates app behavior"""

        options = QgsDataProvider.ProviderOptions()

        subset_string = ''
        if not layer.isValid():
            try:
                subset_string = layer.dataProvider().subsetString()
            except:
                pass

        layer.setDataSource(datasource, layer.name(), provider_key, options)

        if subset_string:
            layer.setSubsetString(subset_string)

        self.assertTrue(layer.originalXmlProperties(), layer.name())
        context = QgsReadWriteContext()
        context.setPathResolver(QgsProject.instance().pathResolver())
        errorMsg = ''
        doc = QDomDocument()
        self.assertTrue(doc.setContent(layer.originalXmlProperties()))
        layer_node = QDomNode(doc.firstChild())
        self.assertTrue(layer.readSymbology(layer_node, errorMsg, context))
Esempio n. 20
0
    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)
Esempio n. 21
0
    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
Esempio n. 22
0
    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))
Esempio n. 23
0
    def processAlgorithm(self, parameters, context, feedback):
        filename = self.getParameterValue(self.INPUT)
        layer = QgsProcessingUtils.mapLayerFromString(filename, context)

        style = self.getParameterValue(self.STYLE)
        if layer is None:
            dataobjects.load(filename, os.path.basename(filename), style=style)
        else:
            with open(style) as f:
                xml = "".join(f.readlines())
            d = QDomDocument()
            d.setContent(xml)
            n = d.firstChild()
            layer.readSymbology(n, '')
            context.addLayerToLoadOnCompletion(self.getOutputFromName(self.OUTPUT).value)
            self.setOutputValue(self.OUTPUT, filename)
            layer.triggerRepaint()
Esempio n. 24
0
    def processAlgorithm(self, progress):
        filename = self.getParameterValue(self.INPUT)
        layer = dataobjects.getObjectFromUri(filename)

        style = self.getParameterValue(self.STYLE)
        if layer is None:
            dataobjects.load(filename, os.path.basename(filename), style=style)
            self.getOutputFromName(self.OUTPUT).open = False
        else:
            with open(style) as f:
                xml = "".join(f.readlines())
            d = QDomDocument()
            d.setContent(xml)
            n = d.firstChild()
            layer.readSymbology(n, '')
            self.setOutputValue(self.OUTPUT, filename)
            iface.mapCanvas().refresh()
Esempio n. 25
0
    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 createSimpleMemorial(self):
        tempDoc = QDomDocument()
        simple = QFile(self.simpleMemorial)
        simple.open(QIODevice.ReadOnly)
        loaded = tempDoc.setContent(simple)
        simple.close()
        
        element = tempDoc.documentElement()
         
        nodes = element.elementsByTagName("table")
         
        table = nodes.item(0).toElement()

        tr = tempDoc.createElement("tr")
        tr.appendChild(self.createCellElement(tempDoc, u"MEMORIAL DESCRITIVO SINTÉTICO", 7, 0))
        table.appendChild(tr)
        
        tr = tempDoc.createElement("tr")
        tr.appendChild(self.createCellElement(tempDoc, u"VÉRTICE", 0, 2))
        tr.appendChild(self.createCellElement(tempDoc, "COORDENADAS", 2, 0))
        tr.appendChild(self.createCellElement(tempDoc, "LADO", 0, 2))
        tr.appendChild(self.createCellElement(tempDoc, "AZIMUTES", 2, 0))
        tr.appendChild(self.createCellElement(tempDoc, u"DISTÂNCIA", 0, 0))
        table.appendChild(tr)
        
        tr = tempDoc.createElement("tr")
        tr.appendChild(self.createCellElement(tempDoc, "E", 0, 0))
        tr.appendChild(self.createCellElement(tempDoc, "N", 0, 0))
        tr.appendChild(self.createCellElement(tempDoc, "PLANO", 0, 0))
        tr.appendChild(self.createCellElement(tempDoc, "REAL", 0, 0))
        tr.appendChild(self.createCellElement(tempDoc, "(m)", 0, 0))
        table.appendChild(tr)
         
        convergence = float(self.convergenciaEdit.text())
             
        rowCount = self.tableWidget.rowCount()
        
        for i in range(0,rowCount):
            lineElement = tempDoc.createElement("tr")
             
            lineElement.appendChild(self.createCellElement(tempDoc, self.tableWidget.item(i,0).text(), 0, 0))
             
            lineElement.appendChild(self.createCellElement(tempDoc, self.tableWidget.item(i,1).text(), 0, 0))
            lineElement.appendChild(self.createCellElement(tempDoc, self.tableWidget.item(i,2).text(), 0, 0))
 
            lineElement.appendChild(self.createCellElement(tempDoc, self.tableWidget.item(i,3).text(), 0, 0))
 
            lineElement.appendChild(self.createCellElement(tempDoc, self.tableWidget.item(i,4).text(), 0, 0))
            lineElement.appendChild(self.createCellElement(tempDoc, self.tableWidget.item(i,5).text(), 0, 0))
            lineElement.appendChild(self.createCellElement(tempDoc, self.tableWidget.item(i,6).text(), 0, 0))
            
            table.appendChild(lineElement)
            
        simple = open(self.simpleMemorial, "w", encoding='utf-8')
        simple.write(tempDoc.toString())
        simple.close()
Esempio n. 27
0
 def testCyclicDependency(self):
     inDoc = """
     <maplayers>
     <maplayer>
       <id>layerB</id>
       <layerDependencies>
         <layer id="layerA"/>
       </layerDependencies>
     </maplayer>
     <maplayer>
       <id>layerA</id>
       <layerDependencies>
         <layer id="layerB"/>
       </layerDependencies>
     </maplayer>
     </maplayers>"""
     doc = QDomDocument("testdoc")
     doc.setContent(inDoc)
     dep = QgsLayerDefinition.DependencySorter(doc)
     self.assertTrue(dep.hasCycle())
Esempio n. 28
0
    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
Esempio n. 29
0
def export_map(layer, new_extent):
    """This function changes the map extents and creates a exported map image"""
    legend = iface.legendInterface()
    legend.setLayerVisible(layer, False)
    canvas = iface.mapCanvas()
    canvas.setExtent(new_extent)
    canvas.refresh()
    project_path = os.path.join(gis_files, 'air_tasking_order.qgs')
    QgsProject.instance().write(QFileInfo(project_path))    #Save with the flight lines
    QgsProject.instance().read(QFileInfo(project_path))
    bridge = QgsLayerTreeMapCanvasBridge(
        QgsProject.instance().layerTreeRoot(), canvas)
    bridge.setCanvasLayers()
    template_file = file(os.path.join(gis_files, 'airborne_survey.qpt'))
    template_content = template_file.read()
    template_file.close()
    document = QDomDocument()
    document.setContent(template_content)
    ms = canvas.mapSettings()
    composition = QgsComposition(ms)
    composition.loadFromTemplate(document, {})
    map_item = composition.getComposerItemById('the_map')
    map_item.setMapCanvas(canvas)
    map_item.zoomToExtent(canvas.extent())
    map_text_box = '<font face="Arial">%s Tasking <br />%s - %s<br />%s' % (
        Requesting_RFC, Survey_Start_Date, Survey_End_Date, Survey_Name)
    map_text = composition.getComposerItemById('Map_ID_Text')
    map_text.setText(map_text_box)
    composition.refreshItems()
    dpi = 300
    dpmm = dpi / 24.4
    width = int(dpmm * composition.paperWidth())
    height = int(dpmm * composition.paperHeight())
    image = QImage(QSize(width, height), QImage.Format_ARGB32)
    image.setDotsPerMeterX(dpmm * 1000)
    image.setDotsPerMeterY(dpmm * 1000)
    imagePainter = QPainter(image)
    composition.renderPage(imagePainter, 0)
    imagePainter.end()
    image.save(Survey_Name + '.png', 'png')
    def get_print_layout(self):
        template_path = self.getTemplateFilePath()
        if not os.path.isfile(template_path):
            msg = 'The requested template {} is not currently available.'.format(template_path)
            QMessageBox.critical(self.iface.mainWindow(), 'Template Not Found', msg)
            return

        # Create a new print layout with name equal to the project title
        project = QgsProject.instance()
        layout_manager = project.layoutManager()
        existing_print_layout = layout_manager.layoutByName(self.ui.titleLineEdit.text())
        if existing_print_layout:
            layout_manager.removeLayout(existing_print_layout)
        print_layout = QgsPrintLayout(project)
        print_layout.setName(self.ui.titleLineEdit.text())
        layout_manager.addLayout(print_layout)

        # Load the template file
        try:
            tree = ET.parse(template_path)
            doc = QDomDocument()
            doc.setContent(ET.tostring(tree.getroot()))
        except IOError:
            # problem reading xml template
            msg = 'The requested template {} could not be read.'.format(template_path)
            QMessageBox.critical(self.iface.mainWindow(), 'Failed to Read Template', msg)
            return
        except:
            # Unexpected problem
            msg = 'An unexpected error occurred while reading {}:\n\n{}'.format(template_path, traceback.format_exc())
            QMessageBox.critical(self.iface.mainWindow(), 'Failed to Read Template', msg)
            return

        if not print_layout.loadFromTemplate(doc, QgsReadWriteContext(), True):
            msg = 'loadFromTemplate returned False.'
            QMessageBox.critical(self.iface.mainWindow(), 'Failed to Read Template', msg)
            return

        return print_layout
Esempio n. 31
0
    def test_getcapabilities(self):
        project = self._project_path
        assert os.path.exists(project), "Project file not found: " + project

        # without cache
        query_string = '?MAP=%s&SERVICE=WMS&VERSION=1.3.0&REQUEST=%s' % (
            urllib.parse.quote(project), 'GetCapabilities')
        header, body = self._execute_request(query_string)
        doc = QDomDocument("wms_getcapabilities_130.xml")
        doc.setContent(body)
        # with cache
        header, body = self._execute_request(query_string)

        # without cache
        query_string = '?MAP=%s&SERVICE=WMS&VERSION=1.1.1&REQUEST=%s' % (
            urllib.parse.quote(project), 'GetCapabilities')
        header, body = self._execute_request(query_string)
        # with cache
        header, body = self._execute_request(query_string)

        # without cache
        query_string = '?MAP=%s&SERVICE=WFS&VERSION=1.1.0&REQUEST=%s' % (
            urllib.parse.quote(project), 'GetCapabilities')
        header, body = self._execute_request(query_string)
        # with cache
        header, body = self._execute_request(query_string)

        # without cache
        query_string = '?MAP=%s&SERVICE=WFS&VERSION=1.0.0&REQUEST=%s' % (
            urllib.parse.quote(project), 'GetCapabilities')
        header, body = self._execute_request(query_string)
        # with cache
        header, body = self._execute_request(query_string)

        # without cache
        query_string = '?MAP=%s&SERVICE=WCS&VERSION=1.0.0&REQUEST=%s' % (
            urllib.parse.quote(project), 'GetCapabilities')
        header, body = self._execute_request(query_string)
        # with cache
        header, body = self._execute_request(query_string)

        # without cache
        query_string = '?MAP=%s&SERVICE=WMTS&VERSION=1.0.0&REQUEST=%s' % (
            urllib.parse.quote(project), 'GetCapabilities')
        header, body = self._execute_request(query_string)
        # with cache
        header, body = self._execute_request(query_string)

        filelist = [
            f for f in os.listdir(self._servercache._cache_dir)
            if f.endswith(".xml")
        ]
        self.assertEqual(len(filelist), 6, 'Not enough file in cache')

        cacheManager = self._server_iface.cacheManager()

        self.assertTrue(cacheManager.deleteCachedDocuments(None),
                        'deleteCachedDocuments does not return True')

        filelist = [
            f for f in os.listdir(self._servercache._cache_dir)
            if f.endswith(".xml")
        ]
        self.assertEqual(len(filelist), 0,
                         'All files in cache are not deleted ')

        prj = QgsProject()
        prj.read(project)

        query_string = '?MAP=%s&SERVICE=WMS&VERSION=1.3.0&REQUEST=%s' % (
            urllib.parse.quote(project), 'GetCapabilities')
        request = QgsBufferServerRequest(query_string,
                                         QgsServerRequest.GetMethod, {}, None)

        accessControls = self._server_iface.accessControls()

        cDoc = QDomDocument("wms_getcapabilities_130.xml")
        self.assertFalse(
            cacheManager.getCachedDocument(cDoc, prj, request, accessControls),
            'getCachedDocument is not None')

        self.assertTrue(
            cacheManager.setCachedDocument(doc, prj, request, accessControls),
            'setCachedDocument false')

        self.assertTrue(
            cacheManager.getCachedDocument(cDoc, prj, request, accessControls),
            'getCachedDocument is None')
        self.assertEqual(doc.documentElement().tagName(),
                         cDoc.documentElement().tagName(),
                         'cachedDocument not equal to provide document')

        self.assertTrue(cacheManager.deleteCachedDocuments(None),
                        'deleteCachedDocuments does not return True')
Esempio n. 32
0
    def testReport(self):
        # Here there be dragons.
        # TODO: Refactor this whole functions out into a seperate class.
        if self.usersettings.getlayout() is not '' and os.path.exists(
                self.usersettings.getlayout()):
            dir_path = self.usersettings.getlayout()
        else:
            dir_path = self.dirpath + "/standardlayout.qpt"
        project = QgsProject.instance()
        self.composition = QgsPrintLayout(project)
        self.composition.initializeDefaults()
        document = QDomDocument()
        # read template content
        template_file = open(dir_path)
        template_content = template_file.read()
        template_file.close()
        document.setContent(template_content)

        # load layout from template and add to Layout Manager
        self.composition.loadFromTemplate(document, QgsReadWriteContext())

        #Set the name to a unique name.
        name = "GeoAtlasReport"
        if project.layoutManager().layoutByName(name) is not None:
            i = 2
            while project.layoutManager().layoutByName(name +
                                                       str(i)) is not None:
                i = i + 1
            name = name + str(i)
        self.composition.setName(name)
        for frame in self.composition.multiFrames():
            if frame.totalSize().width() >= 0 and frame.totalSize().height(
            ) >= 0:
                htmlframe = frame
                break
        settings = CrosssectionSettings()
        settings.depth = self.dlg.getDepth()
        settings.drilldistance = self.dlg.getDrillDistance()
        settings.height = int(htmlframe.frames()[0].sizeWithUnits().height() *
                              3)  #The this is just a magic value ration.
        settings.linepoint = self.calculateLinePoint(self.line, settings)
        section = self.performCrosssection(None, self.coords, settings)
        if section:
            svg = self.fixSvg(section['Svg'], settings)
            html = self.createHtmlframe(svg, settings, section,
                                        "\\styles\\printCSS.css")
            htmlframe.setHtml(html)
            htmlframe.refresh()

        for item in self.composition.items():
            if str(type(item).__name__) == "QgsLayoutItemMap":
                line = self.line
                bbox = line.geometry().boundingBox()
                coords = reduceTo2dList(
                    line.__geo_interface__["geometry"]["coordinates"])
                rotation = getRotationOfLine(coords)
                item.zoomToExtent(bbox)
                scaleFactor = getDistanceOfLine(coords) / item.extent().width()
                bbox.scale(
                    scaleFactor
                )  #Det her kan gøres bedre, lodrette og vandrette linjer virker.
                bbox.scale(1.1)
                item.zoomToExtent(bbox)
                item.setMapRotation(rotation)

                item.refresh()
                break
        #do void 	setContentMode (ContentMode mode)
        project.layoutManager().addLayout(self.composition)
        self.composition = project.layoutManager().layoutByName(name)
        self.iface.openLayoutDesigner(self.composition)
Esempio n. 33
0
    def testSaveLoadTemplate(self):
        tmpfile = os.path.join(self.basetestpath, 'testTemplate.qpt')

        p = QgsProject()
        l = QgsLayout(p)
        l.initializeDefaults()

        # add some items
        item1 = QgsLayoutItemLabel(l)
        item1.setId('xxyyxx')
        item1.attemptMove(QgsLayoutPoint(4, 8, QgsUnitTypes.LayoutMillimeters))
        item1.attemptResize(
            QgsLayoutSize(18, 12, QgsUnitTypes.LayoutMillimeters))
        l.addItem(item1)
        item2 = QgsLayoutItemLabel(l)
        item2.setId('zzyyzz')
        item2.attemptMove(
            QgsLayoutPoint(1.4, 1.8, QgsUnitTypes.LayoutCentimeters))
        item2.attemptResize(
            QgsLayoutSize(2.8, 2.2, QgsUnitTypes.LayoutCentimeters))
        l.addItem(item2)

        # multiframe
        multiframe1 = QgsLayoutItemHtml(l)
        multiframe1.setHtml('mf1')
        l.addMultiFrame(multiframe1)
        frame1 = QgsLayoutFrame(l, multiframe1)
        frame1.setId('frame1')
        frame1.attemptMove(QgsLayoutPoint(4, 8,
                                          QgsUnitTypes.LayoutMillimeters))
        frame1.attemptResize(
            QgsLayoutSize(18, 12, QgsUnitTypes.LayoutMillimeters))
        multiframe1.addFrame(frame1)

        multiframe2 = QgsLayoutItemHtml(l)
        multiframe2.setHtml('mf2')
        l.addMultiFrame(multiframe2)
        frame2 = QgsLayoutFrame(l, multiframe2)
        frame2.setId('frame2')
        frame2.attemptMove(
            QgsLayoutPoint(1.4, 1.8, QgsUnitTypes.LayoutCentimeters))
        frame2.attemptResize(
            QgsLayoutSize(2.8, 2.2, QgsUnitTypes.LayoutCentimeters))
        multiframe2.addFrame(frame2)

        uuids = {
            item1.uuid(),
            item2.uuid(),
            frame1.uuid(),
            frame2.uuid(),
            multiframe1.uuid(),
            multiframe2.uuid()
        }
        original_uuids = {
            item1.uuid(),
            item2.uuid(),
            frame1.uuid(),
            frame2.uuid()
        }

        self.assertTrue(l.saveAsTemplate(tmpfile, QgsReadWriteContext()))

        l2 = QgsLayout(p)
        with open(tmpfile) as f:
            template_content = f.read()
        doc = QDomDocument()
        doc.setContent(template_content)

        # adding to existing items
        new_items, ok = l2.loadFromTemplate(doc, QgsReadWriteContext(), False)
        self.assertTrue(ok)
        self.assertEqual(len(new_items), 4)
        items = l2.items()
        multiframes = l2.multiFrames()
        self.assertEqual(len(multiframes), 2)
        self.assertTrue([i for i in items if i.id() == 'xxyyxx'])
        self.assertTrue([i for i in items if i.id() == 'zzyyzz'])
        self.assertTrue([i for i in items if i.id() == 'frame1'])
        self.assertTrue([i for i in items if i.id() == 'frame2'])
        self.assertTrue([i for i in multiframes if i.html() == 'mf1'])
        self.assertTrue([i for i in multiframes if i.html() == 'mf2'])
        self.assertTrue(new_items[0] in l2.items())
        self.assertTrue(new_items[1] in l2.items())
        self.assertTrue(new_items[2] in l2.items())
        self.assertTrue(new_items[3] in l2.items())

        # double check that new items have a unique uid
        self.assertNotIn(new_items[0].uuid(), uuids)
        uuids.add(new_items[0].uuid())
        self.assertNotIn(new_items[1].uuid(), uuids)
        uuids.add(new_items[1].uuid())
        self.assertNotIn(new_items[2].uuid(), uuids)
        uuids.add(new_items[2].uuid())
        self.assertNotIn(new_items[3].uuid(), uuids)
        uuids.add(new_items[3].uuid())

        self.assertNotIn(
            multiframes[0].uuid(),
            [multiframe1.uuid(), multiframe2.uuid()])
        self.assertNotIn(
            multiframes[1].uuid(),
            [multiframe1.uuid(), multiframe2.uuid()])
        new_multiframe1 = [i for i in multiframes if i.html() == 'mf1'][0]
        self.assertEqual(new_multiframe1.layout(), l2)
        new_multiframe2 = [i for i in multiframes if i.html() == 'mf2'][0]
        self.assertEqual(new_multiframe2.layout(), l2)
        new_frame1 = sip.cast([i for i in items if i.id() == 'frame1'][0],
                              QgsLayoutFrame)
        new_frame2 = sip.cast([i for i in items if i.id() == 'frame2'][0],
                              QgsLayoutFrame)
        self.assertEqual(new_frame1.multiFrame(), new_multiframe1)
        self.assertEqual(new_multiframe1.frames()[0].uuid(), new_frame1.uuid())
        self.assertEqual(new_frame2.multiFrame(), new_multiframe2)
        self.assertEqual(new_multiframe2.frames()[0].uuid(), new_frame2.uuid())

        # adding to existing items
        new_items2, ok = l2.loadFromTemplate(doc, QgsReadWriteContext(), False)
        self.assertTrue(ok)
        self.assertEqual(len(new_items2), 4)
        items = l2.items()
        self.assertEqual(len(items), 8)
        multiframes2 = l2.multiFrames()
        self.assertEqual(len(multiframes2), 4)
        multiframes2 = [
            m for m in l2.multiFrames() if
            not m.uuid() in [new_multiframe1.uuid(),
                             new_multiframe2.uuid()]
        ]
        self.assertEqual(len(multiframes2), 2)
        self.assertTrue([i for i in items if i.id() == 'xxyyxx'])
        self.assertTrue([i for i in items if i.id() == 'zzyyzz'])
        self.assertTrue([i for i in items if i.id() == 'frame1'])
        self.assertTrue([i for i in items if i.id() == 'frame2'])
        self.assertTrue([i for i in multiframes2 if i.html() == 'mf1'])
        self.assertTrue([i for i in multiframes2 if i.html() == 'mf2'])
        self.assertTrue(new_items[0] in l2.items())
        self.assertTrue(new_items[1] in l2.items())
        self.assertTrue(new_items[2] in l2.items())
        self.assertTrue(new_items[3] in l2.items())
        self.assertTrue(new_items2[0] in l2.items())
        self.assertTrue(new_items2[1] in l2.items())
        self.assertTrue(new_items2[2] in l2.items())
        self.assertTrue(new_items2[3] in l2.items())
        self.assertNotIn(new_items2[0].uuid(), uuids)
        uuids.add(new_items[0].uuid())
        self.assertNotIn(new_items2[1].uuid(), uuids)
        uuids.add(new_items[1].uuid())
        self.assertNotIn(new_items2[2].uuid(), uuids)
        uuids.add(new_items[2].uuid())
        self.assertNotIn(new_items2[3].uuid(), uuids)
        uuids.add(new_items[3].uuid())

        self.assertNotIn(multiframes2[0].uuid(), [
            multiframe1.uuid(),
            multiframe2.uuid(),
            new_multiframe1.uuid(),
            new_multiframe2.uuid()
        ])
        self.assertNotIn(multiframes2[1].uuid(), [
            multiframe1.uuid(),
            multiframe2.uuid(),
            new_multiframe1.uuid(),
            new_multiframe2.uuid()
        ])

        new_multiframe1b = [i for i in multiframes2 if i.html() == 'mf1'][0]
        self.assertEqual(new_multiframe1b.layout(), l2)
        new_multiframe2b = [i for i in multiframes2 if i.html() == 'mf2'][0]
        self.assertEqual(new_multiframe2b.layout(), l2)
        new_frame1b = sip.cast([
            i for i in items
            if i.id() == 'frame1' and i.uuid() != new_frame1.uuid()
        ][0], QgsLayoutFrame)
        new_frame2b = sip.cast([
            i for i in items
            if i.id() == 'frame2' and i.uuid() != new_frame2.uuid()
        ][0], QgsLayoutFrame)
        self.assertEqual(new_frame1b.multiFrame(), new_multiframe1b)
        self.assertEqual(new_multiframe1b.frames()[0].uuid(),
                         new_frame1b.uuid())
        self.assertEqual(new_frame2b.multiFrame(), new_multiframe2b)
        self.assertEqual(new_multiframe2b.frames()[0].uuid(),
                         new_frame2b.uuid())

        # clearing existing items
        new_items3, ok = l2.loadFromTemplate(doc, QgsReadWriteContext(), True)
        new_multiframes = l2.multiFrames()
        self.assertTrue(ok)
        self.assertEqual(len(new_items3), 5)  # includes page
        self.assertEqual(len(new_multiframes), 2)
        items = l2.items()
        self.assertTrue([
            i for i in items
            if isinstance(i, QgsLayoutItem) and i.id() == 'xxyyxx'
        ])
        self.assertTrue([
            i for i in items
            if isinstance(i, QgsLayoutItem) and i.id() == 'zzyyzz'
        ])
        self.assertTrue([
            i for i in items
            if isinstance(i, QgsLayoutItem) and i.id() == 'frame1'
        ])
        self.assertTrue([
            i for i in items
            if isinstance(i, QgsLayoutItem) and i.id() == 'frame2'
        ])
        self.assertTrue(new_items3[0] in l2.items())
        self.assertTrue(new_items3[1] in l2.items())
        self.assertTrue(new_items3[2] in l2.items())
        self.assertTrue(new_items3[3] in l2.items())
        new_multiframe1 = [i for i in new_multiframes if i.html() == 'mf1'][0]
        new_multiframe2 = [i for i in new_multiframes if i.html() == 'mf2'][0]

        new_frame1 = sip.cast([
            i for i in items
            if isinstance(i, QgsLayoutItem) and i.id() == 'frame1'
        ][0], QgsLayoutFrame)
        new_frame2 = sip.cast([
            i for i in items
            if isinstance(i, QgsLayoutItem) and i.id() == 'frame2'
        ][0], QgsLayoutFrame)
        self.assertEqual(new_frame1.multiFrame(), new_multiframe1)
        self.assertEqual(new_multiframe1.frames()[0].uuid(), new_frame1.uuid())
        self.assertEqual(new_frame2.multiFrame(), new_multiframe2)
        self.assertEqual(new_multiframe2.frames()[0].uuid(), new_frame2.uuid())
Esempio n. 34
0
    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("&amp; ")
            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()
Esempio n. 35
0
    def run(self,
            templatePath,
            entityFieldName,
            entityFieldValue,
            outputMode,
            filePath=None,
            dataFields=None,
            fileExtension=None,
            data_source=None):
        """
        :param templatePath: The file path to the user-defined template.
        :param entityFieldName: The name of the column for the specified entity which
        must exist in the data source view or table.
        :param entityFieldValue: The value for filtering the records in the data source
        view or table.
        :param outputMode: Whether the output composition should be an image or PDF.
        :param filePath: The output file where the composition will be written to. Applies
        to single mode output generation.
        :param dataFields: List containing the field names whose values will be used to name the files.
        This is used in multiple mode configuration.
        :param fileExtension: The output file format. Used in multiple mode configuration.
        :param data_source: Name of the data source table or view whose
        row values will be used to name output files if the options has been
        specified by the user.
        """
        if dataFields is None:
            dataFields = []

        if fileExtension is None:
            fileExtension = ''

        if data_source is None:
            data_source = ''

        templateFile = QFile(templatePath)

        if not templateFile.open(QIODevice.ReadOnly):
            return False, QApplication.translate("DocumentGenerator",
                                                 "Cannot read template file.")

        templateDoc = QDomDocument()

        if templateDoc.setContent(templateFile):
            composerDS = ComposerDataSource.create(templateDoc)
            spatialFieldsConfig = SpatialFieldsConfiguration.create(
                templateDoc)
            composerDS.setSpatialFieldsConfig(spatialFieldsConfig)

            # Check if data source exists and return if it doesn't
            if not self.data_source_exists(composerDS):
                msg = QApplication.translate(
                    "DocumentGenerator",
                    "'{0}' data source does not exist in the database."
                    "\nPlease contact your database "
                    "administrator.".format(composerDS.name()))
                return False, msg

            # Set file name value formatter
            self._file_name_value_formatter = EntityValueFormatter(
                name=data_source)

            # Register field names to be used for file naming
            self._file_name_value_formatter.register_columns(dataFields)

            # TODO: Need to automatically register custom configuration collections
            # Photo config collection
            ph_config_collection = PhotoConfigurationCollection.create(
                templateDoc)

            # Table configuration collection
            table_config_collection = TableConfigurationCollection.create(
                templateDoc)

            # Create chart configuration collection object
            chart_config_collection = ChartConfigurationCollection.create(
                templateDoc)

            # Create QR code configuration collection object
            qrc_config_collection = QRCodeConfigurationCollection.create(
                templateDoc)

            # Load the layers required by the table composer items
            self._table_mem_layers = load_table_layers(table_config_collection)

            entityFieldName = self.format_entity_field_name(
                composerDS.name(), data_source)

            # Execute query
            dsTable, records = self._exec_query(composerDS.name(),
                                                entityFieldName,
                                                entityFieldValue)

            if records is None or len(records) == 0:
                return False, QApplication.translate(
                    "DocumentGenerator", "No matching records in the database")
            """
            Iterate through records where a single file output will be generated for each matching record.
            """

            for rec in records:
                composition = QgsPrintLayout(self._map_settings)
                context = QgsReadWriteContext()
                composition.loadFromTemplate(templateDoc, context)
                ref_layer = None
                # Set value of composer items based on the corresponding db values
                for composerId in composerDS.dataFieldMappings().reverse:
                    # Use composer item id since the uuid is stripped off
                    composerItem = composition.itemById(composerId)
                    if composerItem is not None:
                        fieldName = composerDS.dataFieldName(composerId)
                        fieldValue = getattr(rec, fieldName)
                        self._composeritem_value_handler(
                            composerItem, fieldValue)

                # Extract photo information
                self._extract_photo_info(composition, ph_config_collection,
                                         rec)

                # Set table item values based on configuration information
                self._set_table_data(composition, table_config_collection, rec)

                # Refresh non-custom map composer items
                self._refresh_composer_maps(
                    composition,
                    list(spatialFieldsConfig.spatialFieldsMapping().keys()))

                # Set use fixed scale to false i.e. relative zoom
                use_fixed_scale = False

                # Create memory layers for spatial features and add them to the map
                for mapId, spfmList in spatialFieldsConfig.spatialFieldsMapping(
                ).items():

                    map_item = composition.itemById(mapId)

                    if map_item is not None:
                        # Clear any previous map memory layer
                        # self.clear_temporary_map_layers()
                        for spfm in spfmList:
                            # Use the value of the label field to name the layer
                            lbl_field = spfm.labelField()
                            spatial_field = spfm.spatialField()

                            if not spatial_field:
                                continue

                            if lbl_field:
                                if hasattr(rec, spfm.labelField()):
                                    layerName = getattr(rec, spfm.labelField())
                                else:
                                    layerName = self._random_feature_layer_name(
                                        spatial_field)
                            else:
                                layerName = self._random_feature_layer_name(
                                    spatial_field)

                            # Extract the geometry using geoalchemy spatial capabilities
                            geom_value = getattr(rec, spatial_field)
                            if geom_value is None:
                                continue

                            geom_func = geom_value.ST_AsText()
                            geomWKT = self._dbSession.scalar(geom_func)

                            # Get geometry type
                            geom_type, srid = geometryType(
                                composerDS.name(), spatial_field)

                            # Create reference layer with feature
                            ref_layer = self._build_vector_layer(
                                layerName, geom_type, srid)

                            if ref_layer is None or not ref_layer.isValid():
                                continue
                            # Add feature
                            bbox = self._add_feature_to_layer(
                                ref_layer, geomWKT)

                            zoom_type = spfm.zoom_type
                            # Only scale the extents if zoom type is relative
                            if zoom_type == 'RELATIVE':
                                bbox.scale(spfm.zoomLevel())

                            # Workaround for zooming to single point extent
                            if ref_layer.wkbType() == QgsWkbTypes.Point:
                                canvas_extent = self._iface.mapCanvas(
                                ).fullExtent()
                                cnt_pnt = bbox.center()
                                canvas_extent.scale(1.0 / 32, cnt_pnt)
                                bbox = canvas_extent

                            # Style layer based on the spatial field mapping symbol layer
                            symbol_layer = spfm.symbolLayer()
                            if symbol_layer is not None:
                                ref_layer.renderer().symbols(
                                )[0].changeSymbolLayer(0, spfm.symbolLayer())
                            '''
                            Add layer to map and ensure its always added at the top
                            '''
                            self.map_registry.addMapLayer(ref_layer)
                            self._iface.mapCanvas().setExtent(bbox)

                            # Set scale if type is FIXED
                            if zoom_type == 'FIXED':
                                self._iface.mapCanvas().zoomScale(
                                    spfm.zoomLevel())
                                use_fixed_scale = True

                            self._iface.mapCanvas().refresh()
                            # Add layer to map memory layer list
                            self._map_memory_layers.append(ref_layer.id())
                            self._hide_layer(ref_layer)
                        '''
                        Use root layer tree to get the correct ordering of layers
                        in the legend
                        '''
                        self._refresh_map_item(map_item, use_fixed_scale)

                # Extract chart information and generate chart
                self._generate_charts(composition, chart_config_collection,
                                      rec)

                # Extract QR code information in order to generate QR codes
                self._generate_qr_codes(composition, qrc_config_collection,
                                        rec)

                # Build output path and generate composition
                if filePath is not None and len(dataFields) == 0:
                    self._write_output(composition, outputMode, filePath)

                elif filePath is None and len(dataFields) > 0:
                    entityFieldName = 'id'
                    docFileName = self._build_file_name(
                        data_source, entityFieldName, entityFieldValue,
                        dataFields, fileExtension)

                    # Replace unsupported characters in Windows file naming
                    docFileName = docFileName.replace('/', '_').replace(
                        '\\', '_').replace(':', '_').strip('*?"<>|')

                    if not docFileName:
                        return (
                            False,
                            QApplication.translate(
                                "DocumentGenerator",
                                "File name could not be generated from the data fields."
                            ))

                    outputDir = self._composer_output_path()
                    if outputDir is None:
                        return (
                            False,
                            QApplication.translate(
                                "DocumentGenerator",
                                "System could not read the location of the output directory in the registry."
                            ))

                    qDir = QDir()
                    if not qDir.exists(outputDir):
                        return (False,
                                QApplication.translate(
                                    "DocumentGenerator",
                                    "Output directory does not exist"))

                    absDocPath = "{0}/{1}".format(outputDir, docFileName)
                    self._write_output(composition, outputMode, absDocPath)

            return True, "Success"

        return False, "Document composition could not be generated"
Esempio n. 36
0
def mkForm(b, qptForm, form_file, project_name, root_out, zl_layer, zl_field,
           di_layer, di_field, di_name):
    root_code = os.path.dirname(os.path.realpath(__file__))
    name = str(b.attribute(1).replace('_', '.')) + '_' + str(
        b.attribute(3)) + '_' + str(b.attribute(4))

    template_file = open(qptForm, 'r')
    template_content = template_file.read()
    template_file.close()
    document = QDomDocument()
    document.setContent(template_content)

    composition = QgsLayout(QgsProject().instance())
    composition.loadFromTemplate(document, QgsReadWriteContext())

    corners = composition.itemById('corners')
    corners.setPicturePath(root_code + '/templates/corners_a4.svg')

    logo = composition.itemById('logo')
    logo.setPicturePath(root_code + '/templates/logo.svg')

    ##title
    ti = composition.itemById('project')
    ti.setText(project_name)

    ##zona
    zo = composition.itemById('zona')
    zo.setText(str(b.attribute(1).replace('_', '.')))

    ##pagina
    zo = composition.itemById('pagina')
    zo.setText(name)

    #form
    qr = composition.itemById('form')
    qr.setPicturePath(form_file)

    #qrcode
    qr = composition.itemById('qrcode')
    data = name
    qrpath = makeQR(data, name)
    qr.setPicturePath(qrpath)

    ##cbarres
    cbarres = composition.itemById('cbarres')
    cbarres.setText('*' + str(b.attribute(1).replace('_', '.')) + ',' +
                    str(b.attribute(3)) + ',' + str(b.attribute(4)) + '*')

    composition.refresh()

    zz = zl_layer.getFeatures(
        QgsFeatureRequest(QgsExpression('"name" = \'' + b.attribute(1) +
                                        '\'')))
    zz = [x for x in zz]
    z = zz[0].geometry()
    currentDistrict = unicode(zz[0].attribute(zl_field))

    image_name = str(b.attribute(1).replace('_', '-')) + '_' + str(
        b.id()) + '_form' + '_' + currentDistrict
    printRaster(composition, image_name, root_out)
    return
Esempio n. 37
0
def add_layers_to_canvas_with_custom_orders(order,
                                            impact_function,
                                            iface=None):
    """Helper to add layers to the map canvas following a specific order.

    From top to bottom in the legend:
        [
            ('FromCanvas', layer name, full layer URI, QML),
            ('FromAnalysis', layer purpose, layer group, None),
            ...
        ]

        The full layer URI is coming from our helper.

    :param order: Special structure the list of layers to add.
    :type order: list

    :param impact_function: The multi exposure impact function used.
    :type impact_function: MultiExposureImpactFunction

    :param iface: QGIS QgisAppInterface instance.
    :type iface: QgisAppInterface
    """
    root = QgsProject.instance().layerTreeRoot()
    # Make all layers hidden.
    for child in root.children():
        child.setItemVisibilityChecked(False)

    group_analysis = root.insertGroup(0, impact_function.name)
    group_analysis.setItemVisibilityChecked(True)
    group_analysis.setCustomProperty(MULTI_EXPOSURE_ANALYSIS_FLAG, True)

    # Insert layers in the good order in the group.
    for layer_definition in order:
        if layer_definition[0] == FROM_CANVAS['key']:
            style = QDomDocument()
            style.setContent(layer_definition[3])
            layer = load_layer(layer_definition[2], layer_definition[1])[0]
            layer.importNamedStyle(style)
            QgsProject.instance().addMapLayer(layer, False)
            layer_node = group_analysis.addLayer(layer)
            layer_node.setItemVisibilityChecked(True)
        else:
            if layer_definition[2] == impact_function.name:
                for layer in impact_function.outputs:
                    if layer.keywords['layer_purpose'] == layer_definition[1]:
                        QgsProject.instance().addMapLayer(layer, False)
                        layer_node = group_analysis.addLayer(layer)
                        layer_node.setItemVisibilityChecked(True)
                        try:
                            title = layer.keywords['title']
                            if qgis_version() >= 21800:
                                layer.setName(title)
                            else:
                                layer.setLayerName(title)
                        except KeyError:
                            pass
                        break
            else:
                for sub_impact_function in impact_function.impact_functions:
                    # Iterate over each sub impact function used in the
                    # multi exposure analysis.
                    if sub_impact_function.name == layer_definition[2]:
                        for layer in sub_impact_function.outputs:
                            purpose = layer_definition[1]
                            if layer.keywords['layer_purpose'] == purpose:
                                QgsProject.instance().addMapLayer(layer, False)
                                layer_node = group_analysis.addLayer(layer)
                                layer_node.setItemVisibilityChecked(True)
                                try:
                                    title = layer.keywords['title']
                                    if qgis_version() >= 21800:
                                        layer.setName(title)
                                    else:
                                        layer.setLayerName(title)
                                except KeyError:
                                    pass
                                break

    if iface:
        iface.setActiveLayer(impact_function.analysis_impacted)
Esempio n. 38
0
    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
Esempio n. 39
0
    def testSaveLoadTemplate(self):
        tmpfile = os.path.join(self.basetestpath, 'testTemplate.qpt')

        p = QgsProject()
        l = QgsLayout(p)
        l.initializeDefaults()

        # add some items
        item1 = QgsLayoutItemLabel(l)
        item1.setId('xxyyxx')
        item1.attemptMove(QgsLayoutPoint(4, 8, QgsUnitTypes.LayoutMillimeters))
        item1.attemptResize(QgsLayoutSize(18, 12, QgsUnitTypes.LayoutMillimeters))
        l.addItem(item1)
        item2 = QgsLayoutItemLabel(l)
        item2.setId('zzyyzz')
        item2.attemptMove(QgsLayoutPoint(1.4, 1.8, QgsUnitTypes.LayoutCentimeters))
        item2.attemptResize(QgsLayoutSize(2.8, 2.2, QgsUnitTypes.LayoutCentimeters))
        l.addItem(item2)

        uuids = {item1.uuid(), item2.uuid()}
        original_uuids = {item1.uuid(), item2.uuid()}

        self.assertTrue(l.saveAsTemplate(tmpfile, QgsReadWriteContext()))

        l2 = QgsLayout(p)
        with open(tmpfile) as f:
            template_content = f.read()
        doc = QDomDocument()
        doc.setContent(template_content)

        # adding to existing items
        new_items, ok = l2.loadFromTemplate(doc, QgsReadWriteContext(), False)
        self.assertTrue(ok)
        self.assertEqual(len(new_items), 2)
        items = l2.items()
        self.assertTrue([i for i in items if i.id() == 'xxyyxx'])
        self.assertTrue([i for i in items if i.id() == 'zzyyzz'])
        self.assertTrue(new_items[0] in l2.items())
        self.assertTrue(new_items[1] in l2.items())
        # double check that new items have a unique uid
        self.assertNotIn(new_items[0].uuid(), uuids)
        self.assertIn(new_items[0].templateUuid(), original_uuids)
        uuids.add(new_items[0].uuid())
        self.assertNotIn(new_items[1].uuid(), uuids)
        self.assertIn(new_items[1].templateUuid(), original_uuids)
        uuids.add(new_items[1].uuid())

        # adding to existing items
        new_items2, ok = l2.loadFromTemplate(doc, QgsReadWriteContext(), False)
        self.assertTrue(ok)
        self.assertEqual(len(new_items2), 2)
        items = l2.items()
        self.assertEqual(len(items), 4)
        self.assertTrue([i for i in items if i.id() == 'xxyyxx'])
        self.assertTrue([i for i in items if i.id() == 'zzyyzz'])
        self.assertTrue(new_items[0] in l2.items())
        self.assertTrue(new_items[1] in l2.items())
        self.assertTrue(new_items2[0] in l2.items())
        self.assertTrue(new_items2[1] in l2.items())
        self.assertNotIn(new_items2[0].uuid(), uuids)
        self.assertIn(new_items2[0].templateUuid(), original_uuids)
        uuids.add(new_items[0].uuid())
        self.assertNotIn(new_items2[1].uuid(), uuids)
        self.assertIn(new_items2[1].templateUuid(), original_uuids)
        uuids.add(new_items[1].uuid())

        # clearing existing items
        new_items3, ok = l2.loadFromTemplate(doc, QgsReadWriteContext(), True)
        self.assertTrue(ok)
        self.assertEqual(len(new_items3), 3) # includes page
        items = l2.items()
        self.assertTrue([i for i in items if isinstance(i, QgsLayoutItem) and i.id() == 'xxyyxx'])
        self.assertTrue([i for i in items if isinstance(i, QgsLayoutItem) and i.id() == 'zzyyzz'])
        self.assertTrue(new_items3[0] in l2.items())
        self.assertTrue(new_items3[1] in l2.items())
        self.assertIn(new_items3[0].templateUuid(), original_uuids)
        self.assertIn(new_items3[1].templateUuid(), original_uuids)
        self.assertEqual(l2.itemByUuid(new_items3[0].templateUuid(), True), new_items3[0])
        self.assertEqual(l2.itemByUuid(new_items3[1].templateUuid(), True), new_items3[1])
Esempio n. 40
0
    def parse_xml(self):
        """Parse the xml file. Returns false if there is failure."""
        xml_file = QFile(self._xml_path)
        if not xml_file.open(QIODevice.ReadOnly):
            return False

        document = QDomDocument()
        if not document.setContent(xml_file):
            return False

        xml_file.close()

        document_element = document.documentElement()
        if document_element.tagName() != 'qgis_style':
            return False

        # Get all the symbols
        self._symbols = []
        symbols_element = document_element.firstChildElement('symbols')
        symbol_element = symbols_element.firstChildElement()
        context = QgsReadWriteContext()
        context.setPathResolver(QgsProject.instance().pathResolver())
        while not symbol_element.isNull():
            if symbol_element.tagName() == 'symbol':
                symbol = QgsSymbolLayerUtils.loadSymbol(
                    symbol_element, context)
                if symbol:
                    self._symbols.append({
                        'name':
                        symbol_element.attribute('name'),
                        'symbol':
                        symbol
                    })
            symbol_element = symbol_element.nextSiblingElement()

        # Get all the colorramps
        self._colorramps = []
        ramps_element = document_element.firstChildElement('colorramps')
        ramp_element = ramps_element.firstChildElement()
        while not ramp_element.isNull():
            if ramp_element.tagName() == 'colorramp':
                colorramp = QgsSymbolLayerUtils.loadColorRamp(ramp_element)
                if colorramp:
                    self._colorramps.append({
                        'name':
                        ramp_element.attribute('name'),
                        'colorramp':
                        colorramp
                    })

            ramp_element = ramp_element.nextSiblingElement()

        # Get all the TextFormats - textformats - textformat
        self._textformats = []
        textformats_element = document_element.firstChildElement('textformats')
        textformat_element = textformats_element.firstChildElement()
        while not textformat_element.isNull():
            if textformat_element.tagName() == 'textformat':
                textformat = QgsTextFormat()
                textformat.readXml(textformat_element, QgsReadWriteContext())
                if textformat:
                    self._textformats.append({
                        'name':
                        textformat_element.attribute('name'),
                        'textformat':
                        textformat
                    })
            textformat_element = textformat_element.nextSiblingElement()

        # Get all the LabelSettings - labelsettings - labelsetting -
        #  QgsPalLayerSettings.readXML?
        self._labelsettings = []
        labels_element = document_element.firstChildElement('labelsettings')
        label_element = labels_element.firstChildElement()

        while not label_element.isNull():
            if label_element.tagName() == 'labelsetting':
                labelsettings = QgsPalLayerSettings()
                labelsettings.readXml(label_element, QgsReadWriteContext())
                if labelsettings:
                    self._labelsettings.append({
                        'name':
                        label_element.attribute('name'),
                        'labelsettings':
                        labelsettings
                    })
            label_element = label_element.nextSiblingElement()
        return True
Esempio n. 41
0
def mkDiv(b, z, qptDivision, project_name, root_out, zl_layer, zl_field,
          di_layer, di_field, di_name):

    root_code = os.path.dirname(os.path.realpath(__file__))
    Lz = zl_layer  #QgsProject.instance().mapLayer(mapL['zones'])
    debug(b.attributes())
    #angle = b.attribute('ang')
    angle = b.attribute(2)
    #esto visulamente es correcto
    ##pero me fastidia la lectira posterior porque no dejo rastro de esta manipulacion
    ##para el escaneo posterio deberia de modificar el orden de los bounds en el qr y en el pie de pagina

    if angle > 45:
        angle = angle - 90
    elif angle < -45:
        angle = angle + 90

    # sql = '"name" = \''+b.attribute('name')+'\''
    # sql += ' AND "x" = '+str(b.attribute('x'))
    # sql += ' AND "y" = '+str(b.attribute('y'))
    #filter('divisions', sql)

    sql = '"name" = \'' + b.attribute(1) + '\''
    sql += ' AND "x" = ' + str(b.attribute(3))
    sql += ' AND "y" = ' + str(b.attribute(4))

    QgsProject.instance().mapLayer(DVL).setSubsetString(sql)

    sql2 = '"name" = \'' + b.attribute(1) + '\''
    #sql2 = '"name" = \'' + b.attribute('name') + '\''
    #filter('divisions2', sql2)
    QgsProject.instance().mapLayer(DVL2).setSubsetString(sql)

    template_file = open(qptDivision, 'r')
    template_content = template_file.read()
    template_file.close()
    document = QDomDocument()
    document.setContent(template_content)

    p = QgsProject().instance()
    composition = QgsLayout(p)
    composition.loadFromTemplate(document, QgsReadWriteContext())

    ##mapa principal
    map_item = composition.itemById('mapa')
    map_item.setKeepLayerStyles(True)
    map_item.setKeepLayerSet(True)
    map_item.setFollowVisibilityPreset(True)
    map_item.setFollowVisibilityPresetName('_szona_big')

    map_item.setMapRotation(-angle)  ########
    cc = b.geometry().centroid().asPoint()
    coordsDesc = str(b.geometry().asWkt())[10:][:-2].split(', ')

    b.geometry().rotate(-angle, cc)
    rBound = b.geometry().boundingBox()
    map_item.zoomToExtent(rBound)

    ##mapa 2
    map_item2 = composition.itemById('minimapa')
    map_item2.setKeepLayerStyles(True)
    map_item2.setKeepLayerSet(True)
    map_item2.setFollowVisibilityPreset(True)
    map_item2.setFollowVisibilityPresetName('_szona_small')

    #cuidado que aqu´i se lia con valor integer o string
    zz = zl_layer.getFeatures(
        QgsFeatureRequest(QgsExpression('"name" = \'' + b.attribute(1) +
                                        '\'')))
    zz = [x for x in zz]
    z = zz[0].geometry()
    map_item2.zoomToExtent(z.boundingBox())

    ##barrio y distrito
    distrito = composition.itemById('distrito')
    distrito.setText('districte : ' + unicode(zz[0].attribute('d_name')))

    barrio = composition.itemById('barrio')

    fields = [e.name() for e in zz[0].fields().toList()]
    if 'b_name' in fields:
        barrio.setText('barri : ' + zz[0].attribute('b_name'))
    else:
        barrio.setText('zona : ' + zz[0].attribute('name').replace('_', '.'))

    ##anotacion coordenadas
    coordsDesc = [c.split(' ') for c in coordsDesc]

    coords = composition.itemById('coordenadas')
    coords.setText(' aX: '+str(round(float(coordsDesc[0][0]),0))+ \
                   ' ay: '+str(round(float(coordsDesc[0][1]),0))+ \
                   ' bX: '+str(round(float(coordsDesc[1][0]),0))+ \
                   ' by: '+str(round(float(coordsDesc[1][1]),0))+ \
                   ' cX: '+str(round(float(coordsDesc[2][0]),0))+ \
                   ' cy: '+str(round(float(coordsDesc[2][1]),0))+ \
                   ' dX: '+str(round(float(coordsDesc[3][0]),0))+ \
                   ' dy: '+str(round(float(coordsDesc[3][1]),0))
                   )

    ##zona
    zo = composition.itemById('zona')
    zo.setText(str(b.attribute(1).replace('_', '.')))

    ##title
    ti = composition.itemById('project')
    ti.setText(project_name)

    ##cbarres
    #cb_name = 'cb_'+str(b.attribute('name').replace('_', '.'))+'_'+str(b.attribute('x'))+'_'+str(b.attribute('y'))
    cb_text = '*' + str(b.attribute(1).replace('_', '.')) + ',' + str(
        b.attribute(3)) + ',' + str(b.attribute(4)) + '*'
    #makeBarcode(cb_text, cb_name)

    cbarres = composition.itemById('cbarres')
    cbarres.setText(cb_text)

    #qrcode
    name = str(b.attribute(1).replace('_', '.')) + '_' + str(
        b.attribute(3)) + '_' + str(b.attribute(4))
    qr = composition.itemById('qrcode')
    data =  name+' '+ \
            str(round(float(coordsDesc[0][0]),3))+' '+ \
            str(round(float(coordsDesc[0][1]),3))+', '+ \
            str(round(float(coordsDesc[1][0]),3))+' '+ \
            str(round(float(coordsDesc[1][1]),3))+', '+ \
            str(round(float(coordsDesc[2][0]),3))+' '+ \
            str(round(float(coordsDesc[2][1]),3))+', '+ \
            str(round(float(coordsDesc[3][0]),3))+' '+ \
            str(round(float(coordsDesc[3][1]),3))

    qrpath = makeQR(data, name)
    qr.setPicturePath(qrpath)

    #pagina
    pagina = composition.itemById('pagina')
    pagina.setText(name)

    #norte
    corners = composition.itemById('corners')
    corners.setPicturePath(root_code + '/templates/corners_a4.svg')

    logo = composition.itemById('logo')
    logo.setPicturePath(root_code + '/templates/logo.svg')

    norte = composition.itemById('norte')
    norte.setPicturePath(root_code + '/templates/norte.svg')
    norte.setRotation(angle)

    composition.refresh()
    currentDistrict = unicode(zz[0].attribute(zl_field))
    image_name = str(b.attribute(1).replace('_', '-')) + '_' + str(
        b.id()) + '_' + currentDistrict
    printRaster(composition, image_name, root_out)
    return
Esempio n. 42
0
def mkChapter(b, qptChapter, project_name, root_out, zl_layer, zl_field,
              di_layer, di_field, di_name):
    """
    b es un bound
    """
    root_code = os.path.dirname(os.path.realpath(__file__))
    Lz = zl_layer  #QgsProject.instance().mapLayer(mapL['zones'])

    file_qptChapter = open(qptChapter, 'r')
    template_content_chapter = file_qptChapter.read()
    file_qptChapter.close()

    ###
    #filter('zones', '"name" = \''+b.attribute('name')+'\'' )#cuidado si el valor es integer o string
    #filter('zones2', '"name" = \''+b.attribute('name')+'\'' )#cuidado si el valor es integer o string
    #filter('divisions', '"name" = \''+b.attribute('name')+'\'' )
    #filter('divisions2', '"name" = \'' + b.attribute('name') + '\'')

    # QgsProject.instance().mapLayer(ZVL).setSubsetString( '"name" = \''+b.attribute('name')+'\'' )
    # QgsProject.instance().mapLayer(DVL).setSubsetString('"name" = \''+b.attribute('name')+'\'' )
    # QgsProject.instance().mapLayer(DVL2).setSubsetString('"name" = \''+b.attribute('name')+'\'' )

    # QgsProject.instance().mapLayer(ZVL).setSubsetString( '"%s" = \'%s\'' %(zl_field, b.attribute(zl_field)) )
    # QgsProject.instance().mapLayer(DVL).setSubsetString('"%s" = \'%s\'' %(di_field, b.attribute(zl_field))  )
    # QgsProject.instance().mapLayer(DVL2).setSubsetString('"%s" = \'%s\'' %(di_field, b.attribute(zl_field)) )

    ### seleccionamos la zona
    #zz = Lz.getFeatures(QgsFeatureRequest(QgsExpression('"name" = \''+b.attribute('name')+'\''))) #cuidado si el valor es integer o string
    print('zz', '"%s" = \'%s\'' % (zl_field, b.attribute(zl_field)))
    zz = Lz.getFeatures(
        QgsFeatureRequest(
            QgsExpression('"%s" = \'%s\'' % (zl_field, b.attribute(zl_field))))
    )  #cuidado si el valor es integer o string

    zz = [x for x in zz]

    # escogemos el distrito correspondiente a la zona
    #filter('districtes', '"name" = \''+unicode(zz[0].attribute('d_name'))+'\'' )
    di_layer.setSubsetString('"' + di_field + '" = \'' +
                             unicode(zz[0].attribute(zl_field)) + '\'')

    global currentDistrict
    #currentDistrict = unicode(zz[0].attribute('d_id'))
    currentDistrict = unicode(zz[0].attribute(zl_field))

    #coje la geometria del distriro
    #distri = QgsProject.instance().mapLayer(mapL['districtes'])
    gd = [d for d in di_layer.getFeatures()][0]

    #canvas = QgsMapCanvas()
    document = QDomDocument()
    document.setContent(template_content_chapter)

    p = QgsProject().instance()
    composition = QgsLayout(p)
    composition.loadFromTemplate(document, QgsReadWriteContext())

    ##
    bounds = (b.geometry()).boundingBox()

    map_item = composition.itemById('mapa')
    map_item.zoomToExtent(bounds)
    map_item.setKeepLayerStyles(True)
    map_item.setKeepLayerSet(True)
    map_item.setFollowVisibilityPreset(True)
    map_item.setFollowVisibilityPresetName('_zona_big')

    map_item_distri = composition.itemById('mapDistrito')
    map_item_distri.zoomToExtent(gd.geometry().boundingBox())
    map_item_distri.setKeepLayerStyles(True)
    map_item_distri.setKeepLayerSet(True)
    map_item_distri.setFollowVisibilityPreset(True)
    map_item_distri.setFollowVisibilityPresetName('_zona_small')

    ##title
    ti = composition.itemById('project')
    ti.setText(project_name)

    ##zona
    zo = composition.itemById('zona')
    zo.setText(str(b.attribute('id')))

    corners = composition.itemById('corners')
    corners.setPicturePath(root_code + '/templates/corners_a4.svg')

    logo = composition.itemById('logo')
    logo.setPicturePath(root_code + '/templates/logo.svg')

    #norte = composition.itemById('norte')
    #norte.setPicturePath(root_code+'templates/norte.svg')
    #norte.setRotation(angle)

    ##barrio y distrito
    distrito = composition.itemById('distrito')
    distrito.setText('districte : ' + unicode(zz[0].attribute('d_name')))
    barrio = composition.itemById('barrio')
    fields = [e.name() for e in zz[0].fields().toList()]
    if 'b_name' in fields:
        barrio.setText('barri : ' + zz[0].attribute('b_name'))  #legacy
    else:
        barrio.setText('zona : ' + zz[0].attribute('name').replace('_', '.'))

    composition.refresh()
    image_name = str(b.attribute('name').replace('_',
                                                 '-')) + '_' + currentDistrict
    printRaster(composition, image_name, root_out)

    # filter('divisions', '' )
    # filter('divisions2', '' )
    # filter('districtes', '' )

    QgsProject.instance().mapLayer(DVL).setSubsetString('')
    QgsProject.instance().mapLayer(DVL2).setSubsetString('')

    return
Esempio n. 43
0
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()