File: ProcessingToolbox.py

package info (click to toggle)
qgis 3.40.6%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: trixie
  • size: 1,181,336 kB
  • sloc: cpp: 1,593,302; python: 370,494; xml: 23,474; perl: 3,664; sh: 3,482; ansic: 2,257; sql: 2,133; yacc: 1,068; lex: 577; javascript: 540; lisp: 411; makefile: 157
file content (284 lines) | stat: -rw-r--r-- 11,537 bytes parent folder | download | duplicates (6)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
"""
***************************************************************************
    ProcessingToolbox.py
    ---------------------
    Date                 : August 2012
    Copyright            : (C) 2012 by Victor Olaya
    Email                : volayaf at gmail dot 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.                                   *
*                                                                         *
***************************************************************************
"""

__author__ = "Victor Olaya"
__date__ = "August 2012"
__copyright__ = "(C) 2012, Victor Olaya"

import operator
import os
import warnings

from qgis.PyQt import uic
from qgis.PyQt.QtCore import Qt, QCoreApplication, pyqtSignal
from qgis.PyQt.QtWidgets import QWidget, QToolButton, QMenu, QAction
from qgis.utils import iface
from qgis.core import (
    QgsWkbTypes,
    QgsMapLayerType,
    QgsApplication,
    QgsProcessingAlgorithm,
)
from qgis.gui import QgsGui, QgsDockWidget, QgsProcessingToolboxProxyModel

from processing.gui.Postprocessing import handleAlgorithmResults
from processing.core.ProcessingConfig import ProcessingConfig
from processing.gui.MessageDialog import MessageDialog
from processing.gui.EditRenderingStylesDialog import EditRenderingStylesDialog
from processing.gui.MessageBarProgress import MessageBarProgress
from processing.gui.ProviderActions import ProviderActions, ProviderContextMenuActions
from processing.tools import dataobjects

pluginPath = os.path.split(os.path.dirname(__file__))[0]

with warnings.catch_warnings():
    warnings.filterwarnings("ignore", category=DeprecationWarning)
    WIDGET, BASE = uic.loadUiType(
        os.path.join(pluginPath, "ui", "ProcessingToolbox.ui")
    )


