Esempio n. 1
0
    def openDock(self):
        '''
        Opens the dock
        '''
        if self.dockWidget is None:
            self.logger.debug('Open dock')
            self.dockWidget = QgepDockWidget(self.iface.mainWindow(),
                                             self.iface.mapCanvas(),
                                             self.iface.addDockWidget)
            self.dockWidget.closed.connect(self.onDockClosed)
            self.dockWidget.showIt()

            self.plotWidget = QgepPlotSVGWidget(self.dockWidget,
                                                self.networkAnalyzer)
            self.plotWidget.specialStructureMouseOver.connect(
                self.highlightProfileElement)
            self.plotWidget.specialStructureMouseOut.connect(
                self.unhighlightProfileElement)
            self.plotWidget.reachMouseOver.connect(
                self.highlightProfileElement)
            self.plotWidget.reachMouseOut.connect(
                self.unhighlightProfileElement)
            self.dockWidget.addPlotWidget(self.plotWidget)
Esempio n. 2
0
    def openDock(self):
        """
        Opens the dock
        """
        if self.profileDock is None:
            self.logger.debug('Open dock')
            self.profileDock = QgepProfileDockWidget(self.iface.mainWindow(),
                                                     self.iface.mapCanvas(),
                                                     self.iface.addDockWidget)
            self.profileDock.closed.connect(self.onDockClosed)
            self.profileDock.showIt()

            self.plotWidget = QgepPlotSVGWidget(self.profileDock,
                                                self.network_analyzer)
            self.plotWidget.specialStructureMouseOver.connect(
                self.highlightProfileElement)
            self.plotWidget.specialStructureMouseOut.connect(
                self.unhighlightProfileElement)
            self.plotWidget.reachMouseOver.connect(
                self.highlightProfileElement)
            self.plotWidget.reachMouseOut.connect(
                self.unhighlightProfileElement)
            self.profileDock.addPlotWidget(self.plotWidget)
            self.profileDock.setTree(self.nodes, self.edges)
Esempio n. 3
0
    def openDock(self):
        """
        Opens the dock
        """
        if self.dockWidget is None:
            self.logger.debug("Open dock")
            self.dockWidget = QgepDockWidget(self.iface.mainWindow(), self.iface.mapCanvas(), self.iface.addDockWidget)
            self.dockWidget.closed.connect(self.onDockClosed)
            self.dockWidget.showIt()

            self.plotWidget = QgepPlotSVGWidget(self.dockWidget, self.networkAnalyzer)
            self.plotWidget.specialStructureMouseOver.connect(self.highlightProfileElement)
            self.plotWidget.specialStructureMouseOut.connect(self.unhighlightProfileElement)
            self.plotWidget.reachMouseOver.connect(self.highlightProfileElement)
            self.plotWidget.reachMouseOut.connect(self.unhighlightProfileElement)
            self.dockWidget.addPlotWidget(self.plotWidget)
