-
Notifications
You must be signed in to change notification settings - Fork 4
/
threedi_plugin.py
339 lines (273 loc) · 13.6 KB
/
threedi_plugin.py
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
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
from qgis.core import QgsApplication
from qgis.core import QgsMapLayer
from qgis.core import QgsPathResolver
from qgis.core import QgsProject
from qgis.core import QgsSettings
from qgis.PyQt.QtCore import QObject
from qgis.PyQt.QtGui import QIcon
from qgis.PyQt.QtWidgets import QAction
from qgis.PyQt.QtXml import QDomDocument
from qgis.PyQt.QtXml import QDomElement
from qgis.utils import iface
from threedi_results_analysis.gui.threedi_plugin_dockwidget import (
ThreeDiPluginDockWidget,
)
from threedi_results_analysis.misc_tools import About
from threedi_results_analysis.misc_tools import ShowLogfile
from threedi_results_analysis.misc_tools import ToggleResultsManager
from threedi_results_analysis.processing.providers import ThreediProvider
from threedi_results_analysis.temporal import TemporalManager
from threedi_results_analysis.threedi_plugin_layer_manager import (
ThreeDiPluginLayerManager,
)
from threedi_results_analysis.threedi_plugin_model import ThreeDiPluginModel
from threedi_results_analysis.threedi_plugin_model_serialization import (
ThreeDiPluginModelSerializer,
)
from threedi_results_analysis.threedi_plugin_model_validation import (
ThreeDiPluginModelValidator,
)
from threedi_results_analysis.tool_animation.map_animator import MapAnimator
from threedi_results_analysis.tool_flow_summary.flow_summary import FlowSummaryTool
from threedi_results_analysis.tool_graph.graph import ThreeDiGraph
from threedi_results_analysis.tool_sideview.sideview import ThreeDiSideView
from threedi_results_analysis.tool_statistics.statistics import StatisticsTool
from threedi_results_analysis.tool_water_balance import WaterBalanceTool
from threedi_results_analysis.tool_watershed.watershed_analysis import (
ThreeDiWatershedAnalyst,
)
from threedi_results_analysis.utils import color
from threedi_results_analysis.utils.qprojects import ProjectStateMixin
import logging
logger = logging.getLogger(__name__)
class ThreeDiPlugin(QObject, ProjectStateMixin):
"""Main Plugin Class which register toolbar ad menu and add tools"""
def __init__(self, iface):
QObject.__init__(self)
# Save reference to the QGIS interface
self.iface = iface
self.provider = None
def initProcessing(self):
"""Create the Qgis Processing Toolbox provider and its algorithms
Called by QGIS to check for processing algorithms.
"""
self.provider = ThreediProvider()
QgsApplication.processingRegistry().addProvider(self.provider)
def initGui(self):
"""Create the menu entries and toolbar icons inside the QGIS GUI.
Called when the plugin is loaded.
"""
self.model = ThreeDiPluginModel()
self.loader = ThreeDiPluginLayerManager()
self.validator = ThreeDiPluginModelValidator(self.model)
QgsProject.instance().writeProject.connect(self.write)
QgsProject.instance().writeMapLayer.connect(self.write_map_layer) # Called after write()
QgsProject.instance().readProject.connect(self.read)
QgsProject.instance().removeAll.connect(self.model.clear)
# Declare instance attributes
self.actions = []
self.menu = "&3Di Results Analysis"
assert not hasattr(self, "dockwidget") # Should be destroyed on unload
self.dockwidget = ThreeDiPluginDockWidget(None, iface)
# Set toolbar and init a few toolbar widgets
self.toolbar = self.iface.addToolBar("ThreeDiResultAnalysis")
self.toolbar.setObjectName("ThreeDiResultAnalysisToolBar")
# Init the rest of the tools
self.about_tool = About(iface)
self.toggle_results_manager = ToggleResultsManager(iface)
self.graph_tool = ThreeDiGraph(iface, self.model)
self.sideview_tool = ThreeDiSideView(iface, self.model)
self.stats_tool = StatisticsTool(iface, self.model)
self.water_balance_tool = WaterBalanceTool(iface, self.model)
self.watershed_tool = ThreeDiWatershedAnalyst(iface, self.model)
self.logfile_tool = ShowLogfile(iface)
self.temporal_manager = TemporalManager(self.model)
self.flow_summary_tool = FlowSummaryTool(self.dockwidget.get_tools_widget(), iface, self.model)
self.tools = [ # second item indicates enabled on startup
(self.about_tool, True),
(self.toggle_results_manager, True),
(self.flow_summary_tool, False),
(self.graph_tool, False),
(self.sideview_tool, False),
(self.stats_tool, False),
(self.water_balance_tool, False),
(self.watershed_tool, False),
(self.logfile_tool, True)
]
# Styling (TODO: can this be moved to where it is used?)
for color_ramp in color.COLOR_RAMPS:
color.add_color_ramp(color_ramp)
for tool, enabled in self.tools:
if tool.icon_path is not None:
self._add_action(
tool,
tool.icon_path,
text=tool.menu_text,
callback=tool.run,
parent=self.iface.mainWindow(),
enabled_flag=enabled
)
# Connect the signals
# Addition signals
self.dockwidget.grid_file_selected.connect(self.validator.validate_grid)
self.dockwidget.result_grid_file_selected.connect(self.validator.validate_result_grid)
self.validator.result_valid.connect(self.loader.load_result)
self.validator.grid_valid.connect(self.loader.load_grid)
self.loader.grid_loaded.connect(self.model.add_grid)
self.loader.result_loaded.connect(self.model.add_result)
self.model.grid_added.connect(self.dockwidget.expand_grid)
# Removal signals
# (note that model.remove_grid -> loader.unload_grid is connected
# later so that tools get the signals first)
self.dockwidget.result_removal_selected.connect(self.model.remove_result)
self.dockwidget.grid_removal_selected.connect(self.model.remove_grid)
# Modification signals
self.model.grid_changed.connect(self.loader.update_grid)
self.model.result_changed.connect(self.loader.update_result)
self.model.result_unchecked.connect(self.loader.result_unchecked)
self.toggle_results_manager.triggered.connect(self.dockwidget.toggle_visible)
self.dockwidget.set_model(self.model)
self.initProcessing()
# temporal manager signals
self.model.result_added.connect(self.temporal_manager.configure)
self.model.result_removed.connect(self.temporal_manager.configure)
self.dockwidget.align_starts_checked.connect(self.temporal_manager.set_align_starts)
# animation signals
self.map_animator = MapAnimator(self.dockwidget.get_tools_widget(), self.model)
self.model.result_checked.connect(self.map_animator.results_changed)
self.model.result_unchecked.connect(self.map_animator.results_changed)
self.model.result_added.connect(self.map_animator.results_changed)
self.model.result_removed.connect(self.map_animator.results_changed)
self.temporal_manager.updated.connect(self.map_animator.update_results)
# flow summary signals
self.model.result_removed.connect(self.flow_summary_tool.result_removed)
self.model.result_changed.connect(self.flow_summary_tool.result_changed)
self.model.result_added.connect(self.flow_summary_tool.result_added)
# graph signals
self.model.result_added.connect(self.graph_tool.result_added)
self.model.result_removed.connect(self.graph_tool.result_removed)
self.model.result_changed.connect(self.graph_tool.result_changed)
self.model.grid_changed.connect(self.graph_tool.grid_changed)
# sideview signals
self.model.grid_added.connect(self.sideview_tool.grid_added)
self.model.grid_removed.connect(self.sideview_tool.grid_removed)
self.model.grid_changed.connect(self.sideview_tool.grid_changed)
self.model.result_added.connect(self.sideview_tool.result_added)
self.model.result_removed.connect(self.sideview_tool.result_removed)
self.model.result_changed.connect(self.sideview_tool.result_changed)
self.temporal_manager.updated.connect(self.sideview_tool.update_waterlevels)
# watershed signals
self.model.result_added.connect(self.watershed_tool.result_added)
self.model.result_removed.connect(self.watershed_tool.result_removed)
self.model.result_changed.connect(self.watershed_tool.result_changed)
self.model.grid_changed.connect(self.watershed_tool.grid_changed)
self.watershed_tool.closing.connect(self.loader.reset_styling)
# statistics signals
self.model.result_added.connect(self.stats_tool.result_added)
self.model.result_removed.connect(self.stats_tool.result_removed)
self.model.result_changed.connect(self.stats_tool.result_changed)
self.model.grid_changed.connect(self.stats_tool.grid_changed)
# water balance signals
self.model.result_added.connect(self.water_balance_tool.result_added)
self.model.result_removed.connect(self.water_balance_tool.result_removed)
self.model.result_changed.connect(self.water_balance_tool.result_changed)
self.model.grid_changed.connect(self.water_balance_tool.grid_changed)
for tool, _ in self.tools:
self.dockwidget.add_custom_actions(tool.get_custom_actions())
# Further administrative signals that need to happens last:
# https://doc.qt.io/qt-5/signalsandslots.html#signals
# If several slots are connected to one signal, the slots will be executed one after the other,
# in the order they have been connected, when the signal is emitted.
self.model.grid_removed.connect(self.loader.unload_grid)
self.model.result_removed.connect(self.loader.unload_result)
self.init_state_sync()
# Disable warning that scratch layer data will be lost
QgsSettings().setValue("askToSaveMemoryLayers", False, QgsSettings.App)
def write(self, doc: QDomDocument) -> bool:
# Resolver convert relative to absolute paths and vice versa
resolver = QgsPathResolver(QgsProject.instance().fileName() if (QgsProject.instance().filePathStorage() == 1) else "")
res, node = ThreeDiPluginModelSerializer.write(self.model, doc, resolver)
if not res:
logger.error("Unable to write model to QGIS project file.")
return False
# Allow each tool to save additional info to the xml node
for tool, _ in self.tools:
if not tool.write(doc, node):
return False
# Also allow animator to persist settings
if not self.map_animator.write(doc, node):
return False
return True
def write_map_layer(self, layer: QgsMapLayer, elem: QDomElement, _: QDomDocument):
# Ensure all our dynamically added attributes are not serialized
result_field_names = self.model.get_result_field_names(layer.id())
ThreeDiPluginModelSerializer.remove_result_field_references(
elem, result_field_names,
)
def read(self, doc: QDomDocument) -> bool:
self.model.clear()
self.dockwidget.set_model(self.model)
# Resolver convert relative to absolute paths and vice versa
resolver = QgsPathResolver(QgsProject.instance().fileName() if (QgsProject.instance().filePathStorage() == 1) else "")
res, tool_node = ThreeDiPluginModelSerializer.read(self.loader, doc, resolver)
if not res:
self.model.clear()
return False
if tool_node:
# Allow each tool to read additional info from the dedicated xml node
for tool, _ in self.tools:
if not tool.read(tool_node):
self.model.clear()
return False
# Also allow animator to read saved settings
if not self.map_animator.read(tool_node):
self.model.clear()
return False
return True
def unload(self):
"""Removes the plugin menu item and icon from QGIS GUI.
Called then the plugin is unloaded.
"""
# Stop animating
self.temporal_manager.updated.disconnect(self.map_animator.update_results)
# Clears model and emits subsequent signals
self.model.clear()
self.unload_state_sync()
QgsApplication.processingRegistry().removeProvider(self.provider)
for action in self.actions:
self.iface.removePluginMenu("&3Di Results Analysis", action)
self.iface.removeToolBarIcon(action)
for tool, _ in self.tools:
tool.on_unload()
self.iface.removeDockWidget(self.dockwidget)
del self.dockwidget
del self.toolbar
def _add_action(
self,
tool_instance,
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."""
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.addPluginToMenu(self.menu, action)
setattr(tool_instance, "action_icon", action)
self.actions.append(action)
return action