Esempio n. 1
0
 def copyLayerViaXmlReadWrite(self, source, dest):
     # write to xml
     doc = QDomDocument("testdoc")
     elem = doc.createElement("maplayer")
     self.assertTrue(source.writeLayerXml(elem, doc, QgsPathResolver()))
     self.assertTrue(dest.readLayerXml(elem, QgsPathResolver()),
                     QgsProject.instance())
Esempio n. 2
0
    def testLoadLayerWithPreprocessor(self):
        """
        Test that custom path preprocessor is used when loading layers
        """
        lines_shp_path = os.path.join(TEST_DATA_DIR, 'moooooo.shp')

        lines_layer = QgsVectorLayer(lines_shp_path, 'Lines', 'ogr')
        self.assertFalse(lines_layer.isValid())
        p = QgsProject()
        p.addMapLayer(lines_layer)
        # save project to a temporary file
        temp_path = tempfile.mkdtemp()
        temp_project_path = os.path.join(temp_path, 'temp.qgs')
        self.assertTrue(p.write(temp_project_path))

        p2 = QgsProject()
        self.assertTrue(p2.read(temp_project_path))
        l = p2.mapLayersByName('Lines')[0]
        self.assertEqual(l.name(), 'Lines')
        self.assertFalse(l.isValid())

        # custom processor to fix path
        def my_processor(path):
            return path.replace('moooooo', 'lines')

        QgsPathResolver.setPathPreprocessor(my_processor)
        p3 = QgsProject()
        self.assertTrue(p3.read(temp_project_path))
        l = p3.mapLayersByName('Lines')[0]
        self.assertEqual(l.name(), 'Lines')
        # layer should have correct path now
        self.assertTrue(l.isValid())
Esempio n. 3
0
    def object_to_qlr(
            obj,
            input_file,
            output_path,
            context: Context,
            use_relative_paths: bool = False) -> Tuple[bool, Optional[str]]:
        """
        Converts an ESRI object to QLR
        """

        root_node, _ = LayerConverter.object_to_layers_and_tree(
            obj, input_file, context)

        output_path = QgsFileUtils.ensureFileNameHasExtension(
            output_path, ['qlr'])

        file = QFile(output_path)
        if not file.open(QFile.WriteOnly | QFile.Truncate):
            return False, file.errorString()

        rw_context = QgsReadWriteContext()
        if not use_relative_paths:
            rw_context.setPathResolver(QgsPathResolver())
        else:
            rw_context.setPathResolver(QgsPathResolver(output_path))

        doc = QDomDocument("qgis-layer-definition")
        res, error = QgsLayerDefinition.exportLayerDefinition(
            doc, root_node.children(), rw_context)
        if res:
            stream = QTextStream(file)
            doc.save(stream, 2)
            return True, None

        return res, error
Esempio n. 4
0
    def testInbuiltPath(self):
        """
        Test resolving and saving inbuilt data paths
        """
        path = "inbuilt:/data/world_map.shp"
        self.assertEqual(QgsPathResolver().readPath(path), QgsApplication.pkgDataPath() + '/resources/data/world_map.shp')

        self.assertEqual(QgsPathResolver().writePath(QgsApplication.pkgDataPath() + '/resources/data/world_map.shp'), 'inbuilt:/data/world_map.shp')
Esempio n. 5
0
        def run_test():
            def my_processor(path):
                return path.upper()

            id = QgsPathResolver.setPathPreprocessor(my_processor)
            self.assertTrue(id)
            self.assertEqual(QgsPathResolver().readPath('aaaaa'), 'AAAAA')
            return id
