Ejemplo n.º 1
0
    def testEditorActionCtor(self):

        parent = QgsAttributeEditorContainer('container', None)
        editor_action = QgsAttributeEditorAction(self.action1, parent)
        self.assertEqual(QUuid(editor_action.action(self.layer).id()),
                         self.action_id1)
        self.assertEqual(
            editor_action.action(self.layer).id(), self.action1.id())

        # Lazy load
        editor_action = QgsAttributeEditorAction(self.action1.id(), parent)
        self.assertEqual(QUuid(editor_action.action(self.layer).id()),
                         self.action_id1)
        self.assertEqual(
            editor_action.action(self.layer).id(), self.action1.id())
Ejemplo n.º 2
0
    def testRemoveActions(self):
        """ test removing actions """

        # add an action
        self.manager.addAction(QgsAction.GenericPython, 'test_action', 'i=1')

        # clear the manager and check that it's empty
        self.manager.clearActions()
        self.assertEqual(self.manager.actions(), [])

        # add some actions
        id1 = self.manager.addAction(QgsAction.GenericPython, 'test_action', 'i=1')
        id2 = self.manager.addAction(QgsAction.GenericPython, 'test_action2', 'i=2')
        id3 = self.manager.addAction(QgsAction.GenericPython, 'test_action3', 'i=3')

        # remove non-existent action
        self.manager.removeAction(QUuid.createUuid())

        # remove them one by one
        self.manager.removeAction(id2)
        self.assertEqual(len(self.manager.actions()), 2)
        self.assertEqual(self.manager.action(id1).name(), 'test_action')
        self.assertEqual(self.manager.action(id3).name(), 'test_action3')
        self.manager.removeAction(id1)
        self.assertEqual(len(self.manager.actions()), 1)
        self.assertEqual(self.manager.action(id3).name(), 'test_action3')
        self.manager.removeAction(id3)
        self.assertEqual(len(self.manager.actions()), 0)
Ejemplo n.º 3
0
    def testDefaultAction(self):
        """ test default action for layer"""

        self.manager.clearActions()
        action1 = QgsAction(QgsAction.GenericPython, 'test_action', '', 'i=1', False, actionScopes={'Feature'})
        self.manager.addAction(action1)
        action2 = QgsAction(QgsAction.GenericPython, 'test_action2', 'i=2')
        self.manager.addAction(action2)

        # initially should be not set
        self.assertFalse(self.manager.defaultAction('Feature').isValid())

        # set bad default action
        self.manager.setDefaultAction('Feature', QUuid.createUuid())
        self.assertFalse(self.manager.defaultAction('Feature').isValid())

        # set good default action
        self.manager.setDefaultAction('Feature', action1.id())
        self.assertTrue(self.manager.defaultAction('Feature').isValid())
        self.assertEqual(self.manager.defaultAction('Feature').id(), action1.id())
        self.assertNotEqual(self.manager.defaultAction('Feature').id(), action2.id())

        # if default action is removed, should be reset to -1
        self.manager.clearActions()
        self.assertFalse(self.manager.defaultAction('Feature').isValid())
    def testRemoveActions(self):
        """ test removing actions """

        # add an action
        self.manager.addAction(QgsAction.GenericPython, 'test_action', 'i=1')

        # clear the manager and check that it's empty
        self.manager.clearActions()
        self.assertEqual(self.manager.actions(), [])

        # add some actions
        id1 = self.manager.addAction(QgsAction.GenericPython, 'test_action', 'i=1')
        id2 = self.manager.addAction(QgsAction.GenericPython, 'test_action2', 'i=2')
        id3 = self.manager.addAction(QgsAction.GenericPython, 'test_action3', 'i=3')

        # remove non-existent action
        self.manager.removeAction(QUuid.createUuid())

        # remove them one by one
        self.manager.removeAction(id2)
        self.assertEqual(len(self.manager.actions()), 2)
        self.assertEqual(self.manager.action(id1).name(), 'test_action')
        self.assertEqual(self.manager.action(id3).name(), 'test_action3')
        self.manager.removeAction(id1)
        self.assertEqual(len(self.manager.actions()), 1)
        self.assertEqual(self.manager.action(id3).name(), 'test_action3')
        self.manager.removeAction(id3)
        self.assertEqual(len(self.manager.actions()), 0)
    def testDefaultAction(self):
        """ test default action for layer"""

        self.manager.clearActions()
        action1 = QgsAction(QgsAction.GenericPython, 'test_action', '', 'i=1', False, actionScopes={'Feature'})
        self.manager.addAction(action1)
        action2 = QgsAction(QgsAction.GenericPython, 'test_action2', 'i=2')
        self.manager.addAction(action2)

        # initially should be not set
        self.assertFalse(self.manager.defaultAction('Feature').isValid())

        # set bad default action
        self.manager.setDefaultAction('Feature', QUuid.createUuid())
        self.assertFalse(self.manager.defaultAction('Feature').isValid())

        # set good default action
        self.manager.setDefaultAction('Feature', action1.id())
        self.assertTrue(self.manager.defaultAction('Feature').isValid())
        self.assertEqual(self.manager.defaultAction('Feature').id(), action1.id())
        self.assertNotEqual(self.manager.defaultAction('Feature').id(), action2.id())

        # if default action is removed, should be reset to -1
        self.manager.clearActions()
        self.assertFalse(self.manager.defaultAction('Feature').isValid())
