nextgis / qgis_reconstructline

QGIS plugin for making line out of points interactively
GNU General Public License v2.0
0 stars 3 forks source link

reconstruct_line.py Mise à jour pour QGIS3.16.3 #13

Closed CEZERT closed 2 years ago

CEZERT commented 2 years ago
# -*- coding: utf-8 -*-
"""
/***************************************************************************
 ReconstructLine
 QGIS tool to reconstruct linear features from points
                              -------------------
        begin                : 2015-03-23
        git sha              : $Format:%H$
        copyright            : (C) 2015 by NextGIS

        email                : info@nextgis.com
 ***************************************************************************/

/***************************************************************************
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 2 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 ***************************************************************************/
"""
from builtins import object
import numpy as np
from qgis.PyQt.QtCore import QSettings, QTranslator, qVersion, QCoreApplication, QObject, Qt
from qgis.PyQt.QtWidgets import QAction, QMessageBox
from qgis.PyQt.QtGui import QIcon
# Import the code for the dialog
import os.path
from qgis.core import *
from qgis.gui import *
from .connector import SOM1d
from .mst import MST

CURR_PATH = os.path.dirname(__file__)

class ReconstructLine(object):
    """QGIS Plugin Implementation."""

    def __init__(self, iface):
        """Constructor.

        :param iface: An interface instance that will be passed to this class
            which provides the hook by which you can manipulate the QGIS
            application at run time.
        :type iface: QgsInterface
        """
        # Save reference to the QGIS interface
        self.iface = iface
        # initialize plugin directory
        self.plugin_dir = os.path.dirname(__file__)
        # initialize locale
        locale = QSettings().value('locale/userLocale')[0:2]
        locale_path = os.path.join(
            self.plugin_dir,
            'i18n',
            'ReconstructLine_{}.qm'.format(locale))

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

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

        # Declare instance attributes
        self.actions = []
        self.menu = self.tr(u'&Reconstruct line')
        # TODO: We are going to let the user set this up in a future iteration
        self.toolbar = self.iface.addToolBar(u'ReconstructLine')
        self.toolbar.setObjectName(u'ReconstructLine')

    # noinspection PyMethodMayBeStatic
    def tr(self, message):
        """Get the translation for a string using Qt translation API.

        We implement this ourselves since we do not inherit QObject.

        :param message: String for translation.
        :type message: str, QString

        :returns: Translated version of message.
        :rtype: QString
        """
        # noinspection PyTypeChecker,PyArgumentList,PyCallByClass
        return QCoreApplication.translate('ReconstructLine', message)

    def add_action(
        self,
        icon_path,
        text,
        callback,
        enabled_flag=True,
        add_to_menu=True,
        add_to_toolbar=True,
        status_tip=None,
        whats_this=None,
        parent=None):
        """Add a toolbar icon to the toolbar.

        :param icon_path: Path to the icon for this action. Can be a resource
            path (e.g. ':/plugins/foo/bar.png') or a normal file system path.
        :type icon_path: str

        :param text: Text that should be shown in menu items for this action.
        :type text: str

        :param callback: Function to be called when the action is triggered.
        :type callback: function

        :param enabled_flag: A flag indicating if the action should be enabled
            by default. Defaults to True.
        :type enabled_flag: bool

        :param add_to_menu: Flag indicating whether the action should also
            be added to the menu. Defaults to True.
        :type add_to_menu: bool

        :param add_to_toolbar: Flag indicating whether the action should also
            be added to the toolbar. Defaults to True.
        :type add_to_toolbar: bool

        :param status_tip: Optional text to show in a popup when mouse pointer
            hovers over the action.
        :type status_tip: str

        :param parent: Parent widget for the new action. Defaults None.
        :type parent: QWidget

        :param whats_this: Optional text to show in the status bar when the
            mouse pointer hovers over the action.

        :returns: The action that was created. Note that the action is also
            added to self.actions list.
        :rtype: QAction
        """

        icon = QIcon(icon_path)
        action = QAction(icon, text, parent)
        action.triggered.connect(callback)
        action.setEnabled(enabled_flag)

        if status_tip is not None:
            action.setStatusTip(status_tip)

        if whats_this is not None:
            action.setWhatsThis(whats_this)

        if add_to_toolbar:
            self.toolbar.addAction(action)

        if add_to_menu:
            self.iface.addPluginToVectorMenu(
                self.menu,
                action)
        self.actions.append(action)
        return action

    def initGui(self):

        icon_path_copy = os.path.join(CURR_PATH, 'copy_points.png')
        icon_path_save = os.path.join(CURR_PATH, 'save_line.png')
        icon_path_method = os.path.join(CURR_PATH, 'save_mult_lines.png')

        self._geom_buffer = None

        self.copy_action = self.add_action(
            icon_path_copy,
            text=self.tr(u'Get points'),
            callback=self.copy_points,
            parent=self.iface.mainWindow())

        self.insert_one_action = self.add_action(
            icon_path_save,
            text=self.tr(u'Insert line'),
            callback=self.insert_one_line,
            parent=self.iface.mainWindow())

        self.insert_mult_action = self.add_action(
            icon_path_method,
            text=self.tr(u'Insert multiple lines'),
            callback=self.insert_mult_lines,
            parent=self.iface.mainWindow())

        # import pydevd
        # pydevd.settrace('localhost', port=9922, stdoutToServer=True, stderrToServer=True, suspend=False)

    def unload(self):
        """Removes the plugin menu item and icon from QGIS GUI."""
        for action in self.actions:
            self.iface.removePluginVectorMenu(
                self.tr(u'&Reconstruct Line'),
                action)
            self.iface.removeToolBarIcon(action)
        # remove the toolbar
        del self.toolbar

    def check_buttons_state(self, layer=None):
        layer = self.iface.activeLayer()

        if not isinstance(layer, QgsVectorLayer):
            self.copy_action.setDisabled(True)
            self.insert_one_action.setDisabled(True)
            self.insert_mult_action.setDisabled(True)
            return

        sel_feat_count = layer.selectedFeatureCount()
        geom_type = layer.geometryType()

        if sel_feat_count < 2 or geom_type != QgsWkbTypes.PointGeometry:
            self.copy_action.setDisabled(True)
        else:
            self.copy_action.setEnabled(True)

        if not layer.isEditable() or geom_type != QgsWkbTypes.LineGeometry or not self._geom_buffer:
            self.insert_one_action.setDisabled(True)
            self.insert_mult_action.setDisabled(True)
        else:
            self.insert_one_action.setEnabled(True)
            self.insert_mult_action.setEnabled(True)

    def copy_points(self):
        layer = self.iface.activeLayer()
        if not isinstance(layer, QgsVectorLayer) or layer.geometryType() != QgsWkbTypes.PointGeometry:
            self.iface.messageBar().pushMessage(self.tr("ReconstructLine"),
                                            self.tr("No points! Choose point layer and select points!"),
                                            level=Qgis.Warning,
                                            duration=5)

            return

        if layer.selectedFeatureCount() < 2:
            self.iface.messageBar().pushMessage(self.tr("ReconstructLine"),
                                            self.tr("No points! Select two or more points in the layer!"),
                                            level=Qgis.Warning,
                                            duration=5)
            return

        self._geom_buffer = [feature.geometry().vertexAt(0) for feature in layer.selectedFeatures()]

        self._srid = layer.crs()

        self.iface.messageBar().pushMessage(self.tr("ReconstructLine"),
                                            self.tr("Total points was copied: %d. Use 'Insert line' button on new or existing line layer to make a line.") % len(self._geom_buffer),
                                            level=Qgis.Info,
                                            duration=5)

    def insert_one_line(self):
        self.insert_line('SOM')

    def insert_mult_lines(self):
        self.insert_line('MST')

    def insert_line(self, method):
        layer = self.iface.activeLayer()
        if not isinstance(layer, QgsVectorLayer) or layer.geometryType() != QgsWkbTypes.LineGeometry:
            self.iface.messageBar().pushMessage(self.tr("ReconstructLine"),
                                    self.tr("Line can\'t be inserted! Select lines layer for inserting new geom!"),
                                    level=Qgis.Warning,
                                    duration=5)
            return

        if not layer.isEditable():
            self.iface.messageBar().pushMessage(self.tr("ReconstructLine"),
                                    self.tr("Line can\'t be inserted! Layer is not editable!"),
                                    level=Qgis.Warning,
                                    duration=5)
            return

        if not self._geom_buffer:
            self.iface.messageBar().pushMessage(self.tr("ReconstructLine"),
                        self.tr("Line can\'t be inserted! Copy points first!"),
                        level=Qgis.Warning,
                        duration=5)
            return

        #show message
        self.iface.messageBar().clearWidgets()
        self.iface.messageBar().pushMessage(self.tr("ReconstructLine"),
                                            self.tr("Processing points. Please wait..."),
                                            level=Qgis.Info
                                            )
        QgsApplication.setOverrideCursor(Qt.WaitCursor)
        QgsApplication.processEvents()
        QgsApplication.processEvents()
        QgsApplication.processEvents()

        try:
            # Create line

            # QGS geoms to np
            points = [(in_geom.x(), in_geom.y()) for in_geom in self._geom_buffer]
            data = np.array(points)

            # Make line

            if method == 'MST':
                conn  = MST(data)
                result = conn.connect()
            elif method == 'SOM':
                som = SOM1d(data)
                result = som.connect()
            else:
                raise ValueError

            #np to QGS
            lines = []
            for line in result:
                lines.append([QgsPointXY(out_geom[0], out_geom[1]) for out_geom in line])

            geom_list = []
            if layer.wkbType() == QgsWkbTypes.MultiLineString:
                geom_list.append(QgsGeometry.fromMultiPolylineXY(lines))
            else:
                for line in lines:
                    geom_list.append(QgsGeometry.fromPolylineXY(line))

            # Check crs and reproject
            target_crs = layer.crs()
            if target_crs.srsid() != self._srid.srsid():
                transf = QgsCoordinateTransform(self._srid, target_crs, QgsProject.instance())
                for geom in geom_list:
                    geom.transform(transf)

            # Insert feature(s)
            features = []
            for geom in geom_list:
                feat = QgsFeature()
                feat.setFields(layer.dataProvider().fields())
                feat.setGeometry(geom)
                features.append(feat)

            default_suppress = (method == 'MST')
            suppressForm = QSettings().value("/qgis/digitizing/disable_enter_attribute_values_dialog", type=bool, defaultValue=default_suppress)

            if suppressForm:
                # quite insert feature
                result = layer.addFeatures(features)
            else:
                # show dialog
                QgsApplication.restoreOverrideCursor()
                for feat in features:
                    attrDialog = QgsAttributeDialog(layer, feat, False)
                    attrDialog.setMode(True)
                    result = attrDialog.exec_()

            # show message
            self.iface.messageBar().clearWidgets()
            if result:
                self.iface.messageBar().pushMessage(self.tr("ReconstructLine"),
                                                self.tr("%s line segment(s) was sucesfull added" % (len(features))),
                                                level=Qgis.Info)
            else:
                self.iface.messageBar().pushMessage(self.tr("ReconstructLine"),
                                                self.tr("Line was not added"),
                                                level=Qgis.Critical)

            self.iface.mapCanvas().refresh()
        finally:
            QgsApplication.restoreOverrideCursor()