Esempio n. 4
0
class QgepPlugin:
    '''
    A plugin for wastewater management
    http://www.github.com/qgep/QGEP
    '''
    # The networkAnalyzer will manage the networklayers and pathfinding
    networkAnalyzer = None

    # Remember not to reopen the dock if there's already one opened
    dockWidget = None

    # The layer ids the plugin will need
    edgeLayer = None
    nodeLayer = None
    specialStructureLayer = None

    profile = None

    def __init__(self, iface):
        self.iface = iface
        self.canvas = iface.mapCanvas()

        self.initLogger()
        setupI18n()

    def tr(self, sourceText):
        return QCoreApplication.translate('qgepplugin', sourceText)

    def initLogger(self):
        '''
        Initializes the logger
        '''
        self.logger = logging.getLogger(__package__)

        settings = QSettings()

        loglevel = settings.value("/QGEP/LogLevel", 'Warning')
        logfile = settings.value("/QGEP/LogFile", None)

        if hasattr(self.logger, 'qgepFileHandler'):
            self.logger.removeHandler(self.logger.qgepFileHandler)
            del self.logger.qgepFileHandler

        self.logger.addHandler(QgepQgsLogHandler())

        if logfile:
            hLog = logging.FileHandler(logfile)
            fmt = logging.Formatter(LOGFORMAT)
            hLog.setFormatter(fmt)
            self.logger.addHandler(hLog)
            self.logger.fileHandler = hLog

        if 'Debug' == loglevel:
            self.logger.setLevel(logging.DEBUG)
        elif 'Info' == loglevel:
            self.logger.setLevel(logging.INFO)
        elif 'Warning' == loglevel:
            self.logger.setLevel(logging.WARNING)
        elif 'Error' == loglevel:
            self.logger.setLevel(logging.ERROR)

        fp = os.path.join(os.path.abspath(os.path.dirname(__file__)),
                          "metadata.txt")

        iniText = QSettings(fp, QSettings.IniFormat)
        verno = iniText.value("version")

        self.logger.info('QGEP plugin version ' + verno + ' started')

    def initGui(self):
        '''
        Called to setup the plugin GUI
        '''
        self.toolbarButtons = []

        # Create toolbar button
        self.profileAction = QAction(
            QIcon(":/plugins/qgepplugin/icons/wastewater-profile.svg"),
            "Profile", self.iface.mainWindow())
        self.profileAction.setWhatsThis(self.tr("Reach trace"))
        self.profileAction.setEnabled(False)
        self.profileAction.setCheckable(True)
        self.profileAction.triggered.connect(self.profileToolClicked)

        self.downstreamAction = QAction(
            QIcon(":/plugins/qgepplugin/icons/wastewater-downstream.svg"),
            "Downstream", self.iface.mainWindow())
        self.downstreamAction.setWhatsThis(self.tr("Downstream reaches"))
        self.downstreamAction.setEnabled(False)
        self.downstreamAction.setCheckable(True)
        self.downstreamAction.triggered.connect(self.downstreamToolClicked)

        self.upstreamAction = QAction(
            QIcon(":/plugins/qgepplugin/icons/wastewater-upstream.svg"),
            "Upstream", self.iface.mainWindow())
        self.upstreamAction.setWhatsThis(self.tr("Upstream reaches"))
        self.upstreamAction.setEnabled(False)
        self.upstreamAction.setCheckable(True)
        self.upstreamAction.triggered.connect(self.upstreamToolClicked)

        self.aboutAction = QAction(self.tr('About'), self.iface.mainWindow())
        self.aboutAction.triggered.connect(self.about)

        self.settingsAction = QAction(self.tr('Settings'),
                                      self.iface.mainWindow())
        self.settingsAction.triggered.connect(self.showSettings)

        # Add toolbar button and menu item
        self.iface.addToolBarIcon(self.profileAction)
        self.iface.addToolBarIcon(self.upstreamAction)
        self.iface.addToolBarIcon(self.downstreamAction)

        self.iface.addPluginToMenu("&QGEP", self.profileAction)
        self.iface.addPluginToMenu("&QGEP", self.settingsAction)
        self.iface.addPluginToMenu("&QGEP", self.aboutAction)

        # Local array of buttons to enable / disable based on context
        self.toolbarButtons.append(self.profileAction)
        self.toolbarButtons.append(self.upstreamAction)
        self.toolbarButtons.append(self.downstreamAction)

        # Init the object maintaining the network
        self.networkAnalyzer = QgepGraphManager(self.iface)
        # Create the map tool for profile selection
        self.profileTool = QgepProfileMapTool(self.iface, self.profileAction,
                                              self.networkAnalyzer)
        self.profileTool.profileChanged.connect(self.onProfileChanged)

        self.upstreamTreeTool = QgepTreeMapTool(self.iface,
                                                self.upstreamAction,
                                                self.networkAnalyzer)
        self.upstreamTreeTool.setDirection("upstream")
        self.downstreamTreeTool = QgepTreeMapTool(self.iface,
                                                  self.downstreamAction,
                                                  self.networkAnalyzer)
        self.downstreamTreeTool.setDirection("downstream")

        # Connect to events that can change layers
        self.iface.projectRead.connect(self.onProjectRead)
        QgsMapLayerRegistry.instance().layersWillBeRemoved.connect(
            self.layersWillBeRemoved)
        QgsMapLayerRegistry.instance().layersAdded.connect(self.layersAdded)

    def unload(self):
        '''
        Called when unloading
        '''
        self.iface.removeToolBarIcon(self.profileAction)
        self.iface.removeToolBarIcon(self.upstreamAction)
        self.iface.removeToolBarIcon(self.downstreamAction)
        self.iface.removePluginMenu("&QGEP", self.profileAction)
        self.iface.removePluginMenu("&QGEP", self.aboutAction)

    def profileToolClicked(self):
        '''
        Is executed when the profile button is clicked
        '''
        self.openDock()
        # Set the profile map tool
        self.profileTool.setActive()

    def upstreamToolClicked(self):
        '''
        Is executed when the user clicks the upstream search tool
        '''
        self.upstreamTreeTool.setActive()

    def downstreamToolClicked(self):
        '''
        Is executed when the user clicks the downstream search tool
        '''
        self.downstreamTreeTool.setActive()

    def openDock(self):
        '''
        Opens the dock
        '''
        if self.dockWidget is None:
            self.logger.debug('Open dock')
            self.dockWidget = QgepDockWidget(self.iface.mainWindow(),
                                             self.iface.mapCanvas(),
                                             self.iface.addDockWidget)
            self.dockWidget.closed.connect(self.onDockClosed)
            self.dockWidget.showIt()

            self.plotWidget = QgepPlotSVGWidget(self.dockWidget,
                                                self.networkAnalyzer)
            self.plotWidget.specialStructureMouseOver.connect(
                self.highlightProfileElement)
            self.plotWidget.specialStructureMouseOut.connect(
                self.unhighlightProfileElement)
            self.plotWidget.reachMouseOver.connect(
                self.highlightProfileElement)
            self.plotWidget.reachMouseOut.connect(
                self.unhighlightProfileElement)
            self.dockWidget.addPlotWidget(self.plotWidget)

    @pyqtSlot()
    def onDockClosed(self):  #used when Dock dialog is closed
        '''
        Gets called when the dock is closed
        All the cleanup of the dock has to be done here
        '''
        self.dockWidget = None

    def layersWillBeRemoved(self, layerList):
        '''
        Gets called when a layer is removed
        
        @param layerList: The layers about to be removed
        '''
        for layerId in layerList:
            if 0 != self.networkAnalyzer.getNodeLayer():
                if self.networkAnalyzer.getNodeLayerId() == layerId:
                    self.networkAnalyzer.setNodeLayer(0)
                    self.layersChanged()

            if 0 != self.networkAnalyzer.getReachLayer():
                if self.networkAnalyzer.getReachLayerId() == layerId:
                    self.networkAnalyzer.setReachLayer(0)
                    self.layersChanged()

    def layersAdded(self, layers):
        '''
        Gets called when a layer is added
        @param layers: the layers to check
        '''
        for newLayer in layers:
            if newLayer.type() == QgsMapLayer.VectorLayer and newLayer.id(
            ) == self.nodeLayer:
                self.networkAnalyzer.setNodeLayer(newLayer)
                self.layersChanged()

            if newLayer.type() == QgsMapLayer.VectorLayer and newLayer.id(
            ) == self.edgeLayer:
                self.networkAnalyzer.setReachLayer(newLayer)
                self.layersChanged()

            if newLayer.type() == QgsMapLayer.VectorLayer and newLayer.id(
            ) == self.specialStructureLayer:
                self.networkAnalyzer.setSpecialStructureLayer(newLayer)
                self.layersChanged()

    def layersChanged(self):
        '''
        Gets called when the layers have changed
        '''
        buttonsEnabled = False

        if self.networkAnalyzer.getNodeLayer() \
        and self.networkAnalyzer.getReachLayer():
            buttonsEnabled = True

        for button in self.toolbarButtons:
            button.setEnabled(buttonsEnabled)

    @pyqtSlot()
    def onProjectRead(self):
        '''
        Gets called when a new project gets loaded. Updates the layers
        '''
        project = QgsProject.instance()

        specialStructureLayer = project.readEntry('QGEP',
                                                  'SpecialStructureLayer')
        graphEdgeLayer = project.readEntry('QGEP', 'GraphEdgeLayer')
        graphNodeLayer = project.readEntry('QGEP', 'GraphNodeLayer')

        if graphNodeLayer[1] is not False:
            self.nodeLayer = graphNodeLayer[0]
        else:
            self.nodeLayer = None

        if graphEdgeLayer[1] is not False:
            self.edgeLayer = graphEdgeLayer[0]
        else:
            self.edgeLayer = None

        if specialStructureLayer[1] is not False:
            self.specialStructureLayer = specialStructureLayer[0]
        else:
            self.specialStructureLayer = None

        if self.nodeLayer is not None  \
        and self.edgeLayer is not None \
        and self.specialStructureLayer is not None:
            reg = QgsMapLayerRegistry.instance()
            self.layersAdded([layer for layer in reg.mapLayers().itervalues()])
        else:
            if self.dockWidget is not None:
                self.dockWidget.close()

    def onProfileChanged(self, profile):
        '''
        The profile changed: update the plot
        @param profile: The profile to plot
        '''
        self.profile = profile.copy()

        if self.plotWidget:
            self.plotWidget.setProfile(profile)

    @pyqtSlot(unicode)
    def highlightProfileElement(self, objId):
        if self.profile is not None:
            self.profile.highlight(unicode(objId))

    @pyqtSlot()
    def unhighlightProfileElement(self):
        if self.profile is not None:
            self.profile.highlight(None)

    def about(self):
        from ui.dlgabout import DlgAbout
        DlgAbout(self.iface.mainWindow()).exec_()

    def showSettings(self):
        settingsDlg = QgepSettingsDialog(self.iface.mainWindow())
        settingsDlg.exec_()
