Example #1
0
    def _load_table_layers(self, config_collection):
        """
        In order to use attribute tables in the composition, the
        corresponding vector layers need to be added to the layer
        registry. This method creates vector layers from the linked tables
        in the configuration items. This is required prior to creating the
        composition from file.
        :param config_collection: Table configuration collection built from
        the template file.
        :type config_collection: TableConfigurationCollection
        """
        table_configs = config_collection.items().values()

        v_layers = []

        for conf in table_configs:

            layer_name = conf.linked_table()

            v_layer = vector_layer(layer_name)

            if v_layer is None:
                return

            if not v_layer.isValid():
                return

            v_layers.append(v_layer)

            self._map_memory_layers.append(v_layer.id())

        self.map_registry.addMapLayers(v_layers, False)
Example #2
0
    def vector_layer(self):
        """
        Returns a QgsVectorLayer based on the configuration information
        specified in the mapper including the system-wide data connection
        properties.
        """
        from stdm.data.pg_utils import vector_layer

        if self._dbmodel is None:
            msg = QApplication.translate("ForeignKeyMapper",
                                         "Primary database model object not defined.")
            return None, msg

        filter_layer = vector_layer(self._entity.name)
        if filter_layer is None:
            msg = QApplication.translate("ForeignKeyMapper",
                "Vector layer could not be constructed from the database table.")

            return None, msg

        if not filter_layer.isValid():
            trans_msg = QApplication.translate("ForeignKeyMapper",
                u"The vector layer for '{0}' table is invalid.")
            msg = trans_msg.format(self._entity.name)

            return None, msg

        return filter_layer, ""
Example #3
0
    def _load_table_layers(self, config_collection):
        """
        In order to use attribute tables in the composition, the
        corresponding vector layers need to be added to the layer
        registry. This method creates vector layers from the linked tables
        in the configuration items. This is required prior to creating the
        composition from file.
        :param config_collection: Table configuration collection built from
        the template file.
        :type config_collection: TableConfigurationCollection
        """
        table_configs = config_collection.items().values()

        v_layers = []

        for conf in table_configs:

            layer_name = conf.linked_table()

            v_layer = vector_layer(layer_name)

            if v_layer is None:
                return

            if not v_layer.isValid():
                return

            v_layers.append(v_layer)

            self._map_memory_layers.append(v_layer.id())

        self.map_registry.addMapLayers(v_layers, False)
Example #4
0
    def set_table_vector_layer(self, table_name):
        """
        Creates a vector layer and appends it to the composer table item.
        :param table_name: Name of the linked table containing tabular
        information.
        :type table_name: str
        """
        self._notif_bar.clear()

        if not table_name:
            return

        v_layer = vector_layer(table_name)
        if v_layer is None:
            msg = QApplication.translate(
                "ComposerTableDataSourceEditor",
                "A vector layer could not be created from the table.")
            self._notif_bar.insertErrorNotification(msg)

            return

        if not v_layer.isValid():
            msg = QApplication.translate(
                "ComposerTableDataSourceEditor",
                "Invalid vector layer, the table will not be added.")
            self._notif_bar.insertErrorNotification(msg)

            return

        #No need to add the layer in the legend
        QgsMapLayerRegistry.instance().addMapLayer(v_layer, False)
        self._composer_table_item.setVectorLayer(
            v_layer)  # _composer_table_item is QgsComposerAttributeTable
        self._composer_table_item.update()
Example #5
0
def load_table_layers(config_collection):
    """
    In order to be able to use attribute tables in the composition, the
    corresponding vector layers need to be added to the layer
    registry. This method creates vector layers from the linked tables
    in the configuration items. This is required prior to creating the
    composition from file.
    :param config_collection: Table configuration collection built from
    the template file.
    :type config_collection: TableConfigurationCollection
    :returns: Valid layers that have been successfully added to the
    registry.
    :rtype: list
    """
    #table_configs = list(config_collection.items()).values()
    table_configs = config_collection.items()

    v_layers = []

    for conf in table_configs:
        layer_name = conf.linked_table()
        v_layer = vector_layer(layer_name)

        if v_layer is None:
            continue

        if not v_layer.isValid():
            continue

        v_layers.append(v_layer)

    QgsProject.instance().addMapLayers(v_layers, False)

    return v_layers