Esempio n. 6
0
    def testCustomPreprocessor(self):
        self.assertEqual(QgsPathResolver().readPath('aaaaa'), 'aaaaa')

        def run_test():
            def my_processor(path):
                return path.upper()

            QgsPathResolver.setPathPreprocessor(my_processor)
            self.assertEqual(QgsPathResolver().readPath('aaaaa'), 'AAAAA')

        run_test()
        gc.collect()
        # my_processor should be out of scope and cleaned up, unless things are working
        # correctly and ownership was transferred
        self.assertEqual(QgsPathResolver().readPath('aaaaa'), 'AAAAA')
    def __init__(self, iface):
        self.iface = iface
        self.pluginDir = os.path.dirname(__file__)
        self.dataPath = os.path.join(self.pluginDir, 'data')
        self.logos = RcLogos()
        self.logos.readFromCsv(os.path.join(self.dataPath, 'logos', 'logos.csv'))
        self.worldLayerPath = os.path.join(self.dataPath, 'sims_maps_resources.gpkg|layername=world_map')
        self.worldLayerId = None
        self.layoutBaseName = 'sims_layout'

        self.addIconPath()
        self.colorScheme = QgsSimsColorScheme()
        #self.addColorScheme()
        self.pathPreprocessorId = QgsPathResolver.setPathPreprocessor(self.simsMapsPathPreprocessor)

        # initialize locale
        locale = QSettings().value('locale/userLocale')[0:2]
        print(locale)
        locale_path = os.path.join(self.pluginDir, 'i18n', f'sims_maps_{locale}.qm')
        print(locale_path)

        if os.path.exists(locale_path):
            self.translator = QTranslator()
            self.translator.load(locale_path)

            if qVersion() > '4.3.3':
                QCoreApplication.installTranslator(self.translator)

        self.checkVersion()
Esempio n. 8
0
        def run_test():
            def my_processor(path):
                return 'x' + path + 'x'

            def my_processor2(path):
                return 'y' + path + 'y'

            id = QgsPathResolver.setPathPreprocessor(my_processor)
            self.assertTrue(id)

            self.assertEqual(QgsPathResolver().readPath('aaaaa'), 'xaaaaax')

            id2 = QgsPathResolver.setPathPreprocessor(my_processor2)
            self.assertTrue(id2)

            self.assertEqual(QgsPathResolver().readPath('aaaaa'), 'yxaaaaaxy')

            return id, id2
Esempio n. 9
0
    def testCustomPreprocessor(self):
        self.assertEqual(QgsPathResolver().readPath('aaaaa'), 'aaaaa')
        with self.assertRaises(KeyError):
            QgsPathResolver().removePathPreprocessor('bad')

        def run_test():
            def my_processor(path):
                return path.upper()

            id = QgsPathResolver.setPathPreprocessor(my_processor)
            self.assertTrue(id)
            self.assertEqual(QgsPathResolver().readPath('aaaaa'), 'AAAAA')
            return id

        id = run_test()
        gc.collect()
        # my_processor should be out of scope and cleaned up, unless things are working
        # correctly and ownership was transferred
        self.assertEqual(QgsPathResolver().readPath('aaaaa'), 'AAAAA')

        QgsPathResolver().removePathPreprocessor(id)
        self.assertEqual(QgsPathResolver().readPath('aaaaa'), 'aaaaa')

        # expect key error
        with self.assertRaises(KeyError):
            QgsPathResolver().removePathPreprocessor(id)
Esempio n. 10
0
    def testPathWriter(self):
        readerId = QgsPathResolver.setPathPreprocessor(self.__test_path_reader)
        writerId = QgsPathResolver.setPathWriter(self.__test__path_writer)

        lines_shp_path = os.path.join(TEST_DATA_DIR, 'lines.shp')

        lines_layer = QgsVectorLayer(lines_shp_path, 'Lines', 'ogr')
        self.assertTrue(lines_layer.isValid())
        p = QgsProject()
        p.addMapLayer(lines_layer)
        # save project to a temporary file
        temp_path = tempfile.mkdtemp()
        temp_project_path = os.path.join(temp_path, 'temp.qgs')
        self.assertTrue(p.write(temp_project_path))

        with open(temp_project_path) as f:
            self.assertTrue("@TEST_DATA_DIR@" in f.read())

        p2 = QgsProject()
        self.assertTrue(p2.read(temp_project_path))
        l = p2.mapLayersByName('Lines')[0]
        self.assertEqual(l.isValid(), True)
        self.assertEqual(l.source(), lines_shp_path)

        QgsPathResolver.removePathPreprocessor(readerId)
        QgsPathResolver.removePathWriter(writerId)