Gui0delp commented 2 years ago

Hi @CEZERT ,

First of all thanks for the work on the plugin to bring it at QGis 3 and more.

I test your version of the plugin and i didn't see the tool "insert_mult_lines". Because when i test it on QGis the tool "insert_mult_lines" create only one line for all points selected but the fisrt version of the plugin (QGis 2) if i select points and i use the tool "insert_mult_lines", it create a line between each points selected. Do you have some stuff for implement this feature ?

Have a nice day :)

Gui0delp commented 2 years ago

Hi @CEZERT,

I have suggestion about this part of code:

            geom_list = []
            if layer.wkbType() == QgsWkbTypes.MultiLineString:
                geom_list.append(QgsGeometry.fromMultiPolylineXY(lines))
            else:
                for line in lines:
                    geom_list.append(QgsGeometry.fromPolylineXY(line))

Replace by this one:

            geom_list = []
            if layer.wkbType() == QgsWkbTypes.MultiLineString:
                for line in lines:
                    geom_list.append(QgsGeometry.fromPolylineXY(line))

            else:
                geom_list.append(QgsGeometry.fromMultiPolylineXY(lines))

In that situation it work perfectly on QGis 3.16.9, need to be test with other version. Open to suggestion ;)

PS: I made a PR with the modifications https://github.com/nextgis/ReconstructLine/pull/14

eduard-kazakov commented 2 years ago

Plugin is now available for QGIS3 in standard repository. Thanks for your contribution.