-
Notifications
You must be signed in to change notification settings - Fork 1
/
geomelba_spirit.py
470 lines (428 loc) · 25 KB
/
geomelba_spirit.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
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
# -*- coding: utf-8 -*-
"""
/***************************************************************************
GeomelbaSpirit
A QGIS plugin
Based on GeoMelba software, meant to be used with the serious game CAUSERIE.
This file contains the functions to use when the user configure the first dialog of the plugin.
Once he clicked on the "Ok" button, some functions are going to launch depending on the parameters he chose.
Generated by Plugin Builder: http://g-sherman.github.io/Qgis-Plugin-Builder/
-------------------
begin : 2021-08-24
git sha : $Format:%H$
copyright : (C) 2021 by Jules Grillot / INRAE
email : [email protected]
***************************************************************************/
/***************************************************************************
* *
* 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. *
* *
***************************************************************************/
"""
import os.path
from qgis.core import QgsVectorFileWriter, QgsProject, QgsCoordinateReferenceSystem, QgsVectorLayer, QgsField, \
QgsPalLayerSettings, QgsVectorLayerSimpleLabeling, QgsMapLayer, QgsApplication
from qgis.PyQt.QtCore import QSettings, QTranslator, QCoreApplication, Qt
from qgis.PyQt.QtGui import QIcon
from qgis.PyQt.QtWidgets import QAction, QMessageBox
from PyQt5.QtCore import QVariant
# Import the code for the dialog
from .geomelba_spirit_dialog import GeomelbaSpiritDialog
from .watershed_creation.watershed_creation_dialog import WatershedCreationDialog
# Import the code for to launch the dock widget
from .serious_game.spirit_dockwidget import SpiritDockWidget
# Import the special QgsVectorLayer class for each element
from .serious_game.layers import ParcelLayer, LineLayer
# Import variables from the dictionary
from .dictionnaire import parcel_layer_name, line_layer_name, line_style_layer_name,\
original_layer_group_name, data_layer, field_type_parcel, field_type_parcel_origin, style_parcel,\
field_type_line_middle, field_type_line_left, field_type_line_right, field_type_line_top, field_type_line_bottom,\
field_top_line, style_multiple_line, field_parcel_id, field_type_line_origin, geopackage_layer_name_parcel, \
geopackage_layer_name_line, geopackage_layer_name_connexions, information_geopackage_error_pt1, \
information_geopackage_error_pt2, serious_game_data_folder, watershed_prefix
class GeomelbaSpirit:
"""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
self.project = QgsProject()
self.dlg = None
# 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',
'GeomelbaSpirit_{}.qm'.format(locale))
if os.path.exists(locale_path):
self.translator = QTranslator()
self.translator.load(locale_path)
QCoreApplication.installTranslator(self.translator)
# Declare instance attributes
self.actions = []
self.menu = self.tr(u'&Geomelba Spirit')
# Check if plugin was started the first time in current QGIS session
# Must be set in initGui() to survive plugin reloads
self.first_start = None
self.pluginIsActive = False
self.dockwidget = None
self.watershed_creation = None
# 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('GeomelbaSpirit', 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:
# Adds plugin icon to Plugins toolbar
self.iface.addToolBarIcon(action)
if add_to_menu:
self.iface.addPluginToMenu(
self.menu,
action)
self.actions.append(action)
return action
def initGui(self):
"""Create the menu entries and toolbar icons inside the QGIS GUI."""
icon_path = self.plugin_dir + '/icon.png'
self.add_action(
icon_path,
text=self.tr(u'Geomelba Spirit'),
callback=self.run,
parent=self.iface.mainWindow())
# will be set False in run()
self.first_start = True
def onClosePlugin(self, sender):
"""Cleanup necessary items here when plugin is closed"""
self.pluginIsActive = False
if sender == "dockwidget":
# Disconnect the function connected to the signal emitted by the CRS when it is changed.
self.dockwidget.project.crsChanged.disconnect(self.dockwidget.crs_change)
# Disconnect functions on layers.
self.dockwidget.parcel_layer.attributeValueChanged.disconnect(self.dockwidget.write_change)
self.dockwidget.line_layer.attributeValueChanged.disconnect(self.dockwidget.write_change)
self.dockwidget.parcel_layer.selectionChanged.disconnect(self.dockwidget.check_valid)
self.dockwidget.line_layer.selectionChanged.disconnect(self.dockwidget.check_valid)
self.dockwidget.project.layerTreeRoot().visibilityChanged.disconnect(
self.dockwidget.layer_visibility_management)
# Hide the line layer used for the legend and show the reel line layer.
root = self.project.layerTreeRoot()
for layer in self.project.mapLayers().values():
ltv = self.iface.layerTreeView()
# model = ltv.model()
if layer.name() == line_layer_name:
index = ltv.layerTreeModel().node2index(root.findLayer(layer))
ltv.setRowHidden(index.row(), index.parent(), False)
ltv.setCurrentIndex(ltv.layerTreeModel().node2index(root))
# layer.setFlags(QgsMapLayer.Identifiable)
# layer.setFlags(QgsMapLayer.Removable)
elif layer.name() == line_style_layer_name:
# layer.setFlags(QgsMapLayer.Private)
index = ltv.layerTreeModel().node2index(root.findLayer(layer))
ltv.setRowHidden(index.row(), index.parent(), True)
ltv.setCurrentIndex(ltv.layerTreeModel().node2index(root))
self.dockwidget.setParent(None)
def unload(self):
"""Removes the plugin menu item and icon from QGIS GUI."""
for action in self.actions:
self.iface.removePluginMenu(
self.tr(u'&Geomelba Spirit'),
action)
self.iface.removeToolBarIcon(action)
def saving_geopackage(self, layer, name, out_path, coordinate_system, overwrite):
"""Save a layer to a geopackage file. If it already exists it is overwritten.
Variables are :
- layer to save into the geopackage
- name of the layer
- output path of the geopackage
- the coordinate reference system for the new layers
- boolean to know if the geopackage needs to be filled or overwritten
"""
context = self.project.transformContext()
options = QgsVectorFileWriter.SaveVectorOptions()
# if overwrite is set to true, the geopackage will erase the previous one.
if not overwrite:
if os.path.isfile(out_path):
options.actionOnExistingFile = QgsVectorFileWriter.CreateOrOverwriteLayer
options.layerName = name
options.fileEncoding = layer.dataProvider().encoding()
options.driverName = "GPKG"
layer.setCrs(coordinate_system)
QgsVectorFileWriter.writeAsVectorFormatV2(layer, out_path, context, options)
def run(self):
"""Set up the dialog for the user options and realize actions when the user clicked on the "OK" button.
Several actions are realized :
- Selection of the output folder
- Selection of the crs
- Selection of the watershed data
if a know watershed is selected:
- Creation of a directory to put the newly created data
- Creation of a folder in the layer panel to store the layers already in the project
- Creation of the new layers
- Creation of new type field so we can keep the original values and check changes
- Add style to the layers
- Creation of an empty memory layer with a specific style for the lines to get a nice legend in the layer
panel
- Add the dockwidget panel to QGIS
else:
- Launching a dialog to create new watershed data
"""
if not self.pluginIsActive:
self.dlg = GeomelbaSpiritDialog()
# Put the dialog window on top.
self.dlg.setModal(True)
self.project = QgsProject.instance()
# If there is no layer in the project, the default CRS is 2154.
if len(self.project.mapLayers()) == 0:
# self.dlg.crs_selector.setCrs(QgsCoordinateReferenceSystem(self.project.crs()))
self.dlg.crs_selector.setCrs(QgsCoordinateReferenceSystem(2154))
# If there is layers in the project, the default CRS is the one used by the mapCanvas.
else:
self.dlg.crs_selector.setCrs(
QgsCoordinateReferenceSystem(self.iface.mapCanvas().mapSettings().destinationCrs().authid()))
# show the dialog
self.dlg.show()
# Run the dialog event loop
result = self.dlg.exec_()
# See if OK was pressed
if result:
parcel_layer = None
line_layer = None
new_parcel_layer = None
new_line_layer = None
connexion_layer = None
self.pluginIsActive = True
# Watershed name used to find the data
watershed_name = self.dlg.watershed_button_group.button(
self.dlg.watershed_button_group.checkedId()).accessibleName().lower()
# Path variables
if self.dlg.output_text.text()[-1] == "/":
output_path = self.dlg.output_text.text()
else:
output_path = self.dlg.output_text.text() + "/"
# Get CRS from widget and set CRS for project
crs = self.dlg.crs_selector.crs()
self.project.setCrs(crs)
if watershed_name != "create_watershed":
input_path = self.plugin_dir + serious_game_data_folder + watershed_prefix + str(watershed_name)
# Check if the linear and parcel layer already exist in th project, if so we change their name
if self.project.mapLayersByName(line_style_layer_name):
layer = self.project.mapLayersByName(line_style_layer_name)[0]
layer.setName(line_style_layer_name + "_1")
if self.project.mapLayersByName(line_layer_name):
layer = self.project.mapLayersByName(line_layer_name)[0]
layer.setName(line_layer_name + "_1")
if self.project.mapLayersByName(parcel_layer_name):
layer = self.project.mapLayersByName(parcel_layer_name)[0]
layer.setName(parcel_layer_name + "_1")
# All the layers already in the Qgis project are stored in a directory.
root = self.project.layerTreeRoot()
names = [layer.name() for layer in self.project.mapLayers().values()]
if len(names) != 0:
group = root.findGroup(original_layer_group_name)
if not group:
root.insertGroup(0, original_layer_group_name)
group = root.findGroup(original_layer_group_name)
for child in root.children():
if child.name() == original_layer_group_name:
pass
else:
my_clone = child.clone()
parent = child.parent()
group.insertChildNode(0, my_clone)
parent.removeChildNode(child)
group.setExpanded(0)
group.setItemVisibilityChecked(False)
# Get the layers from the geopackage
geopackage_path = input_path + "/" + watershed_prefix + str(watershed_name) + '.gpkg'
geopackage = QgsVectorLayer(geopackage_path, "", "ogr")
layers = geopackage.dataProvider().subLayers()
error_count = 0
for layer in layers:
name = layer.split('!!::!!')[1]
uri = "%s|layername=%s" % (geopackage_path, name,)
if name == geopackage_layer_name_parcel:
parcel_layer = QgsVectorLayer(uri, name, 'ogr')
error_count = error_count + 1
elif name == geopackage_layer_name_line:
line_layer = QgsVectorLayer(uri, name, 'ogr')
error_count = error_count + 1
elif name == geopackage_layer_name_connexions:
connexion_layer = QgsVectorLayer(uri, name, 'ogr')
connexion_layer.setCrs(crs)
error_count = error_count + 1
if error_count != 3:
QMessageBox.information(
None, information_geopackage_error_pt1, information_geopackage_error_pt2)
else:
# Test if the output folder and data folder exist, if not they are created
output_directory = output_path + watershed_name + "/"
if not os.path.exists(output_directory):
os.makedirs(output_directory)
data_directory = output_directory + data_layer + "/"
if not os.path.exists(data_directory):
os.makedirs(data_directory)
# Save the layers into a new geopackage into the data folder.
self.saving_geopackage(
parcel_layer, parcel_layer_name, data_directory + data_layer + ".gpkg", crs, True)
self.saving_geopackage(
line_layer, line_layer_name, data_directory + data_layer + ".gpkg", crs, False)
# Add the layers to the project.
gpkg = QgsVectorLayer(data_directory + data_layer + ".gpkg", "", "ogr")
layers = gpkg.dataProvider().subLayers()
for layer in layers:
name = layer.split('!!::!!')[1]
uri = "%s|layername=%s" % (data_directory + data_layer + ".gpkg", name,)
if name == parcel_layer_name:
new_parcel_layer = ParcelLayer(uri, name, 'ogr')
self.project.addMapLayer(new_parcel_layer)
elif name == line_layer_name:
new_line_layer = LineLayer(uri, name, 'ogr')
self.project.addMapLayer(new_line_layer)
# Create a new type attribute for the parcel layer.
new_parcel_layer.startEditing()
new_parcel_layer.addAttribute(QgsField(field_type_parcel, QVariant.Int, "int", 3))
for parcel in new_parcel_layer.getFeatures():
attrs = parcel.attributes()
new_value = attrs[new_parcel_layer.fields().indexFromName(field_type_parcel_origin)]
new_parcel_layer.changeAttributeValue(parcel.id(), new_parcel_layer.fields().indexFromName(
field_type_parcel), new_value)
# Add a style to the parcel layer.
new_parcel_layer.commitChanges()
new_parcel_layer.triggerRepaint()
new_parcel_layer.loadNamedStyle(input_path + "/" + style_parcel)
label_settings = QgsPalLayerSettings()
label_settings.drawLabels = True
label_settings.fieldName = field_parcel_id
new_parcel_layer.setLabelsEnabled(True)
new_parcel_layer.setLabeling(QgsVectorLayerSimpleLabeling(label_settings))
new_parcel_layer.triggerRepaint()
new_parcel_layer.saveStyleToDatabase(name="ocsol", description="example", useAsDefault=True,
uiFileContent="")
# Create new types attributes for the line layer.
new_line_layer.startEditing()
new_line_layer.addAttribute(QgsField(field_type_line_middle, QVariant.Int, "int", 1))
new_line_layer.addAttribute(QgsField(field_type_line_top, QVariant.Int, "int", 1))
new_line_layer.addAttribute(QgsField(field_type_line_bottom, QVariant.Int, "int", 1))
# Check if left or right is the top or the bottom.
for line in new_line_layer.getFeatures():
attrs = line.attributes()
up_side = attrs[new_line_layer.fields().indexFromName(field_top_line)]
if up_side == "left":
type_up = attrs[new_line_layer.fields().indexFromName(field_type_line_left)]
type_dwn = attrs[new_line_layer.fields().indexFromName(field_type_line_right)]
else:
type_up = attrs[new_line_layer.fields().indexFromName(field_type_line_right)]
type_dwn = attrs[new_line_layer.fields().indexFromName(field_type_line_left)]
type_center = attrs[new_line_layer.fields().indexFromName(field_type_line_origin)]
if type_center == 0 and (type_up != 0 or type_dwn != 0):
if type_up != 0 and type_dwn != 0:
type_center = type_dwn
type_dwn = 0
elif type_dwn == 0:
type_center = type_up
type_up = 0
elif type_up == 0:
type_center = type_dwn
type_dwn = 0
new_line_layer.changeAttributeValue(line.id(), new_line_layer.fields().indexFromName(
field_type_line_middle), type_center)
new_line_layer.changeAttributeValue(line.id(), new_line_layer.fields().indexFromName(
field_type_line_top), type_up)
new_line_layer.changeAttributeValue(line.id(), new_line_layer.fields().indexFromName(
field_type_line_bottom), type_dwn)
new_line_layer.changeAttributeValue(line.id(), new_line_layer.fields().indexFromName(
field_type_line_left), 0)
new_line_layer.changeAttributeValue(line.id(), new_line_layer.fields().indexFromName(
field_type_line_right), 0)
# Add a style to the line layer.
new_line_layer.commitChanges()
new_line_layer.triggerRepaint()
new_line_layer.loadNamedStyle(input_path + "/" + style_multiple_line)
new_line_layer.triggerRepaint()
new_line_layer.saveStyleToDatabase(name="line_type", description="example", useAsDefault=True,
uiFileContent="")
# Create a memory layer to be used as legend in QGIS.
line_style = QgsVectorLayer("LineString", line_style_layer_name, "memory")
layer_crs = line_style.crs()
layer_crs.createFromId(crs.postgisSrid())
line_style.setCrs(layer_crs)
self.project.addMapLayer(line_style)
# Open the dockwidget with arguments.
self.dockwidget = SpiritDockWidget(parent=None, iface=self.iface, project=self.project,
watershed_name=watershed_name, parcel_layer=new_parcel_layer,
line_layer=new_line_layer, style_line_layer=line_style,
connexion_layer=connexion_layer, crs=crs,
output_path=output_directory)
# Connect to provide cleanup on closing of dockwidget.
self.dockwidget.closingPlugin.connect(lambda sender="dockwidget": self.onClosePlugin(sender))
self.iface.addDockWidget(Qt.RightDockWidgetArea, self.dockwidget)
self.dockwidget.show()
else:
# input_path = self.plugin_dir + serious_game_data_folder
self.watershed_creation = WatershedCreationDialog(parent=None, crs=crs, path=output_path)
self.watershed_creation.closingPlugin.connect(lambda sender="creation": self.onClosePlugin(sender))
self.watershed_creation.show()
self.dlg.close()