Esempio n. 11
0
    def testSaveFields(self):
        # Create a new memory layer with no fields
        myMemoryLayer = QgsVectorLayer(('Point?crs=epsg:4326&index=yes'),
                                       'test', 'memory')

        # Add some fields to the layer
        myFields = [
            QgsField('TestInt', QVariant.Int, 'integer', 2, 0),
            QgsField('TestLong', QVariant.LongLong, 'long', -1, 0),
            QgsField('TestDbl', QVariant.Double, 'double', 8, 6),
            QgsField('TestString', QVariant.String, 'string', 50, 0),
            QgsField('TestDate', QVariant.Date, 'date'),
            QgsField('TestTime', QVariant.Time, 'time'),
            QgsField('TestDateTime', QVariant.DateTime, 'datetime')
        ]
        assert myMemoryLayer.startEditing()
        for f in myFields:
            assert myMemoryLayer.addAttribute(f)
        assert myMemoryLayer.commitChanges()
        myMemoryLayer.updateFields()

        # Export the layer to a layer-definition-XML
        qlr = QgsLayerDefinition.exportLayerDefinitionLayers([myMemoryLayer],
                                                             QgsPathResolver())
        assert qlr is not None

        # Import the layer from the layer-definition-XML
        layers = QgsLayerDefinition.loadLayerDefinitionLayers(
            qlr, QgsPathResolver())
        assert layers is not None
        myImportedLayer = layers[0]
        assert myImportedLayer is not None

        # Check for the presence of the fields
        importedFields = myImportedLayer.fields()
        assert importedFields is not None
        for f in myFields:
            assert f == importedFields.field(f.name())
    def unload(self):
        try:
            self.iface.layoutDesignerOpened.disconnect()
        except Exception:
            pass
        try:
            self.iface.layoutDesignerClosed.disconnect()
        except Exception:
            pass
        try:
            self.actionCreateLayout.triggered.disconnect()
        except Exception:
            pass
        if self.pathPreprocessorId is not None:
            QgsPathResolver.removePathPreprocessor(self.pathPreprocessorId)
        # remove toolBar
        self.iface.removeToolBarIcon(self.actionCreateLayout)
        self.iface.mainWindow().removeToolBar(self.toolBar)
        del self.toolBar

        self.removeIconPath()
        self.removeColorScheme()
        self.removeWorldLayer()
Esempio n. 13
0
    def testChainedPreprocessors(self):
        """
        Test that chaining preprocessors works correctly
        """
        self.assertEqual(QgsPathResolver().readPath('aaaaa'), 'aaaaa')

        def run_test():
            def my_processor(path):
                return 'x' + path + 'x'

            def my_processor2(path):
                return 'y' + path + 'y'

            id = QgsPathResolver.setPathPreprocessor(my_processor)
            self.assertTrue(id)

            self.assertEqual(QgsPathResolver().readPath('aaaaa'), 'xaaaaax')

            id2 = QgsPathResolver.setPathPreprocessor(my_processor2)
            self.assertTrue(id2)

            self.assertEqual(QgsPathResolver().readPath('aaaaa'), 'yxaaaaaxy')

            return id, id2

        id, id2 = run_test()
        gc.collect()
        # my_processor should be out of scope and cleaned up, unless things are working
        # correctly and ownership was transferred
        self.assertEqual(QgsPathResolver().readPath('aaaaa'), 'yxaaaaaxy')

        QgsPathResolver().removePathPreprocessor(id)
        self.assertEqual(QgsPathResolver().readPath('aaaaa'), 'yaaaaay')

        # expect key error
        with self.assertRaises(KeyError):
            QgsPathResolver().removePathPreprocessor(id)

        QgsPathResolver().removePathPreprocessor(id2)
        self.assertEqual(QgsPathResolver().readPath('aaaaa'), 'aaaaa')

        with self.assertRaises(KeyError):
            QgsPathResolver().removePathPreprocessor(id2)
