/
gison3dmap.py
executable file
·428 lines (344 loc) · 15.9 KB
/
gison3dmap.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
# -*- coding: utf-8 -*-
"""
/***************************************************************************
gison3dmap
A QGIS plugin
Client for gison3dmap to project gis data in a physical terrain model
-------------------
begin : 2015-07-24
git sha : $Format:%H$
copyright : (C) 2015 by Alexandre Neto (for CCC Geomática)
email : alex.f.neto@gmail.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. *
* *
***************************************************************************/
"""
import os.path, sys, re
from qgis.PyQt.QtCore import QTranslator, QCoreApplication
from qgis.PyQt.QtWidgets import QAction
from qgis.PyQt.QtGui import QIcon
from qgis.core import QgsApplication, QgsSettings
from gison3dmap.gison3dmap_dialog import gison3dmapDialog
from gison3dmap.config_dialog import configDialog
from gison3dmap.tools.layersxml import get_layer_legend, define_layer, get_layer_filter
from gison3dmap.tools import tocontroller, utils
import gison3dmap.tools.config as config
class gison3dmap:
"""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
# and other elements
self.iface = iface
self.canvas = self.iface.mapCanvas()
self.tree_view = self.iface.layerTreeView()
# initialize plugin directory
self.plugin_dir = os.path.dirname(__file__)
# initialize locale
locale = QgsApplication.locale()
locale_path = '{}/i18n/gison3dmap_{}.qm'.format(self.plugin_dir, locale)
if os.path.exists(locale_path):
self.translator = QTranslator()
self.translator.load(locale_path)
QCoreApplication.installTranslator(self.translator)
# Create the dialogs (after translation) and keep reference
self.send_commands_dlg = gison3dmapDialog()
self.config_dlg = configDialog()
# Declare instance attributes
self.actions = []
self.menu = self.tr('&gison3dmap')
self.toolbar = self.iface.addToolBar('gison3dmap')
self.toolbar.setObjectName('gison3dmap')
# Save reference from shared configuration instance
self.cfg = config.shared
# 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('gison3dmap', message)
def add_action(
self,
icon_path,
text,
callback,
enabled_flag=True,
add_to_menu=True,
add_to_toolbar=True,
status_tip=None,
whats_this=None,
parent=None):
"""Add a toolbar icon to the toolbar.
:param icon_path: Path to the icon for this action. Can be a resource
path (e.g. ':/plugins/foo/bar.png') or a normal file system path.
:type icon_path: str
:param text: Text that should be shown in menu items for this action.
:type text: str
:param callback: Function to be called when the action is triggered.
:type callback: function
:param enabled_flag: A flag indicating if the action should be enabled
by default. Defaults to True.
:type enabled_flag: bool
:param add_to_menu: Flag indicating whether the action should also
be added to the menu. Defaults to True.
:type add_to_menu: bool
:param add_to_toolbar: Flag indicating whether the action should also
be added to the toolbar. Defaults to True.
:type add_to_toolbar: bool
:param status_tip: Optional text to show in a popup when mouse pointer
hovers over the action.
:type status_tip: str
:param parent: Parent widget for the new action. Defaults None.
:type parent: QWidget
:param whats_this: Optional text to show in the status bar when the
mouse pointer hovers over the action.
:returns: The action that was created. Note that the action is also
added to self.actions list.
:rtype: QAction
"""
icon = QIcon(icon_path)
action = QAction(icon, text, parent)
action.triggered.connect(callback)
action.setEnabled(enabled_flag)
if status_tip is not None:
action.setStatusTip(status_tip)
if whats_this is not None:
action.setWhatsThis(whats_this)
if add_to_toolbar:
self.toolbar.addAction(action)
if add_to_menu:
self.iface.addPluginToMenu(
self.menu,
action)
self.actions.append(action)
return action
def initGui(self):
"""Create the menu entries and toolbar icons inside the QGIS GUI."""
self.send_Selection_action = self.add_action(
QIcon(os.path.join(self.plugin_dir, 'icons', 'cmdAddSelection.png')),
text=self.tr('Seleção'),
callback=self.sendSelection,
parent=self.iface.mainWindow(),
enabled_flag=False)
self.send_Layer_action = self.add_action(
QIcon(os.path.join(self.plugin_dir, 'icons', 'cmdAddLayer.png')),
text=self.tr('Camada ou Grupo'),
callback=self.sendLayer,
parent=self.iface.mainWindow(),
enabled_flag=False)
self.send_Map_action = self.add_action(
QIcon(os.path.join(self.plugin_dir, 'icons', 'cmdAllLayers.png')),
text=self.tr('Mapa'),
callback=self.sendMap,
parent=self.iface.mainWindow(),
enabled_flag=False)
self.add_action(
QIcon(os.path.join(self.plugin_dir, 'icons', 'cmdClear.png')),
text=self.tr('Limpar'),
callback=self.clear,
parent=self.iface.mainWindow())
self.add_action(
QIcon(os.path.join(self.plugin_dir, 'icons', 'cmdComando.png')),
text=self.tr('Enviar comandos'),
callback=self.sendCommands,
parent=self.iface.mainWindow())
self.add_action(
QIcon(os.path.join(self.plugin_dir, 'icons', 'cmdConfig.png')),
text=self.tr('Configuração'),
callback=self.configuration,
parent=self.iface.mainWindow())
# connect signals for button behavior
self.iface.currentLayerChanged['QgsMapLayer *'].connect(self.toggle)
self.canvas.selectionChanged.connect(self.toggle)
self.canvas.mapCanvasRefreshed.connect(self.toggle)
def unload(self):
"""Removes the plugin menu item and icon from QGIS GUI."""
for action in self.actions:
self.iface.removePluginMenu(
self.tr('&gison3dmap'),
action)
self.iface.removeToolBarIcon(action)
# remove the toolbar
del self.toolbar
def toggle(self):
"""
function to activate or deactivate the plugin buttons
:return:
"""
# disconnect all previously connect signals of the node
try:
self.current_node.visibilityChanged.disconnect(self.toggle)
except:
pass
# get current active node
self.current_node = self.tree_view.currentNode()
if self.current_node is None:
#No node is selected disable selection and layer buttons
self.send_Selection_action.setEnabled(False)
self.send_Layer_action.setEnabled(False)
elif self.current_node.nodeType() == 1:
#In this case the node is a QgsLayerTree
layer = self.current_node.layer()
# Check if it is possible to use selection command
if layer.type() == layer.VectorLayer and layer.selectedFeatureCount() > 0:
self.send_Selection_action.setEnabled(True)
else:
self.send_Selection_action.setEnabled(False)
self.send_Layer_action.setEnabled(True)
elif self.current_node.nodeType() == 0:
#In this case the node is a QgsLayerGroup
self.send_Selection_action.setEnabled(False)
# Check if there are visible layers on the current node
visible = False
for layer in self.current_node.findLayers():
if layer.isVisible():
visible = True
break
if visible:
self.send_Layer_action.setEnabled(True)
else:
self.send_Layer_action.setEnabled(False)
# Create a slot waiting for visibility changes on any child layer in the node
self.current_node.visibilityChanged.connect(self.toggle)
# See if there are any visible layers on the map canvas
if self.canvas.layerCount() > 0:
self.send_Map_action.setEnabled(True)
else:
self.send_Map_action.setEnabled(False)
def sendSelection(self):
"""Function to send selected features on the active layer to gison3dmap"""
layer = self.canvas.currentLayer()
commands = list()
if self.cfg.clear_before_draw_map:
commands.append('CLEAR')
# Try to get the legend form layer
layer_legend = get_layer_legend(layer)
if layer_legend:
# Get IDs from selected Features
ids = layer.selectedFeaturesIds()
ids = [id + 1 for id in ids]
#convert the list to a string to use in LAYERID command
ids_str = ','.join(map(str, ids))
# Replace all colors in legend by project selection color
qcolor = self.canvas.mapSettings().selectionColor()
s_color = ','.join(map(str, qcolor.getRgb()))
s_color = utils.rgba2argb(s_color, 1.0)
layer_legend = re.sub(r'\d{1,3},\d{1,3},\d{1,3},\d{1,3}', s_color, layer_legend)
commands.append('DEFINELAYER ' + define_layer(layer))
commands.append('LEGEND ' + layer_legend)
commands.append('LAYERID ' + layer.name() + ',' + ids_str)
commands.append('DRAW')
if len(commands) > 2:
tocontroller.send_messages(commands)
else:
error_msg = 'The following layer is not compatible with gison3dmap: ' + layer.name()
self.iface.messageBar().pushMessage('gison3dmap', error_msg, 0, 10)
def sendLayer(self):
"""Function to send active layer or layer group to gison3dmap"""
current_node = self.tree_view.currentNode()
if current_node.nodeType() == 1:
#In this case the node is a QgsLayerTree
#One single layer will be projected
layer = current_node.layer()
group_layers = [layer]
elif current_node.nodeType() == 0:
#In this case the node is a QgsLayerGroup
#All visible layers with the group should be projected
layers_tree = current_node.findLayers()
group_layers = [layer.layer() for layer in layers_tree if layer.isVisible()]
else:
group_layers = None
commands = list()
if self.cfg.clear_before_draw_map:
commands.append('CLEAR')
for layer in group_layers[::-1]: # [::-1] is used to reverse the order of layers to project
# Try to get the legend from layer
try:
layer_legend = get_layer_legend(layer)
except AttributeError:
layer_legend = None
if layer.type() == layer.VectorLayer and layer_legend:
commands.append('DEFINELAYER ' + define_layer(layer))
commands.append('LEGEND ' + layer_legend)
commands.append('LAYERSQL ' + layer.name() + ', ' + get_layer_filter(layer))
elif layer.type() == layer.RasterLayer and layer_legend:
commands.append('DEFINEGRID ' + layer.name() + ',' + layer_legend)
commands.append('GRID ' + layer.name())
else:
error_msg = 'The following layer is not compatible with gison3dmap: ' + layer.name()
self.iface.messageBar().pushMessage('gison3dmao', error_msg, 0, 10)
commands.append('DRAW')
tocontroller.send_messages(commands)
def sendMap(self):
"""Function to send all visible layers to gison3dmap"""
visible_layers = self.canvas.layers()
commands = list()
if self.cfg.clear_before_draw_map:
commands.append('CLEAR')
# Since last defined layer will be projected above the other, we need to iterate the
# Visible layer at the inverse order,i.e., bottom to top. That's why [::-1] was used
for layer in visible_layers[::-1]:
layer_legend = get_layer_legend(layer)
try:
layer_legend = get_layer_legend(layer)
except AttributeError:
layer_legend = None
if layer.type() == layer.VectorLayer and layer_legend:
commands.append('DEFINELAYER ' + define_layer(layer))
commands.append('LEGEND ' + layer_legend)
commands.append('LAYERSQL ' + layer.name() + ', ' + get_layer_filter(layer))
elif layer.type() == layer.RasterLayer and layer_legend:
commands.append('DEFINEGRID ' + layer.name() + ',' + layer_legend)
commands.append('GRID ' + layer.name())
else:
error_msg = 'The following layer is not compatible with gison3dmap: ' + layer.name()
self.iface.messageBar().pushMessage('gison3dmap', error_msg, 0, 10)
commands.append('DRAW')
# Check if list of commands are more that just CLEAR and DRAW and a DEFINE LAYER
# Meaning that there are no valid layers to project
if len(commands) > 2:
tocontroller.send_messages(commands)
def clear(self):
"""
Function to clear all layers from gison3dmap
"""
commands = ['CLEAR', 'DRAW']
tocontroller.send_messages(commands)
def sendCommands(self):
"""Function to send single commands to gison3dmap"""
# show the dialog
self.send_commands_dlg.show()
# Run the dialog event loop
# result = self.dlg.exec_()
# See if OK was pressed
if self.send_commands_dlg.exec_():
command = self.send_commands_dlg.comboBox.currentText()
commands = [command]
tocontroller.send_messages(commands)
def configuration(self):
"""Function to execute configuration dialog"""
# Update dialog values from settings
self.config_dlg.settingsToDialog()
# show the dialog
self.config_dlg.show()
# Run the dialog event loop
result = self.config_dlg.exec_()
# If OK was pressed save dialog values to settings
if result:
self.config_dlg.dialogToSettings()