class ProcessingToolbox(QgsDockWidget, WIDGET):
    ALG_ITEM = "ALG_ITEM"
    PROVIDER_ITEM = "PROVIDER_ITEM"
    GROUP_ITEM = "GROUP_ITEM"

    NAME_ROLE = Qt.ItemDataRole.UserRole
    TAG_ROLE = Qt.ItemDataRole.UserRole + 1
    TYPE_ROLE = Qt.ItemDataRole.UserRole + 2

    # Trigger algorithm execution
    executeWithGui = pyqtSignal(str, QWidget, bool, bool)

    def __init__(self):
        super().__init__(None)
        self.tipWasClosed = False
        self.in_place_mode = False
        self.setupUi(self)
        self.setAllowedAreas(
            Qt.DockWidgetArea.LeftDockWidgetArea | Qt.DockWidgetArea.RightDockWidgetArea
        )
        self.processingToolbar.setIconSize(iface.iconSize(True))

        self.algorithmTree.setRegistry(
            QgsApplication.processingRegistry(),
            QgsGui.instance().processingRecentAlgorithmLog(),
            QgsGui.instance().processingFavoriteAlgorithmManager(),
        )
        filters = QgsProcessingToolboxProxyModel.Filters(
            QgsProcessingToolboxProxyModel.Filter.FilterToolbox
        )
        if ProcessingConfig.getSetting(ProcessingConfig.SHOW_ALGORITHMS_KNOWN_ISSUES):
            filters |= QgsProcessingToolboxProxyModel.Filter.FilterShowKnownIssues
        self.algorithmTree.setFilters(filters)

        self.searchBox.setShowSearchIcon(True)

        self.searchBox.textChanged.connect(self.set_filter_string)
        self.searchBox.returnPressed.connect(self.activateCurrent)
        self.algorithmTree.customContextMenuRequested.connect(self.showPopupMenu)
        self.algorithmTree.doubleClicked.connect(self.executeAlgorithm)
        self.txtTip.setVisible(self.disabledProviders())

        def openSettings(url):
            if url == "close":
                self.txtTip.setVisible(False)
                self.tipWasClosed = True
            else:
                iface.showOptionsDialog(iface.mainWindow(), "processingOptions")
                self.txtTip.setVisible(self.disabledProviders())

        self.txtTip.linkActivated.connect(openSettings)
        if hasattr(self.searchBox, "setPlaceholderText"):
            self.searchBox.setPlaceholderText(
                QCoreApplication.translate("ProcessingToolbox", "Search…")
            )

        # connect to existing providers
        for p in QgsApplication.processingRegistry().providers():
            if p.isActive():
                self.addProviderActions(p)

        QgsApplication.processingRegistry().providerRemoved.connect(self.addProvider)
        QgsApplication.processingRegistry().providerRemoved.connect(self.removeProvider)

        iface.currentLayerChanged.connect(self.layer_changed)

    def set_filter_string(self, string):
        filters = self.algorithmTree.filters()
        if ProcessingConfig.getSetting(ProcessingConfig.SHOW_ALGORITHMS_KNOWN_ISSUES):
            filters |= QgsProcessingToolboxProxyModel.Filter.FilterShowKnownIssues
        else:
            filters &= ~QgsProcessingToolboxProxyModel.Filter.FilterShowKnownIssues
        self.algorithmTree.setFilters(filters)
        self.algorithmTree.setFilterString(string)

    def set_in_place_edit_mode(self, enabled):
        filters = QgsProcessingToolboxProxyModel.Filters(
            QgsProcessingToolboxProxyModel.Filter.FilterToolbox
        )
        if ProcessingConfig.getSetting(ProcessingConfig.SHOW_ALGORITHMS_KNOWN_ISSUES):
            filters |= QgsProcessingToolboxProxyModel.Filter.FilterShowKnownIssues

        if enabled:
            self.algorithmTree.setFilters(
                filters | QgsProcessingToolboxProxyModel.Filter.FilterInPlace
            )
        else:
            self.algorithmTree.setFilters(filters)
        self.in_place_mode = enabled

    def layer_changed(self, layer):
        if layer is None or layer.type() != QgsMapLayerType.VectorLayer:
            return
        self.algorithmTree.setInPlaceLayer(layer)

    def disabledProviders(self):
        showTip = ProcessingConfig.getSetting(ProcessingConfig.SHOW_PROVIDERS_TOOLTIP)
        if not showTip or self.tipWasClosed:
            return False

        for provider in QgsApplication.processingRegistry().providers():
            if not provider.isActive() and provider.canBeActivated():
                return True

        return False

    def addProviderActions(self, provider):
        if provider.id() in ProviderActions.actions:
            toolbarButton = QToolButton()
            toolbarButton.setObjectName("provideraction_" + provider.id())
            toolbarButton.setIcon(provider.icon())
            toolbarButton.setToolTip(provider.name())
            toolbarButton.setPopupMode(QToolButton.ToolButtonPopupMode.InstantPopup)

            actions = ProviderActions.actions[provider.id()]
            menu = QMenu(provider.name(), self)
            for action in actions:
                action.setData(self)
                act = QAction(action.name, menu)
                act.triggered.connect(action.execute)
                menu.addAction(act)
            toolbarButton.setMenu(menu)
            self.processingToolbar.addWidget(toolbarButton)

    def addProvider(self, provider_id):
        provider = QgsApplication.processingRegistry().providerById(provider_id)
        if provider is not None:
            self.addProviderActions(provider)

    def removeProvider(self, provider_id):
        button = self.findChild(QToolButton, "provideraction-" + provider_id)
        if button:
            self.processingToolbar.removeChild(button)

    def showPopupMenu(self, point):
        index = self.algorithmTree.indexAt(point)
        popupmenu = QMenu()
        alg = self.algorithmTree.algorithmForIndex(index)
        if alg is not None:
            executeAction = QAction(
                QCoreApplication.translate("ProcessingToolbox", "Execute…"), popupmenu
            )
            executeAction.triggered.connect(self.executeAlgorithm)
            popupmenu.addAction(executeAction)
            if alg.flags() & QgsProcessingAlgorithm.Flag.FlagSupportsBatch:
                executeBatchAction = QAction(
                    QCoreApplication.translate(
                        "ProcessingToolbox", "Execute as Batch Process…"
                    ),
                    popupmenu,
                )
                executeBatchAction.triggered.connect(
                    self.executeAlgorithmAsBatchProcess
                )
                popupmenu.addAction(executeBatchAction)
            popupmenu.addSeparator()
            editRenderingStylesAction = QAction(
                QCoreApplication.translate(
                    "ProcessingToolbox", "Edit Rendering Styles for Outputs…"
                ),
                popupmenu,
            )
            editRenderingStylesAction.triggered.connect(self.editRenderingStyles)
            popupmenu.addAction(editRenderingStylesAction)

            popupmenu.addSeparator()
            actionText = QCoreApplication.translate(
                "ProcessingToolbox", "Add to Favorites"
            )
            if (
                QgsGui.instance()
                .processingFavoriteAlgorithmManager()
                .isFavorite(alg.id())
            ):
                actionText = QCoreApplication.translate(
                    "ProcessingToolbox", "Remove from Favorites"
                )
            favoriteAction = QAction(actionText, popupmenu)
            favoriteAction.triggered.connect(self.toggleFavorite)
            popupmenu.addAction(favoriteAction)

            actions = ProviderContextMenuActions.actions
            if len(actions) > 0:
                popupmenu.addSeparator()
            for action in actions:
                action.setData(alg, self)
                if action.is_separator:
                    popupmenu.addSeparator()
                elif action.isEnabled():
                    contextMenuAction = QAction(action.name, popupmenu)
                    contextMenuAction.setIcon(action.icon())
                    contextMenuAction.triggered.connect(action.execute)
                    popupmenu.addAction(contextMenuAction)

            popupmenu.exec(self.algorithmTree.mapToGlobal(point))

    def editRenderingStyles(self):
        alg = (
            self.algorithmTree.selectedAlgorithm().create()
            if self.algorithmTree.selectedAlgorithm() is not None
            else None
        )
        if alg is not None:
            dlg = EditRenderingStylesDialog(alg)
            dlg.exec()

    def activateCurrent(self):
        self.executeAlgorithm()

    def executeAlgorithmAsBatchProcess(self):
        alg = self.algorithmTree.selectedAlgorithm()
        if alg is not None:
            self.executeWithGui.emit(alg.id(), self, self.in_place_mode, True)

    def executeAlgorithm(self):
        alg = self.algorithmTree.selectedAlgorithm()
        if alg is not None:
            self.executeWithGui.emit(alg.id(), self, self.in_place_mode, False)

    def toggleFavorite(self):
        alg = self.algorithmTree.selectedAlgorithm()
        if alg is not None:
            if (
                QgsGui.instance()
                .processingFavoriteAlgorithmManager()
                .isFavorite(alg.id())
            ):
                QgsGui.instance().processingFavoriteAlgorithmManager().remove(alg.id())
            else:
                QgsGui.instance().processingFavoriteAlgorithmManager().add(alg.id())