Ejemplo n.º 6
0
    def testDefaultAction(self):
        """ test default action for layer"""

        self.manager.clearActions()
        action1 = QgsAction(QgsAction.GenericPython, "test_action", "", "i=1", False, actionScopes={"Feature"})
        self.manager.addAction(action1)
        action2 = QgsAction(QgsAction.GenericPython, "test_action2", "i=2")
        self.manager.addAction(action2)

        # initially should be not set
        self.assertFalse(self.manager.defaultAction("Feature").isValid())

        # set bad default action
        self.manager.setDefaultAction("Feature", QUuid.createUuid())
        self.assertFalse(self.manager.defaultAction("Feature").isValid())

        # set good default action
        self.manager.setDefaultAction("Feature", action1.id())
        self.assertTrue(self.manager.defaultAction("Feature").isValid())
        self.assertEquals(self.manager.defaultAction("Feature").id(), action1.id())
        self.assertNotEquals(self.manager.defaultAction("Feature").id(), action2.id())

        # if default action is removed, should be reset to -1
        self.manager.clearActions()
        self.assertFalse(self.manager.defaultAction("Feature").isValid())
Ejemplo n.º 7
0
    def testSetAction(self):

        parent = QgsAttributeEditorContainer('container', None)
        editor_action = QgsAttributeEditorAction(self.action1, parent)

        editor_action.setAction(self.action2)
        self.assertEqual(QUuid(editor_action.action(self.layer).id()),
                         self.action_id2)
Ejemplo n.º 8
0
    def setUpClass(cls):
        cls.layer = QgsVectorLayer(
            "Point?field=fldtxt:string&field=fldint:integer&field=flddate:datetime",
            "test_layer", "memory")

        cls.action_id1 = QUuid.createUuid()
        cls.action_id2 = QUuid.createUuid()
        cls.action_id3 = QUuid.createUuid()
        cls.action1 = QgsAction(cls.action_id1, QgsAction.GenericPython,
                                'Test Action 1 Desc', 'i=1', '', False,
                                'Test Action 1 Short Title')
        cls.action2 = QgsAction(cls.action_id2, QgsAction.GenericPython,
                                'Test Action 2 Desc', 'i=2',
                                QGISAPP.appIconPath(), False,
                                'Test Action 2 Short Title')
        cls.action3 = QgsAction(cls.action_id3, QgsAction.GenericPython,
                                'Test Action 3 Desc', 'i=3', '', False)
    def __openDatabase(self, dbPath):
        """

        :type dbPath: str
        :return:
        """
        # QgsMessageLog.logMessage("(VFK) Open DB: {}".format(dbPath))
        if not QSqlDatabase.isDriverAvailable('QSQLITE'):
            raise VFKError(u'Databázový ovladač QSQLITE není dostupný.')

        connectionName = QUuid.createUuid().toString()
        db = QSqlDatabase.addDatabase("QSQLITE", connectionName)
        db.setDatabaseName(dbPath)
        if not db.open():
            raise VFKError(u'Nepodařilo se otevřít databázi. ')

        self.setProperty("connectionName", connectionName)