Esempio n. 5
0
class QgepPlugin:
    """
    A plugin for wastewater management
    http://www.github.com/qgep/QGEP
    """

    # The networkAnalyzer will manage the networklayers and pathfinding
    networkAnalyzer = None

    # Remember not to reopen the dock if there's already one opened
    dockWidget = None

    # The layer ids the plugin will need
    edgeLayer = None
    nodeLayer = None
    specialStructureLayer = None

    profile = None

    def __init__(self, iface):
        self.iface = iface
        self.canvas = iface.mapCanvas()

        self.initLogger()
        setupI18n()

    def tr(self, sourceText):
        return QCoreApplication.translate("qgepplugin", sourceText)

    def initLogger(self):
        """
        Initializes the logger
        """
        self.logger = logging.getLogger(__package__)

        settings = QSettings()

        loglevel = settings.value("/QGEP/LogLevel", "Warning")
        logfile = settings.value("/QGEP/LogFile", None)

        if hasattr(self.logger, "qgepFileHandler"):
            self.logger.removeHandler(self.logger.qgepFileHandler)
            del self.logger.qgepFileHandler

        self.logger.addHandler(QgepQgsLogHandler())

        if logfile:
            hLog = logging.FileHandler(logfile)
            fmt = logging.Formatter(LOGFORMAT)
            hLog.setFormatter(fmt)
            self.logger.addHandler(hLog)
            self.logger.fileHandler = hLog

        if "Debug" == loglevel:
            self.logger.setLevel(logging.DEBUG)
        elif "Info" == loglevel:
            self.logger.setLevel(logging.INFO)
        elif "Warning" == loglevel:
            self.logger.setLevel(logging.WARNING)
        elif "Error" == loglevel:
            self.logger.setLevel(logging.ERROR)

        fp = os.path.join(os.path.abspath(os.path.dirname(__file__)), "metadata.txt")

        iniText = QSettings(fp, QSettings.IniFormat)
        verno = iniText.value("version")

        self.logger.info("QGEP plugin version " + verno + " started")

    def initGui(self):
        """
        Called to setup the plugin GUI
        """
        self.toolbarButtons = []

        # Create toolbar button
        self.profileAction = QAction(
            QIcon(":/plugins/qgepplugin/icons/wastewater-profile.svg"), "Profile", self.iface.mainWindow()
        )
        self.profileAction.setWhatsThis(self.tr("Reach trace"))
        self.profileAction.setEnabled(False)
        self.profileAction.setCheckable(True)
        self.profileAction.triggered.connect(self.profileToolClicked)

        self.downstreamAction = QAction(
            QIcon(":/plugins/qgepplugin/icons/wastewater-downstream.svg"), "Downstream", self.iface.mainWindow()
        )
        self.downstreamAction.setWhatsThis(self.tr("Downstream reaches"))
        self.downstreamAction.setEnabled(False)
        self.downstreamAction.setCheckable(True)
        self.downstreamAction.triggered.connect(self.downstreamToolClicked)

        self.upstreamAction = QAction(
            QIcon(":/plugins/qgepplugin/icons/wastewater-upstream.svg"), "Upstream", self.iface.mainWindow()
        )
        self.upstreamAction.setWhatsThis(self.tr("Upstream reaches"))
        self.upstreamAction.setEnabled(False)
        self.upstreamAction.setCheckable(True)
        self.upstreamAction.triggered.connect(self.upstreamToolClicked)

        self.aboutAction = QAction(self.tr("About"), self.iface.mainWindow())
        self.aboutAction.triggered.connect(self.about)

        self.settingsAction = QAction(self.tr("Settings"), self.iface.mainWindow())
        self.settingsAction.triggered.connect(self.showSettings)

        # Add toolbar button and menu item
        self.iface.addToolBarIcon(self.profileAction)
        self.iface.addToolBarIcon(self.upstreamAction)
        self.iface.addToolBarIcon(self.downstreamAction)

        self.iface.addPluginToMenu("&QGEP", self.profileAction)
        self.iface.addPluginToMenu("&QGEP", self.settingsAction)
        self.iface.addPluginToMenu("&QGEP", self.aboutAction)

        # Local array of buttons to enable / disable based on context
        self.toolbarButtons.append(self.profileAction)
        self.toolbarButtons.append(self.upstreamAction)
        self.toolbarButtons.append(self.downstreamAction)

        # Init the object maintaining the network
        self.networkAnalyzer = QgepGraphManager(self.iface)
        # Create the map tool for profile selection
        self.profileTool = QgepProfileMapTool(self.iface, self.profileAction, self.networkAnalyzer)
        self.profileTool.profileChanged.connect(self.onProfileChanged)

        self.upstreamTreeTool = QgepTreeMapTool(self.iface, self.upstreamAction, self.networkAnalyzer)
        self.upstreamTreeTool.setDirection("upstream")
        self.downstreamTreeTool = QgepTreeMapTool(self.iface, self.downstreamAction, self.networkAnalyzer)
        self.downstreamTreeTool.setDirection("downstream")

        # Connect to events that can change layers
        self.iface.projectRead.connect(self.onProjectRead)
        QgsMapLayerRegistry.instance().layersWillBeRemoved.connect(self.layersWillBeRemoved)
        QgsMapLayerRegistry.instance().layersAdded.connect(self.layersAdded)

    def unload(self):
        """
        Called when unloading
        """
        self.iface.removeToolBarIcon(self.profileAction)
        self.iface.removeToolBarIcon(self.upstreamAction)
        self.iface.removeToolBarIcon(self.downstreamAction)
        self.iface.removePluginMenu("&QGEP", self.profileAction)
        self.iface.removePluginMenu("&QGEP", self.aboutAction)

    def profileToolClicked(self):
        """
        Is executed when the profile button is clicked
        """
        self.openDock()
        # Set the profile map tool
        self.profileTool.setActive()

    def upstreamToolClicked(self):
        """
        Is executed when the user clicks the upstream search tool
        """
        self.upstreamTreeTool.setActive()

    def downstreamToolClicked(self):
        """
        Is executed when the user clicks the downstream search tool
        """
        self.downstreamTreeTool.setActive()

    def openDock(self):
        """
        Opens the dock
        """
        if self.dockWidget is None:
            self.logger.debug("Open dock")
            self.dockWidget = QgepDockWidget(self.iface.mainWindow(), self.iface.mapCanvas(), self.iface.addDockWidget)
            self.dockWidget.closed.connect(self.onDockClosed)
            self.dockWidget.showIt()

            self.plotWidget = QgepPlotSVGWidget(self.dockWidget, self.networkAnalyzer)
            self.plotWidget.specialStructureMouseOver.connect(self.highlightProfileElement)
            self.plotWidget.specialStructureMouseOut.connect(self.unhighlightProfileElement)
            self.plotWidget.reachMouseOver.connect(self.highlightProfileElement)
            self.plotWidget.reachMouseOut.connect(self.unhighlightProfileElement)
            self.dockWidget.addPlotWidget(self.plotWidget)

    @pyqtSlot()
    def onDockClosed(self):  # used when Dock dialog is closed
        """
        Gets called when the dock is closed
        All the cleanup of the dock has to be done here
        """
        self.dockWidget = None

    def layersWillBeRemoved(self, layerList):
        """
        Gets called when a layer is removed
        
        @param layerList: The layers about to be removed
        """
        for layerId in layerList:
            if 0 != self.networkAnalyzer.getNodeLayer():
                if self.networkAnalyzer.getNodeLayerId() == layerId:
                    self.networkAnalyzer.setNodeLayer(0)
                    self.layersChanged()

            if 0 != self.networkAnalyzer.getReachLayer():
                if self.networkAnalyzer.getReachLayerId() == layerId:
                    self.networkAnalyzer.setReachLayer(0)
                    self.layersChanged()

    def layersAdded(self, layers):
        """
        Gets called when a layer is added
        @param layers: the layers to check
        """
        for newLayer in layers:
            if newLayer.type() == QgsMapLayer.VectorLayer and newLayer.id() == self.nodeLayer:
                self.networkAnalyzer.setNodeLayer(newLayer)
                self.layersChanged()

            if newLayer.type() == QgsMapLayer.VectorLayer and newLayer.id() == self.edgeLayer:
                self.networkAnalyzer.setReachLayer(newLayer)
                self.layersChanged()

            if newLayer.type() == QgsMapLayer.VectorLayer and newLayer.id() == self.specialStructureLayer:
                self.networkAnalyzer.setSpecialStructureLayer(newLayer)
                self.layersChanged()

    def layersChanged(self):
        """
        Gets called when the layers have changed
        """
        buttonsEnabled = False

        if self.networkAnalyzer.getNodeLayer() and self.networkAnalyzer.getReachLayer():
            buttonsEnabled = True

        for button in self.toolbarButtons:
            button.setEnabled(buttonsEnabled)

    @pyqtSlot()
    def onProjectRead(self):
        """
        Gets called when a new project gets loaded. Updates the layers
        """
        project = QgsProject.instance()

        specialStructureLayer = project.readEntry("QGEP", "SpecialStructureLayer")
        graphEdgeLayer = project.readEntry("QGEP", "GraphEdgeLayer")
        graphNodeLayer = project.readEntry("QGEP", "GraphNodeLayer")

        if graphNodeLayer[1] is not False:
            self.nodeLayer = graphNodeLayer[0]
        else:
            self.nodeLayer = None

        if graphEdgeLayer[1] is not False:
            self.edgeLayer = graphEdgeLayer[0]
        else:
            self.edgeLayer = None

        if specialStructureLayer[1] is not False:
            self.specialStructureLayer = specialStructureLayer[0]
        else:
            self.specialStructureLayer = None

        if self.nodeLayer is not None and self.edgeLayer is not None and self.specialStructureLayer is not None:
            reg = QgsMapLayerRegistry.instance()
            self.layersAdded([layer for layer in reg.mapLayers().itervalues()])
        else:
            if self.dockWidget is not None:
                self.dockWidget.close()

    def onProfileChanged(self, profile):
        """
        The profile changed: update the plot
        @param profile: The profile to plot
        """
        self.profile = profile.copy()

        if self.plotWidget:
            self.plotWidget.setProfile(profile)

    @pyqtSlot(unicode)
    def highlightProfileElement(self, objId):
        if self.profile is not None:
            self.profile.highlight(unicode(objId))

    @pyqtSlot()
    def unhighlightProfileElement(self):
        if self.profile is not None:
            self.profile.highlight(None)

    def about(self):
        from ui.dlgabout import DlgAbout

        DlgAbout(self.iface.mainWindow()).exec_()

    def showSettings(self):
        settingsDlg = QgepSettingsDialog(self.iface.mainWindow())
        settingsDlg.exec_()