Esempio n. 14
0
    def testRelativeProject(self):
        """Test relative project paths can still resolve, regression #33200"""

        curdir = os.getcwd()
        os.chdir(os.path.join(TEST_DATA_DIR, 'qgis_server'))
        resolver = QgsPathResolver('./test_project.qgs')
        self.assertEqual(
            resolver.readPath('./testlayer.shp').replace("\\", "/"),
            os.path.join(TEST_DATA_DIR, 'qgis_server',
                         'testlayer.shp').replace("\\", "/"))
        self.assertEqual(
            resolver.readPath('testlayer.shp').replace("\\", "/"),
            os.path.join(TEST_DATA_DIR, 'qgis_server',
                         'testlayer.shp').replace("\\", "/"))
        resolver = QgsPathResolver('test_project.qgs')
        self.assertEqual(
            resolver.readPath('./testlayer.shp').replace("\\", "/"),
            os.path.join(TEST_DATA_DIR, 'qgis_server',
                         'testlayer.shp').replace("\\", "/"))
        self.assertEqual(
            resolver.readPath('testlayer.shp').replace("\\", "/"),
            os.path.join(TEST_DATA_DIR, 'qgis_server',
                         'testlayer.shp').replace("\\", "/"))
        os.chdir(curdir)
Esempio n. 15
0
    def __init__(self, id, gtotool, config, debug):
        super(run, self).__init__()
        try:
            self.debug = debug
            self.gtotool=gtotool
            self.gtomain = gtotool.gtomain
            self.info =gtotool.info
            self.metadata = self.gtomain.metadata
            templatedir = self.metadata.dirPrintLayouts
            self.iface = self.gtomain.iface
            #tool data
            template = config.get('template',None)
            activetool= config.get('active_tool',None)
            scale = config.get('scale',0)
            #init
            templatefile = None
            layoutname =config.get('layoutname', None)
            if template and layoutname is None:
                layoutname= os.path.splitext(template)[0]#default layoutname for template
            if self.debug:self.info.log("layoutname:",layoutname)
            prj = QgsProject.instance()
            projectLayoutManager = prj.layoutManager()#QgsLayoutManager
            self.layout = None
            if template is not None:
                templatefile = os.path.join(templatedir , template)
                if debug: self.info.log("template:",templatefile)
                if os.path.isfile(templatefile):
                    f= open(templatefile, 'r')
                    templateContent = f.read()
                    f.close()
                    doc=QDomDocument()
                    doc.setContent(templateContent)
                    pr = QgsPathResolver(templatefile)
                    rwc = QgsReadWriteContext()
                    rwc.setPathResolver(pr)
                    self.layout = QgsPrintLayout(prj)
                    self.layout.loadFromTemplate(doc,rwc)
                    self.layout.setName(layoutname)
                    projectLayoutManager.addLayout(self.layout)
            self.layout = projectLayoutManager.layoutByName(layoutname)
            if self.debug: self.info.log(type(self.layout))
            if self.debug and self.layout:self.info.log("found layout:",self.layout.name())
            if self.layout:
                result = self.iface.openLayoutDesigner(self.layout)#QgsLayoutDesignerInterface

                self.layoutview = result.view()#QgsLayoutView
                currenttool = self.layoutview.tool()#QgsLayoutViewTool
                if self.debug: self.info.log(currenttool.toolName())

                if activetool:
                    tool = QgsLayoutViewToolMoveItemContent(self.layoutview)
                    self.layoutview.setTool(tool)

                #itemMap = QgsLayoutItemMap(self.layout)
                referencemap = self.layout.referenceMap()
                referencemap.zoomToExtent(self.iface.mapCanvas().extent())
                if scale < 0:
                    referencemap.setScale(self.iface.mapCanvas().scale())
                elif scale > 0:
                    referencemap.setScale(scale)
                referencemap.refresh()

                if activetool:
                    menu = result.editMenu()
                    for a in menu.actions():
                        if a.objectName() == activetool:
                            if self.debug: self.info.log("set active tool:",activetool)
                            a.trigger()
                            break
                self.result = True
            else:
                self.result="Layout <%s> not found!" % layoutname
        except Exception as e:
            self.info.err(e)
 def testWithResolver(self):
     self.assertEqual(QgsPathResolver().readPath('localized:' + MAP_PATH),
                      ABSOLUTE_PATH)
     self.assertEqual(QgsPathResolver().writePath(ABSOLUTE_PATH),
                      'localized:' + MAP_PATH)