Example #6
0
def load_table_layers(config_collection):
    """
    In order to be able to use attribute tables in the composition, the
    corresponding vector layers need to be added to the layer
    registry. This method creates vector layers from the linked tables
    in the configuration items. This is required prior to creating the
    composition from file.
    :param config_collection: Table configuration collection built from
    the template file.
    :type config_collection: TableConfigurationCollection
    :returns: Valid layers that have been successfully added to the
    registry.
    :rtype: list
    """
    table_configs = config_collection.items().values()

    v_layers = []

    for conf in table_configs:
        layer_name = conf.linked_table()
        v_layer = vector_layer(layer_name)

        if v_layer is None:
            continue

        if not v_layer.isValid():
            continue

        v_layers.append(v_layer)

    QgsMapLayerRegistry.instance().addMapLayers(v_layers, False)

    return v_layers
Example #7
0
    def vector_layer(self):
        """
        Returns a QgsVectorLayer based on the configuration information
        specified in the mapper including the system-wide data connection
        properties.
        """
        from stdm.data.pg_utils import vector_layer

        if self._dbmodel is None:
            msg = QApplication.translate(
                "ForeignKeyMapper",
                "Primary database model object not defined.")
            return None, msg

        filter_layer = vector_layer(self._entity.name)
        if filter_layer is None:
            msg = QApplication.translate(
                "ForeignKeyMapper",
                "Vector layer could not be constructed from the database table."
            )

            return None, msg

        if not filter_layer.isValid():
            trans_msg = QApplication.translate(
                "ForeignKeyMapper",
                "The vector layer for '{0}' table is invalid.")
            msg = trans_msg.format(self._entity.name)

            return None, msg

        return filter_layer, ""
Example #8
0
    def __init__(self, search_config):
        self._config = search_config
        self._is_valid = self._validate_data_source()
        self._geom_columns = []
        self._valid_cols = OrderedDict()
        self._valid_filter_cols = OrderedDict()
        self._vector_layer = None
        self._column_types = {}

        # Set attributes if data source is valid
        if self._is_valid:
            self._geom_columns = table_column_names(self._config.data_source,
                                                    True)
            self._valid_cols = self._validate_columns()
            self._valid_filter_cols = self._validate_filter_columns()

            # Use the first geometry column in the list. Hence, it is
            # important to ensure that each data has not more than one
            # geometry column.
            geom_col = self._geom_columns[0] if len(
                self._geom_columns) > 0 else ''
            self._vector_layer = vector_layer(
                self._config.data_source,
                layer_name=self._config.display_name,
                geom_column=geom_col)
Example #9
0
    def set_table_vector_layer(self, table_name):
        """
        Creates a vector layer and appends it to the composer table item.
        :param table_name: Name of the linked table containing tabular
        information.
        :type table_name: str
        """
        self._notif_bar.clear()

        if not table_name:
            return

        v_layer = vector_layer(table_name)
        if v_layer is None:
            msg = QApplication.translate("ComposerTableDataSourceEditor",
                                         "A vector layer could not be created from the table.")
            self._notif_bar.insertErrorNotification(msg)

            return

        if not v_layer.isValid():
            msg = QApplication.translate("ComposerTableDataSourceEditor",
                                         "Invalid vector layer, the table will not be added.")
            self._notif_bar.insertErrorNotification(msg)

            return

        #No need to add the layer in the legend
        QgsMapLayerRegistry.instance().addMapLayer(v_layer, False)

        if len(self.composer_item().columns()) > 0:
            self._composer_table_item.setVectorLayer(v_layer)  # _composer_table_item is QgsComposerAttributeTable
        self._composer_table_item.update()
Example #10
0
 def _refresh_map_canvas(self):
     """
     Refresh map canvas on file source or feature type change
     :return: None
     :rtype: None
     """
     curr_layer = vector_layer(self.sp_table, geom_column=self.sp_col)
     layer_extent = curr_layer.extent()
     gpx_view.remove_vertex(self.map_canvas, self.point_row_attr)
     self.map_canvas.setExtent(layer_extent)
     self.map_canvas.refresh()
Example #11
0
    def create_layer(self):
        srid = None
        column = ''
        if self.entity.has_geometry_column():
            geom_cols = [col.name for col in self.entity.columns.values()
                         if col.TYPE_INFO == 'GEOMETRY']
            column = geom_cols[0]
            geom_col_obj = self.entity.columns[column]

            if geom_col_obj.srid >= 100000:
                srid = geom_col_obj.srid
        layer = vector_layer(self.entity.name, geom_column=column,
                             proj_wkt=srid)
        return layer