Esempio n. 6
0
class QgepPlugin:
    """
    A plugin for wastewater management
    http://www.github.com/qgep/QGEP
    """
    # The networkAnalyzer will manage the networklayers and pathfinding
    network_analyzer = None

    # Remember not to reopen the dock if there's already one opened
    profileDock = None

    # Wizard
    wizarddock = None

    # The layer ids the plugin will need
    edgeLayer = None
    nodeLayer = None
    specialStructureLayer = None
    networkElementLayer = None

    profile = None

    def __init__(self, iface):
        self.iface = iface
        self.canvas = iface.mapCanvas()
        self.nodes = None
        self.edges = None

        self.initLogger()
        setup_i18n()

    def tr(self, source_text):
        """
        This does not inherit from QObject but for the translation to work (in particular to have translatable strings
        picked up) we need a tr method.
        :rtype : unicode
        :param source_text: The text to translate
        :return: The translated text
        """
        return QApplication.translate('QgepPlugin', source_text)

    def initLogger(self):
        """
        Initializes the logger
        """
        self.logger = logging.getLogger(__package__)

        settings = QSettings()

        loglevel = settings.value("/QGEP/LogLevel", 'Warning')
        logfile = settings.value("/QGEP/LogFile", None)

        if hasattr(self.logger, 'qgepFileHandler'):
            self.logger.removeHandler(self.logger.qgepFileHandler)
            del self.logger.qgepFileHandler

        self.logger.addHandler(QgepQgsLogHandler())

        if logfile:
            log_handler = logging.FileHandler(logfile)
            fmt = logging.Formatter(LOGFORMAT)
            log_handler.setFormatter(fmt)
            self.logger.addHandler(log_handler)
            self.logger.fileHandler = log_handler

        if 'Debug' == loglevel:
            self.logger.setLevel(logging.DEBUG)
        elif 'Info' == loglevel:
            self.logger.setLevel(logging.INFO)
        elif 'Warning' == loglevel:
            self.logger.setLevel(logging.WARNING)
        elif 'Error' == loglevel:
            self.logger.setLevel(logging.ERROR)

        fp = os.path.join(os.path.abspath(os.path.dirname(__file__)),
                          "metadata.txt")

        ini_text = QSettings(fp, QSettings.IniFormat)
        verno = ini_text.value("version")

        self.logger.info('QGEP plugin version ' + verno + ' started')

    def initGui(self):
        """
        Called to setup the plugin GUI
        """
        self.network_layer_notifier = QgepLayerNotifier(
            self.iface.mainWindow(), ['vw_network_node', 'vw_network_segment'])
        self.wastewater_networkelement_layer_notifier = QgepLayerNotifier(
            self.iface.mainWindow(), ['vw_wastewater_node', 'vw_qgep_reach'])
        self.toolbarButtons = []

        # Create toolbar button
        self.profileAction = QAction(
            QIcon(":/plugins/qgepplugin/icons/wastewater-profile.svg"),
            self.tr("Profile"), self.iface.mainWindow())
        self.profileAction.setWhatsThis(self.tr("Reach trace"))
        self.profileAction.setEnabled(False)
        self.profileAction.setCheckable(True)
        self.profileAction.triggered.connect(self.profileToolClicked)

        self.downstreamAction = QAction(
            QIcon(":/plugins/qgepplugin/icons/wastewater-downstream.svg"),
            self.tr("Downstream"), self.iface.mainWindow())
        self.downstreamAction.setWhatsThis(self.tr("Downstream reaches"))
        self.downstreamAction.setEnabled(False)
        self.downstreamAction.setCheckable(True)
        self.downstreamAction.triggered.connect(self.downstreamToolClicked)

        self.upstreamAction = QAction(
            QIcon(":/plugins/qgepplugin/icons/wastewater-upstream.svg"),
            self.tr("Upstream"), self.iface.mainWindow())
        self.upstreamAction.setWhatsThis(self.tr("Upstream reaches"))
        self.upstreamAction.setEnabled(False)
        self.upstreamAction.setCheckable(True)
        self.upstreamAction.triggered.connect(self.upstreamToolClicked)

        self.wizardAction = QAction(
            QIcon(":/plugins/qgepplugin/icons/wizard.svg"), "Wizard",
            self.iface.mainWindow())
        self.wizardAction.setWhatsThis(
            self.tr("Create new manholes and reaches"))
        self.wizardAction.setEnabled(False)
        self.wizardAction.setCheckable(True)
        self.wizardAction.triggered.connect(self.wizard)

        self.connectNetworkElementsAction = QAction(
            QIcon(
                ":/plugins/qgepplugin/icons/link-wastewater-networkelement.svg"
            ),
            QApplication.translate('qgepplugin',
                                   'Connect wastewater networkelements'),
            self.iface.mainWindow())
        self.connectNetworkElementsAction.setEnabled(False)
        self.connectNetworkElementsAction.setCheckable(True)
        self.connectNetworkElementsAction.triggered.connect(
            self.connectNetworkElements)

        self.refreshNetworkTopologyAction = QAction(
            QIcon(":/plugins/qgepplugin/icons/refresh-network.svg"),
            "Refresh network topology", self.iface.mainWindow())
        self.refreshNetworkTopologyAction.setWhatsThis(
            self.tr("Refresh network topology"))
        self.refreshNetworkTopologyAction.setEnabled(False)
        self.refreshNetworkTopologyAction.setCheckable(False)
        self.refreshNetworkTopologyAction.triggered.connect(
            self.refreshNetworkTopologyActionClicked)

        self.aboutAction = QAction(self.tr('About'), self.iface.mainWindow())
        self.aboutAction.triggered.connect(self.about)

        self.settingsAction = QAction(self.tr('Settings'),
                                      self.iface.mainWindow())
        self.settingsAction.triggered.connect(self.showSettings)

        # Add toolbar button and menu item
        self.toolbar = QToolBar(QApplication.translate('qgepplugin', 'QGEP'))
        self.toolbar.addAction(self.profileAction)
        self.toolbar.addAction(self.upstreamAction)
        self.toolbar.addAction(self.downstreamAction)
        self.toolbar.addAction(self.wizardAction)
        self.toolbar.addAction(self.refreshNetworkTopologyAction)
        self.toolbar.addAction(self.connectNetworkElementsAction)

        self.iface.addPluginToMenu("&QGEP", self.profileAction)
        self.iface.addPluginToMenu("&QGEP", self.settingsAction)
        self.iface.addPluginToMenu("&QGEP", self.aboutAction)

        self.iface.addToolBar(self.toolbar)

        # Local array of buttons to enable / disable based on context
        self.toolbarButtons.append(self.profileAction)
        self.toolbarButtons.append(self.upstreamAction)
        self.toolbarButtons.append(self.downstreamAction)
        self.toolbarButtons.append(self.wizardAction)
        self.toolbarButtons.append(self.refreshNetworkTopologyAction)

        self.network_layer_notifier.layersAvailable.connect(
            self.onLayersAvailable)
        self.network_layer_notifier.layersUnavailable.connect(
            self.onLayersUnavailable)

        # Init the object maintaining the network
        self.network_analyzer = QgepGraphManager(self.iface)
        # Create the map tool for profile selection
        self.profile_tool = QgepProfileMapTool(self.iface, self.profileAction,
                                               self.network_analyzer)
        self.profile_tool.profileChanged.connect(self.onProfileChanged)

        self.upstream_tree_tool = QgepTreeMapTool(self.iface,
                                                  self.upstreamAction,
                                                  self.network_analyzer)
        self.upstream_tree_tool.setDirection("upstream")
        self.upstream_tree_tool.treeChanged.connect(self.onTreeChanged)
        self.downstream_tree_tool = QgepTreeMapTool(self.iface,
                                                    self.downstreamAction,
                                                    self.network_analyzer)
        self.downstream_tree_tool.setDirection("downstream")
        self.downstream_tree_tool.treeChanged.connect(self.onTreeChanged)

        self.maptool_connect_networkelements = QgepMapToolConnectNetworkElements(
            self.iface, self.connectNetworkElementsAction)

        self.wastewater_networkelement_layer_notifier.layersAvailableChanged.connect(
            self.connectNetworkElementsAction.setEnabled)

        self.processing_provider = QgepProcessingProvider()
        Processing.addProvider(self.processing_provider)

    def unload(self):
        """
        Called when unloading
        """
        self.toolbar.removeAction(self.profileAction)
        self.toolbar.removeAction(self.upstreamAction)
        self.toolbar.removeAction(self.downstreamAction)
        self.toolbar.removeAction(self.wizardAction)
        self.toolbar.removeAction(self.refreshNetworkTopologyAction)
        self.toolbar.removeAction(self.connectNetworkElementsAction)

        self.toolbar.deleteLater()

        self.iface.removePluginMenu("&QGEP", self.profileAction)
        self.iface.removePluginMenu("&QGEP", self.aboutAction)

    def onLayersAvailable(self, layers):
        for b in self.toolbarButtons:
            b.setEnabled(True)

        self.network_analyzer.setReachLayer(layers['vw_network_segment'])
        self.network_analyzer.setNodeLayer(layers['vw_network_node'])

    def onLayersUnavailable(self):
        for b in self.toolbarButtons:
            b.setEnabled(False)

    def profileToolClicked(self):
        """
        Is executed when the profile button is clicked
        """
        self.openDock()
        # Set the profile map tool
        self.profile_tool.setActive()

    def upstreamToolClicked(self):
        """
        Is executed when the user clicks the upstream search tool
        """
        self.openDock()
        self.upstream_tree_tool.setActive()

    def downstreamToolClicked(self):
        """
        Is executed when the user clicks the downstream search tool
        """
        self.openDock()
        self.downstream_tree_tool.setActive()

    def refreshNetworkTopologyActionClicked(self):
        """
        Is executed when the user clicks the refreshNetworkTopologyAction tool
        """
        self.network_analyzer.refresh()

    def wizard(self):
        """
        """
        if not self.wizarddock:
            self.wizarddock = QgepWizard(self.iface.mainWindow(), self.iface)
        self.logger.debug('Opening Wizard')
        self.iface.addDockWidget(Qt.LeftDockWidgetArea, self.wizarddock)
        self.wizarddock.show()

    @pyqtSlot()
    def connectNetworkElements(self):
        print 'Copnnet them'
        self.iface.mapCanvas().setMapTool(self.maptool_connect_networkelements)

    def openDock(self):
        """
        Opens the dock
        """
        if self.profileDock is None:
            self.logger.debug('Open dock')
            self.profileDock = QgepProfileDockWidget(self.iface.mainWindow(),
                                                     self.iface.mapCanvas(),
                                                     self.iface.addDockWidget)
            self.profileDock.closed.connect(self.onDockClosed)
            self.profileDock.showIt()

            self.plotWidget = QgepPlotSVGWidget(self.profileDock,
                                                self.network_analyzer)
            self.plotWidget.specialStructureMouseOver.connect(
                self.highlightProfileElement)
            self.plotWidget.specialStructureMouseOut.connect(
                self.unhighlightProfileElement)
            self.plotWidget.reachMouseOver.connect(
                self.highlightProfileElement)
            self.plotWidget.reachMouseOut.connect(
                self.unhighlightProfileElement)
            self.profileDock.addPlotWidget(self.plotWidget)
            self.profileDock.setTree(self.nodes, self.edges)

    @pyqtSlot()
    def onDockClosed(self):  # used when Dock dialog is closed
        """
        Gets called when the dock is closed
        All the cleanup of the dock has to be done here
        """
        self.profileDock = None

    def onProfileChanged(self, profile):
        """
        The profile changed: update the plot
        @param profile: The profile to plot
        """
        self.profile = profile.copy()

        if self.plotWidget:
            self.plotWidget.setProfile(profile)

    def onTreeChanged(self, nodes, edges):
        if self.profileDock:
            self.profileDock.setTree(nodes, edges)
        self.nodes = nodes
        self.edges = edges

    @pyqtSlot(unicode)
    def highlightProfileElement(self, obj_id):
        if self.profile is not None:
            self.profile.highlight(unicode(obj_id))

    @pyqtSlot()
    def unhighlightProfileElement(self):
        if self.profile is not None:
            self.profile.highlight(None)

    def about(self):
        from ui.dlgabout import DlgAbout

        DlgAbout(self.iface.mainWindow()).exec_()

    def showSettings(self):
        settings_dlg = QgepSettingsDialog(self.iface.mainWindow())
        settings_dlg.exec_()