def getValue(val):
    value_type = val.WhichOneof('value_type')
    if value_type == 'null_value':
        return None
    elif value_type == 'string_value':
        return val.string_value
    elif value_type == 'int_value':
        return val.int_value
    elif value_type == 'long_value':
        return val.long_value
    elif value_type == 'bool_value':
        return val.bool_value
    elif value_type == 'double_value':
        return val.double_value
    elif value_type == 'float_value':
        return val.foat_value
    elif value_type == "geom_value":
        if len(val.geom_value) == 0:
            return None
        qgeom = QgsGeometry()
        qgeom.fromWkb(val.geom_value)
        return qgeom
    elif value_type == "byte_value":
        return val.byte_value
    elif value_type == "short_value":
        return val.short_value
    elif value_type == "char_value":
        return (val.char_value)
    elif value_type == "uuid_value":
        return QUuid(val.uuid_value)
    elif value_type == "datetime_value":
        return QDateTime.fromMSecsSinceEpoch(val.datetime_value)
    elif value_type == "date_value":
        dt = QDateTime.fromMSecsSinceEpoch(val.date_value)
        return dt.date()
    elif value_type == "time_value":
        dt = QDateTime.fromMSecsSinceEpoch(val.time_value)
        return dt.time()
    elif value_type == "timestamp_value":
        ts = val.timestamp_value
        dt = QDateTime.fromMSecsSinceEpoch(ts.seconds * 1000)
        dt.addMSecs(ts.nanos / 1000000)
        return dt.time()
    def do_aeag_menu(self,
                     fileName,
                     who,
                     menu=None,
                     visible=None,
                     expanded=None):
        self.canvas.freeze(True)
        self.canvas.setRenderFlag(False)
        group = None
        theLayer = None
        groupName = None
        QgsApplication.setOverrideCursor(Qt.WaitCursor)

        try:
            if (type(menu.parentWidget()) == QMenu or type(menu.parentWidget())
                    == QWidget) and self.optionCreateGroup:
                groupName = menu.title().replace("&", "")
                group = QgsProject.instance().layerTreeRoot().findGroup(
                    groupName)
                if group is None:
                    group = QgsProject.instance().layerTreeRoot().addGroup(
                        groupName)

            # load all layers
            if fileName is None and who is None and self.optionLoadAll:
                for action in menu.actions():
                    if ((action.text() != self.tr("&Load all"))
                            and (action.text() != "Load all")):
                        action.trigger()
            else:
                # read QGis project
                doc = QtXml.QDomDocument()
                xml = QFile(fileName)
                if xml.open(QIODevice.ReadOnly | QIODevice.Text):
                    doc.setContent(xml)

                # is project in relative path ?
                absolute = self.isAbsolute(doc)

                node = getFirstChildByTagNameValue(doc.documentElement(),
                                                   "maplayer", "id", who)
                if node:
                    idNode = node.namedItem("id")
                    layerType = node.toElement().attribute("type", "vector")
                    # give it a new id (for multiple import)
                    import re
                    newLayerId = "L%s" % re.sub("[{}-]", "",
                                                QUuid.createUuid().toString())
                    try:
                        idNode.firstChild().toText().setData(newLayerId)
                    except:
                        pass

                    # if relative path, adapt datasource
                    if not absolute:
                        try:
                            datasourceNode = node.namedItem("datasource")
                            ds = datasourceNode.firstChild().toText().data()
                            providerNode = node.namedItem("provider")
                            provider = providerNode.firstChild().toText().data(
                            )

                            if provider == "ogr" and (ds.find(".") == 0):
                                projectpath = QFileInfo(
                                    os.path.realpath(fileName)).path()
                                newlayerpath = projectpath + "/" + ds
                                datasourceNode.firstChild().toText().setData(
                                    newlayerpath)
                        except:
                            pass

                    # read modified layer node
                    if self.optionCreateGroup and group is not None:
                        """# sol 1 bug : layer incomplete
                        # because of API strange behaviour, we clone the layer... 
                        theLayer = QgsProject.instance().mapLayer(newLayerId)
                        cloneLayer = theLayer.clone()
                        # removing the first
                        QgsProject.instance().removeMapLayer(newLayerId)
                        # adding the clone...
                        treeNode = group.addLayer(cloneLayer)
                        treeNode.setExpanded(expanded)
                        treeNode.setItemVisibilityChecked(visible)"""

                        # solution 2, ok !
                        if layerType == "raster":
                            theLayer = QgsRasterLayer()
                        else:
                            theLayer = QgsVectorLayer()

                        theLayer.readLayerXml(node.toElement(),
                                              QgsReadWriteContext())
                        # needed
                        QgsProject.instance().addMapLayer(theLayer, False)
                        # add to group
                        treeNode = group.addLayer(theLayer)
                        treeNode.setExpanded(expanded)
                        treeNode.setItemVisibilityChecked(visible)
                    else:
                        # create layer
                        QgsProject.instance().readLayer(node)

        except Exception as e:
            QgsMessageLog.logMessage(
                'Menu from layer: Invalid ' +
                (fileName if fileName is not None else ""), 'Extensions')
            for m in e.args:
                QgsMessageLog.logMessage(m, 'Extensions')

        self.canvas.freeze(False)
        self.canvas.setRenderFlag(True)
        self.canvas.refresh()
        QgsApplication.restoreOverrideCursor()
    def addLayer(self,
                 uri,
                 fileName,
                 layerId,
                 group=None,
                 visible=False,
                 expanded=False):
        theLayer = None

        # read QGIS project
        doc, _ = self.getQgsDoc(fileName)

        # is project in relative path ?
        absolute = is_absolute(doc)
        trusted = project_trusted(doc)

        node = getFirstChildByTagNameValue(doc.documentElement(), "maplayer",
                                           "id", layerId)
        node = node.cloneNode()
        if node:
            idNode = node.namedItem("id")
            layerType = node.toElement().attribute("type", "vector")
            # give it a new id (for multiple import)
            newLayerId = "L%s" % re.sub("[{}-]", "",
                                        QUuid.createUuid().toString())
            try:
                idNode.firstChild().toText().setData(newLayerId)
            except Exception:
                pass

            # if relative path, adapt datasource
            if not absolute:
                try:
                    datasourceNode = node.namedItem("datasource")
                    ds = datasourceNode.firstChild().toText().data()
                    providerNode = node.namedItem("provider")
                    provider = providerNode.firstChild().toText().data()

                    if provider in ["ogr", "gdal"] and (ds.find(".") == 0):
                        projectpath = QFileInfo(uri).path()
                        newlayerpath = projectpath + "/" + ds
                        datasourceNode.firstChild().toText().setData(
                            newlayerpath)
                except Exception:
                    pass

            # read modified layer node
            if self.optionCreateGroup and group is not None:
                if layerType == "raster":
                    theLayer = QgsRasterLayer()
                else:
                    theLayer = QgsVectorLayer()
                    theLayer.setReadExtentFromXml(trusted)

                theLayer.readLayerXml(node.toElement(), QgsReadWriteContext())

                # Special process if the plugin "DB Style Manager" is installed
                flag = "use_db_style_manager_in_custom_menu" in os.environ
                if flag and "db-style-manager" in plugins:
                    try:
                        plugins["db-style-manager"].load_style_from_database(
                            theLayer)
                    except Exception:
                        self.log("DB-Style-Manager failed to load the style.")

                # needed
                QgsProject.instance().addMapLayer(theLayer, False)

                # add to group
                treeNode = group.insertLayer(0, theLayer)
                treeNode.setExpanded(expanded)
                treeNode.setItemVisibilityChecked(visible)
            else:
                # create layer
                theLayer = QgsProject.instance().readLayer(node)

            return QgsProject.instance().mapLayer(newLayerId)

        else:
            self.log("{} not found".format(layerId))

        return None
Ejemplo n.º 13
0
 def _gen_svg_path(self):
     """Generate a file path in temp folder."""
     return '{0}/{1}.svg'.format(self._temp_dir,
                                 QUuid.createUuid().toString())