Example #12
0
    def create_layer(self):
        srid = None
        column = ''
        if self.entity.has_geometry_column():
            geom_cols = [col.name for col in self.entity.columns.values()
                         if col.TYPE_INFO == 'GEOMETRY']
            column = geom_cols[0]
            geom_col_obj = self.entity.columns[column]

            if geom_col_obj.srid >= 100000:
                srid = geom_col_obj.srid
        layer = vector_layer(self.entity.name, geom_column=column,
                             proj_wkt=srid)
        return layer
Example #13
0
def lht_plot_layer(scheme_id=-1, layer_name='Plot'):
    """
    Creates the plot layer for the given scheme and sets the name to plot.
    :param scheme_id: Primary key of the scheme for which the plots belong to
    and loads all the plots within it. If -1 it loads all plots in the table.
    :type scheme_id: int
    :param layer_name: Name assigned to the layer containing the plots.
    type: layer_name: str
    """
    if scheme_id == -1:
        sql = ''
    else:
        sql = 'scheme_id={0}'.format(scheme_id)

    return vector_layer(table_name='cb_plot',
                        sql=sql,
                        key='',
                        geom_column='geom',
                        layer_name=layer_name)
Example #14
0
    def column_to_fk_layer_join(self, column, layer, join_field):
        """
        Creates and executes the join by creating fk layer and running the join
        method using a column object.
        :param column: The column object
        :type column: Object
        :param layer: The layer to contain the joined fk layer
        :type layer: QgsVectorLayer
        :param join_field: The join field that is in the fk layer
        :type join_field: String
        """
        fk_entity = column.entity_relation.parent
        fk_layer = vector_layer(fk_entity.name, layer_name=fk_entity.name)
        QgsProject.instance().addMapLayer(fk_layer, False)
        # hide the fk id column
        column.hidden = True
        header = column.header()

        self.execute_layers_join(layer, column.name, header, fk_layer,
                                 join_field)
Example #15
0
    def on_bt_save_clicked(self):
        """
        Run when Qtablewidget button save is clicked
        """
        geom_list = []

        for key, vertex in self.vertex_dict.iteritems():
            if vertex[3] == Qt.Checked:
                geom_list.append(QgsPoint(vertex[1], vertex[2]))

        if self.active_layer_geometry_typ == 0:
            geom = QgsGeometry.fromPoint(geom_list[0])
        elif self.active_layer_geometry_typ == 1:
            geom = QgsGeometry.fromPolyline(geom_list)
        elif self.active_layer_geometry_typ == 2:
            geom = QgsGeometry.fromPolygon([geom_list])

        geom_wkb = geom.exportToWkt()

        non_sp_colms = non_spatial_table_columns(self.sp_table)

        for key, vertex in self.vertex_dict.iteritems():
            self.map_canvas.scene().removeItem(vertex[0])

        self.close()

        self.curr_layer = vector_layer(self.sp_table, geom_column=self.sp_col)

        self.iface.mapCanvas().setExtent(self.curr_layer.extent())

        self.iface.mapCanvas().refresh()

        srid = self.entity.columns[self.sp_col].srid
        #init form
        editor = EntityEditorDialog(self.entity, None, self.iface.mainWindow())

        model = editor.model()
        # add geometry into the model
        setattr(model, self.sp_col, 'SRID={};{}'.format(srid, geom_wkb))

        editor.exec_()
Example #16
0
    def column_to_fk_layer_join(self, column, layer, join_field):
        """
        Creates and executes the join by creating fk layer and running the join
        method using a column object.
        :param column: The column object
        :type column: Object
        :param layer: The layer to contain the joined fk layer
        :type layer: QgsVectorLayer
        :param join_field: The join field that is in the fk layer
        :type join_field: String
        """
        fk_entity = column.entity_relation.parent
        fk_layer = vector_layer(
            fk_entity.name,
            layer_name=fk_entity.name
        )
        QgsMapLayerRegistry.instance().addMapLayer(
            fk_layer, False
        )
        # hide the fk id column
        column.hidden = True
        header = column.header()

        self.execute_layers_join(layer, column.name, header, fk_layer, join_field)