Esempio n. 7
0
class QgepPlugin:
    """
    A plugin for wastewater management
    http://www.github.com/qgep/QGEP
    """
    # The networkAnalyzer will manage the networklayers and pathfinding
    network_analyzer = None

    # Remember not to reopen the dock if there's already one opened
    profileDock = None

    # Wizard
    wizarddock = None

    # The layer ids the plugin will need
    edgeLayer = None
    nodeLayer = None
    specialStructureLayer = None
    networkElementLayer = None

    profile = None

    def __init__(self, iface):
        self.iface = iface
        self.canvas = iface.mapCanvas()

        self.initLogger()
        setup_i18n()

    def tr(self, source_text):
        """
        This does not inherit from QObject but for the translation to work (in particular to have translatable strings
        picked up) we need a tr method.
        :rtype : unicode
        :param source_text: The text to translate
        :return: The translated text
        """
        return QApplication.translate('QgepPlugin', source_text)

    def initLogger(self):
        """
        Initializes the logger
        """
        self.logger = logging.getLogger(__package__)

        settings = QSettings()

        loglevel = settings.value("/QGEP/LogLevel", 'Warning')
        logfile = settings.value("/QGEP/LogFile", None)

        if hasattr(self.logger, 'qgepFileHandler'):
            self.logger.removeHandler(self.logger.qgepFileHandler)
            del self.logger.qgepFileHandler

        self.logger.addHandler(QgepQgsLogHandler())

        if logfile:
            log_handler = logging.FileHandler(logfile)
            fmt = logging.Formatter(LOGFORMAT)
            log_handler.setFormatter(fmt)
            self.logger.addHandler(log_handler)
            self.logger.fileHandler = log_handler

        if 'Debug' == loglevel:
            self.logger.setLevel(logging.DEBUG)
        elif 'Info' == loglevel:
            self.logger.setLevel(logging.INFO)
        elif 'Warning' == loglevel:
            self.logger.setLevel(logging.WARNING)
        elif 'Error' == loglevel:
            self.logger.setLevel(logging.ERROR)

        fp = os.path.join(os.path.abspath(os.path.dirname(__file__)), "metadata.txt")

        ini_text = QSettings(fp, QSettings.IniFormat)
        verno = ini_text.value("version")

        self.logger.info('QGEP plugin version ' + verno + ' started')

    def initGui(self):
        """
        Called to setup the plugin GUI
        """
        self.network_layer_notifier = QgepLayerNotifier(self.iface.mainWindow(),
                                                        ['vw_network_node', 'vw_network_segment'])
        self.wastewater_networkelement_layer_notifier = QgepLayerNotifier(self.iface.mainWindow(),
                                                                          ['vw_wastewater_node', 'vw_qgep_reach'])
        self.toolbarButtons = []

        # Create toolbar button
        self.profileAction = QAction(QIcon(":/plugins/qgepplugin/icons/wastewater-profile.svg"), self.tr("Profile"),
                                     self.iface.mainWindow())
        self.profileAction.setWhatsThis(self.tr("Reach trace"))
        self.profileAction.setEnabled(False)
        self.profileAction.setCheckable(True)
        self.profileAction.triggered.connect(self.profileToolClicked)

        self.downstreamAction = QAction(QIcon(":/plugins/qgepplugin/icons/wastewater-downstream.svg"),
                                        self.tr("Downstream"), self.iface.mainWindow())
        self.downstreamAction.setWhatsThis(self.tr("Downstream reaches"))
        self.downstreamAction.setEnabled(False)
        self.downstreamAction.setCheckable(True)
        self.downstreamAction.triggered.connect(self.downstreamToolClicked)

        self.upstreamAction = QAction(QIcon(":/plugins/qgepplugin/icons/wastewater-upstream.svg"), self.tr("Upstream"),
                                      self.iface.mainWindow())
        self.upstreamAction.setWhatsThis(self.tr("Upstream reaches"))
        self.upstreamAction.setEnabled(False)
        self.upstreamAction.setCheckable(True)
        self.upstreamAction.triggered.connect(self.upstreamToolClicked)

        self.wizardAction = QAction(QIcon(":/plugins/qgepplugin/icons/wizard.svg"), "Wizard", self.iface.mainWindow())
        self.wizardAction.setWhatsThis(self.tr("Create new manholes and reaches"))
        self.wizardAction.setEnabled(False)
        self.wizardAction.setCheckable(True)
        self.wizardAction.triggered.connect(self.wizard)

        self.connectNetworkElementsAction = QAction(
            QIcon(":/plugins/qgepplugin/icons/link-wastewater-networkelement.svg"),
            QApplication.translate('qgepplugin', 'Connect wastewater networkelements'), self.iface.mainWindow())
        self.connectNetworkElementsAction.setEnabled(False)
        self.connectNetworkElementsAction.setCheckable(True)
        self.connectNetworkElementsAction.triggered.connect(self.connectNetworkElements)

        self.refreshNetworkTopologyAction = QAction(QIcon(":/plugins/qgepplugin/icons/refresh-network.svg"),
                                                    "Refresh network topology", self.iface.mainWindow())
        self.refreshNetworkTopologyAction.setWhatsThis(self.tr("Refresh network topology"))
        self.refreshNetworkTopologyAction.setEnabled(False)
        self.refreshNetworkTopologyAction.setCheckable(False)
        self.refreshNetworkTopologyAction.triggered.connect(self.refreshNetworkTopologyActionClicked)

        self.aboutAction = QAction(self.tr('About'), self.iface.mainWindow())
        self.aboutAction.triggered.connect(self.about)

        self.settingsAction = QAction(self.tr('Settings'), self.iface.mainWindow())
        self.settingsAction.triggered.connect(self.showSettings)

        # Add toolbar button and menu item
        self.iface.addToolBarIcon(self.profileAction)
        self.iface.addToolBarIcon(self.upstreamAction)
        self.iface.addToolBarIcon(self.downstreamAction)
        self.iface.addToolBarIcon(self.wizardAction)
        self.iface.addToolBarIcon(self.refreshNetworkTopologyAction)
        self.iface.addToolBarIcon(self.connectNetworkElementsAction)

        self.iface.addPluginToMenu("&QGEP", self.profileAction)
        self.iface.addPluginToMenu("&QGEP", self.settingsAction)
        self.iface.addPluginToMenu("&QGEP", self.aboutAction)

        # Local array of buttons to enable / disable based on context
        self.toolbarButtons.append(self.profileAction)
        self.toolbarButtons.append(self.upstreamAction)
        self.toolbarButtons.append(self.downstreamAction)
        self.toolbarButtons.append(self.wizardAction)
        self.toolbarButtons.append(self.refreshNetworkTopologyAction)

        self.network_layer_notifier.layersAvailable.connect(self.onLayersAvailable)
        self.network_layer_notifier.layersUnavailable.connect(self.onLayersUnavailable)

        # Init the object maintaining the network
        self.network_analyzer = QgepGraphManager(self.iface)
        # Create the map tool for profile selection
        self.profile_tool = QgepProfileMapTool(self.iface, self.profileAction, self.network_analyzer)
        self.profile_tool.profileChanged.connect(self.onProfileChanged)

        self.upstream_tree_tool = QgepTreeMapTool(self.iface, self.upstreamAction, self.network_analyzer)
        self.upstream_tree_tool.setDirection("upstream")
        self.downstream_tree_tool = QgepTreeMapTool(self.iface, self.downstreamAction, self.network_analyzer)
        self.downstream_tree_tool.setDirection("downstream")

        self.maptool_connect_networkelements = QgepMapToolConnectNetworkElements(
            self.iface, self.connectNetworkElementsAction)

        self.wastewater_networkelement_layer_notifier.layersAvailableChanged.connect(
            self.connectNetworkElementsAction.setEnabled)

    def unload(self):
        """
        Called when unloading
        """
        self.iface.removeToolBarIcon(self.profileAction)
        self.iface.removeToolBarIcon(self.upstreamAction)
        self.iface.removeToolBarIcon(self.downstreamAction)
        self.iface.removeToolBarIcon(self.wizardAction)
        self.iface.removeToolBarIcon(self.refreshNetworkTopologyAction)
        self.iface.removeToolBarIcon(self.connectNetworkElementsAction)

        self.iface.removePluginMenu("&QGEP", self.profileAction)
        self.iface.removePluginMenu("&QGEP", self.aboutAction)

    def onLayersAvailable(self, layers):
        for b in self.toolbarButtons:
            b.setEnabled(True)

        self.network_analyzer.setReachLayer(layers['vw_network_segment'])
        self.network_analyzer.setNodeLayer(layers['vw_network_node'])

    def onLayersUnavailable(self):
        for b in self.toolbarButtons:
            b.setEnabled(False)

    def profileToolClicked(self):
        """
        Is executed when the profile button is clicked
        """
        self.openDock()
        # Set the profile map tool
        self.profile_tool.setActive()

    def upstreamToolClicked(self):
        """
        Is executed when the user clicks the upstream search tool
        """
        self.upstream_tree_tool.setActive()

    def downstreamToolClicked(self):
        """
        Is executed when the user clicks the downstream search tool
        """
        self.downstream_tree_tool.setActive()

    def refreshNetworkTopologyActionClicked(self):
        """
        Is executed when the user clicks the refreshNetworkTopologyAction tool
        """
        self.network_analyzer.refresh()

    def wizard(self):
        """
        """
        if not self.wizarddock:
            self.wizarddock = QgepWizard(self.iface.mainWindow(), self.iface)
        self.logger.debug('Opening Wizard')
        self.iface.addDockWidget(Qt.LeftDockWidgetArea, self.wizarddock)
        self.wizarddock.show()

    @pyqtSlot()
    def connectNetworkElements(self):
        print 'Copnnet them'
        self.iface.mapCanvas().setMapTool(self.maptool_connect_networkelements)

    def openDock(self):
        """
        Opens the dock
        """
        if self.profileDock is None:
            self.logger.debug('Open dock')
            self.profileDock = QgepProfileDockWidget(self.iface.mainWindow(), self.iface.mapCanvas(),
                                                     self.iface.addDockWidget)
            self.profileDock.closed.connect(self.onDockClosed)
            self.profileDock.showIt()

            self.plotWidget = QgepPlotSVGWidget(self.profileDock, self.network_analyzer)
            self.plotWidget.specialStructureMouseOver.connect(self.highlightProfileElement)
            self.plotWidget.specialStructureMouseOut.connect(self.unhighlightProfileElement)
            self.plotWidget.reachMouseOver.connect(self.highlightProfileElement)
            self.plotWidget.reachMouseOut.connect(self.unhighlightProfileElement)
            self.profileDock.addPlotWidget(self.plotWidget)

    @pyqtSlot()
    def onDockClosed(self):  # used when Dock dialog is closed
        """
        Gets called when the dock is closed
        All the cleanup of the dock has to be done here
        """
        self.profileDock = None

    def onProfileChanged(self, profile):
        """
        The profile changed: update the plot
        @param profile: The profile to plot
        """
        self.profile = profile.copy()

        if self.plotWidget:
            self.plotWidget.setProfile(profile)

    @pyqtSlot(unicode)
    def highlightProfileElement(self, obj_id):
        if self.profile is not None:
            self.profile.highlight(unicode(obj_id))

    @pyqtSlot()
    def unhighlightProfileElement(self):
        if self.profile is not None:
            self.profile.highlight(None)

    def about(self):
        from ui.dlgabout import DlgAbout

        DlgAbout(self.iface.mainWindow()).exec_()

    def showSettings(self):
        settings_dlg = QgepSettingsDialog(self.iface.mainWindow())
        settings_dlg.exec_()