Example #17
0
    def on_add_to_canvas_button_clicked(self):
        """
        Add STDM layer to map canvas.
        """
        if self.stdm_layers_combo.count() == 0:
            return

        sp_col_info = self.stdm_layers_combo.itemData(
            self.stdm_layers_combo.currentIndex())
        if sp_col_info is None:
            title = QApplication.translate('SpatialUnitManagerDockWidget',
                                           'Spatial Unit Manager')
            msg = QApplication.translate(
                'SpatialUnitManagerDockWidget',
                'Spatial Column Layer Could not be found')
            # Message: Spatial column information
            # could not be found
            QMessageBox.warning(self.iface.mainWindow(), title, msg)

        table_name, spatial_column = sp_col_info["table_name"], \
                                     sp_col_info["column_name"]

        # Check if the layer has already been
        layer_item = sp_col_info.get('item', None)

        layer_name = self.geom_col_layer_name(table_name, layer_item)

        if layer_name in self._map_registry_layer_names():
            layer = QgsProject.instance().mapLayersByName(layer_name)[0]
            self.iface.setActiveLayer(layer)
            return

        self.curr_lyr_table = table_name
        self.curr_lyr_sp_col = spatial_column

        if layer_item is not None:
            if isinstance(layer_item, str):
                layer_name = layer_item
            else:
                layer_name = layer_item.layer_display()

            entity = self._curr_profile.entity_by_name(table_name)
            if entity is not None:
                geom_col_obj = entity.columns[spatial_column]

                srid = None
                if geom_col_obj.srid >= 100000:
                    srid = geom_col_obj.srid

                curr_layer = vector_layer(table_name,
                                          geom_column=spatial_column,
                                          layer_name=layer_name,
                                          proj_wkt=srid)
            else:

                curr_layer = vector_layer(table_name,
                                          geom_column=spatial_column,
                                          layer_name=layer_name,
                                          proj_wkt=None)
        # for lookup layer.
        else:
            curr_layer = vector_layer(table_name, geom_column=spatial_column)

        if curr_layer is not None and curr_layer.isValid():
            if curr_layer.name() in self._map_registry_layer_names():
                return

            QgsProject.instance().addMapLayer(curr_layer)
            LayerUtils.tag_layer_as_stdm_layer(curr_layer)
            self.zoom_to_layer()

            self.onLayerAdded.emit(spatial_column, curr_layer)

            self.toggle_entity_multi_layers(curr_layer)

            self.set_canvas_crs(curr_layer)
            # Required in order for the layer name to be set
            if layer_name is not None:
                QTimer.singleShot(
                    100, lambda: self._set_layer_display_name(
                        curr_layer, layer_name))

            entity = self._curr_profile.entity_by_name(self.curr_lyr_table)
            fk_fields = self.join_fk_layer(curr_layer, entity)
            if entity is not None:
                self.sort_joined_columns(curr_layer, fk_fields)
                self.set_field_alias(curr_layer, entity, fk_fields)

        elif curr_layer is not None:
            msg = QApplication.translate(
                "Spatial Unit Manager",
                "'{0}.{1}' layer is invalid, it cannot "
                "be added to the map view.".format(table_name, spatial_column))
            QMessageBox.critical(self.iface.mainWindow(),
                                 'Spatial Unit Manager', msg)
Example #18
0
    def on_add_to_canvas_button_clicked(self):
        """
        Add STDM layer to map canvas.
        """
        if self.stdm_layers_combo.count() == 0:
            return

        sp_col_info = self.stdm_layers_combo.itemData(
            self.stdm_layers_combo.currentIndex()
        )
        if sp_col_info is None:
            title = QApplication.translate(
                'SpatialUnitManagerDockWidget',
                'Spatial Unit Manager'
            )
            msg = QApplication.translate(
                'SpatialUnitManagerDockWidget',
                'Spatial Column Layer Could not be found'
            )
            # Message: Spatial column information
            # could not be found
            QMessageBox.warning(self.iface.mainWindow(), title, msg)

        table_name, spatial_column = sp_col_info["table_name"], \
                                     sp_col_info["column_name"]

        # Check if the layer has already been
        layer_item = sp_col_info.get('item', None)

        layer_name = self.geom_col_layer_name(
            table_name, layer_item
        )

        if layer_name in self._map_registry_layer_names():
            layer = QgsMapLayerRegistry.instance().mapLayersByName(layer_name)[0]
            self.iface.setActiveLayer(layer)
            return

        self.curr_lyr_table = table_name
        self.curr_lyr_sp_col = spatial_column

        if not layer_item is None:
            if isinstance(layer_item, str) or isinstance(layer_item, unicode):
                layer_name = layer_item
            else:
                layer_name = layer_item.layer_display()

            entity = self._curr_profile.entity_by_name(table_name)
            if entity is not None:
                geom_col_obj = entity.columns[spatial_column]

                srid = None
                if geom_col_obj.srid >= 100000:
                    srid = geom_col_obj.srid

                curr_layer = vector_layer(
                    table_name,
                    geom_column=spatial_column,
                    layer_name=layer_name,
                    proj_wkt=srid
                )
            else:

                curr_layer = vector_layer(
                    table_name,
                    geom_column=spatial_column,
                    layer_name=layer_name,
                    proj_wkt=None
                )
        # for lookup layer.
        else:
            curr_layer = vector_layer(
                table_name, geom_column=spatial_column
            )


        if curr_layer.isValid():
            if curr_layer.name() in self._map_registry_layer_names():
                return

            QgsMapLayerRegistry.instance().addMapLayer(
                curr_layer
            )
            self.zoom_to_layer()

            self.onLayerAdded.emit(spatial_column, curr_layer)

            self.toggle_entity_multi_layers(curr_layer)

            self.set_canvas_crs(curr_layer)
            # Required in order for the layer name to be set
            if layer_name is not None:
                QTimer.singleShot(
                    100,
                    lambda: self._set_layer_display_name(
                        curr_layer,
                        layer_name
                    )
                )

            entity = self._curr_profile.entity_by_name(self.curr_lyr_table)
            fk_fields = self.join_fk_layer(curr_layer, entity)
            if entity is not None:
                self.sort_joined_columns(curr_layer, fk_fields)
                self.set_field_alias(curr_layer, entity, fk_fields)

        else:
            msg = QApplication.translate(
                "Spatial Unit Manager",
                "'{0}.{1}' layer is invalid, it cannot "
                "be added to the map view.".format(
                    table_name, spatial_column
                )
            )
            QMessageBox.critical(
                self.iface.mainWindow(),
                'Spatial Unit Manager',
                msg
            )
Example #19
0
    def on_add_to_canvas_button_clicked(self):
        """
        Add STDM layer to map canvas.
        """
        if self.stdm_layers_combo.count() == 0:
            return

        sp_col_info = self.stdm_layers_combo.itemData(
            self.stdm_layers_combo.currentIndex())
        if sp_col_info is None:
            title = QApplication.translate('SpatialUnitManagerDockWidget',
                                           'Spatial Unit Manager')
            msg = QApplication.translate(
                'SpatialUnitManagerDockWidget',
                'Spatial Column Layer Could not be found')
            # Message: Spatial column information
            # could not be found
            QMessageBox.warning(self.iface.mainWindow(), title, msg)

        table_name, spatial_column = sp_col_info["table_name"], \
                                     sp_col_info["column_name"]

        # Check if the layer has already been
        layer_item = sp_col_info.get('item', None)

        layer_name = self.geom_col_layer_name(table_name, layer_item)

        if layer_name in self._map_registry_layer_names():
            return

        # Used in gpx_table.py
        self.curr_lyr_table = table_name
        self.curr_lyr_sp_col = spatial_column

        if not layer_item is None:
            curr_layer = vector_layer(table_name,
                                      geom_column=spatial_column,
                                      layer_name=layer_item.layer_display())
        else:
            curr_layer = vector_layer(table_name, geom_column=spatial_column)

        if curr_layer.isValid():

            QgsMapLayerRegistry.instance().addMapLayer(curr_layer)

            self.toggle_entity_multi_layers(curr_layer)

            self.set_canvas_crs(curr_layer)
            # Required in order for the layer name to be set
            QTimer.singleShot(
                100, lambda: self._set_layer_display_name(
                    curr_layer, layer_item.layer_display()))
            self.zoom_to_layer()
            self.onLayerAdded.emit(spatial_column, curr_layer)
        else:
            msg = QApplication.translate(
                "Spatial Unit Manager",
                "'{0}.{1}' layer is invalid, it cannot "
                "be added to the map view.".format(table_name, spatial_column))
            QMessageBox.critical(self.iface.mainWindow(),
                                 'Spatial Unit Manager', msg)