-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathlftools.py
More file actions
397 lines (338 loc) · 17.7 KB
/
lftools.py
File metadata and controls
397 lines (338 loc) · 17.7 KB
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
# -*- coding: utf-8 -*-
"""
/***************************************************************************
LFTools
A QGIS plugin
Tools for cartographic production and spatial analysis.
Generated by Plugin Builder: http://g-sherman.github.io/Qgis-Plugin-Builder/
-------------------
begin : 2021-03-01
copyright : (C) 2021 by Leandro Franca
email : suporte@geoone.com.br
***************************************************************************/
/***************************************************************************
* *
* 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__ = 'Leandro Franca'
__date__ = '2021-03-01'
__copyright__ = '(C) 2021 by Leandro Franca'
__revision__ = '$Format:%H$'
import os
import sys
import inspect
from qgis.core import (QgsProject,
QgsCoordinateTransform,
QgsApplication,
QgsExpression)
from qgis.PyQt.QtCore import QVariant, QCoreApplication, QSettings, QTranslator, QUrl
from qgis.PyQt.QtGui import QIcon
from qgis.PyQt.QtWidgets import QAction, QMenu, QToolButton, QMessageBox
from .lftools_provider import LFToolsProvider
from .translations.translate import translate
from .geocapt.topogeo import dms2dd as DMS2DD
from .geocapt.cartography import LabelConf, SymbolSimplePoint, prepare_temp_qml
from .geocapt.tools import *
from .expressions import *
from .LFTools_Dialog import ImportXYZ_Dialog
from qgis.utils import iface
import processing
import webbrowser
exprs = (coord2inom, fieldstat, dd2dms, projectCRS, layerCRS, magneticdec, mainAzimuth,
dms2dd, scalefactor, zonehemisf, deedtable, inom2mi, meridianconv, cusum, inter_area,
removespetialchar, deedtable2, deedtable3, areaLTP, deedtext, geoneighbors, gpsdate,
str2html, img2html, dinamictable, perimeterLTP, lengthLTP, areaLTP2, perimeterLTP2,
lengthLTP2, lengthLTP3, layer_schema, azimuth_by_sequence, classify, triangle_area_3d,
azimuth2bearing, bearing2azimuth)
cmd_folder = os.path.split(inspect.getfile(inspect.currentframe()))[0]
if cmd_folder not in sys.path:
sys.path.insert(0, cmd_folder)
class LFToolsPlugin(object):
def __init__(self):
self.iface = iface
self.canvas = iface.mapCanvas()
self.provider = None
self.camada_copiada = None
self.plugin_dir = os.path.dirname(__file__)
self.layerid = ''
self.layerid2 = ''
def tr(self, *string):
return translate(string, QgsApplication.locale()[:2])
def exec_dialog(self, dlg):
try:
return dlg.exec() # PyQt6
except AttributeError:
return dlg.exec_() # PyQt5
def initProcessing(self):
"""Init Processing provider for QGIS >= 3.8."""
self.provider = LFToolsProvider()
QgsApplication.processingRegistry().addProvider(self.provider)
def initGui(self):
self.initProcessing()
for expr in exprs:
if not QgsExpression.isFunctionName(expr.name()):
QgsExpression.registerFunction(expr)
# Iniciar LFTools toolbar
self.toolbar = self.iface.addToolBar('LFTools')
self.toolbar.setObjectName('LFToolsToolbar')
self.toolbar.setToolTip('LFTools')
# Definir SRC
icon = QIcon(self.plugin_dir + '/images/tools/UTM.svg')
self.UTM_Action = QAction(icon, self.tr('Set CRS in UTM', 'Definir SRC em UTM'), self.iface.mainWindow())
self.UTM_Action.setObjectName('DefineUTM')
self.UTM_Action.triggered.connect(self.runUTM)
self.toolbar.addAction(self.UTM_Action)
# Importar X,Y,Z
icon = QIcon(self.plugin_dir + '/images/tools/XYZ.svg')
self.ImportXYZ_Action = QAction(icon, self.tr('Import XYZ', 'Importar XYZ'), self.iface.mainWindow())
self.ImportXYZ_Action.setObjectName('ImportXYZ')
self.ImportXYZ_Action.triggered.connect(self.runImportXYZ)
self.toolbar.addAction(self.ImportXYZ_Action)
# Linhas de Cotagem (Dimensioning)
icon = QIcon(self.plugin_dir + '/images/tools/DIMENSIONING.svg')
self.Dimensioning_Action = QAction(icon, self.tr('Dimensioning', 'Cotagem'), self.iface.mainWindow())
self.Dimensioning_Action.setObjectName('Dimensioning')
self.Dimensioning_Action.triggered.connect(self.runDimensioning)
self.toolbar.addAction(self.Dimensioning_Action)
# Copiar estilo da camada ativa
icon = QIcon(self.plugin_dir + '/images/tools/COPY_STYLE.svg')
self.CopiarEstilo_Action = QAction(icon, self.tr('Copy layer style', 'Copiar estilo da camada'), self.iface.mainWindow())
self.CopiarEstilo_Action.setObjectName('CopyStyle')
self.CopiarEstilo_Action.triggered.connect(self.runCopiarEstilo)
self.toolbar.addAction(self.CopiarEstilo_Action)
# Colar estilo
icon = QIcon(self.plugin_dir + '/images/tools/PASTE_STYLE.svg')
self.ColarEstilo_Action = QAction(icon, self.tr('Paste style to the layer', 'Colar estilo na camada'), self.iface.mainWindow())
self.ColarEstilo_Action.setObjectName('PasteStyle')
self.ColarEstilo_Action.triggered.connect(self.runColarEstilo)
self.toolbar.addAction(self.ColarEstilo_Action)
# DEM Downloader
icon = QIcon(self.plugin_dir + '/images/tools/DEM_DOWNLOADER.svg')
self.DEM_Downloader_Action = QAction(icon, self.tr('DEM Downloader', 'Baixar MDE'), self.iface.mainWindow())
self.DEM_Downloader_Action.setObjectName('DEMDownloader')
self.DEM_Downloader_Action.triggered.connect(self.DEM_Downloader)
self.toolbar.addAction(self.DEM_Downloader_Action)
# Principais ferramentas LFTools (Mão na roda)
menu = QMenu()
menu.setObjectName('MainLFTools')
# Adicionando principais ferramentas
icon = QIcon(self.plugin_dir + '/images/tools/THUMBS_UP.svg')
self.Coord2Layer_Action = menu.addAction(icon, self.tr('Table to point layer', 'Planilha para camada de pontos'), self.Coord2Layer)
self.Coord2Layer_Action.setObjectName('CoordToLayer')
self.GetAttribute_Action = menu.addAction(icon, self.tr('Get attribute by location', 'Pegar atributo pela localização'), self.GetAttribute)
self.GetAttribute_Action.setObjectName('GetAttribute')
self.MeasureLayer_Action = menu.addAction(icon, self.tr('Measure layers', 'Medir camadas'), self.MeasureLayer)
self.MeasureLayer_Action.setObjectName('MeasureLayer')
self.ExportASCII_Action = menu.addAction(icon, self.tr('Export expression as ASCII', 'Exportar expressão como ASCII'), self.ExportASCII)
self.ExportASCII_Action.setObjectName('ExportASCII')
self.SelectByKeyAtt_Action = menu.addAction(icon, self.tr('Select by key attribute', 'Selecionar por atributo chave'), self.SelectByKeyAtt)
self.SelectByKeyAtt_Action.setObjectName('SelectByKeyAtt')
self.MagicStyles_Action = menu.addAction(icon, self.tr('Magic Styles', 'Estilos Mágicos'), self.MagicStyles)
self.MagicStyles_Action.setObjectName('MagicStyles')
# Adicionando conjunto de botões
self.MainLFToolsButton = QToolButton()
self.MainLFToolsButton.setMenu(menu)
self.MainLFToolsButton.setDefaultAction(self.Coord2Layer_Action)
try:
# Qt6
popup_mode = QToolButton.ToolButtonPopupMode.MenuButtonPopup
except AttributeError:
# Qt5
popup_mode = QToolButton.MenuButtonPopup
self.MainLFToolsButton.setPopupMode(popup_mode)
self.MainLFToolsButton.triggered.connect(self.toolButtonTriggered)
self.MainLFToolsToolbar = self.toolbar.addWidget(self.MainLFToolsButton)
self.MainLFToolsToolbar.setObjectName('MainLFToolsToolbar')
# Ajuda do LFTools
icon = QIcon(self.plugin_dir + '/images/tools/GEOONE.svg')
self.Tutoriais_Action = QAction(icon, self.tr('Tutorials', 'Tutoriais'), self.iface.mainWindow())
self.Tutoriais_Action.setObjectName('Tutorials')
self.Tutoriais_Action.triggered.connect(self.runTutoriais)
self.toolbar.addAction(self.Tutoriais_Action)
def unload(self):
QgsApplication.processingRegistry().removeProvider(self.provider)
for expr in exprs:
if QgsExpression.isFunctionName(expr.name()):
QgsExpression.unregisterFunction(expr.name())
# Remove from toolbar
self.iface.removeToolBarIcon(self.UTM_Action)
self.iface.removeToolBarIcon(self.ImportXYZ_Action)
self.iface.removeToolBarIcon(self.Dimensioning_Action)
self.iface.removeToolBarIcon(self.CopiarEstilo_Action)
self.iface.removeToolBarIcon(self.ColarEstilo_Action)
self.iface.removeToolBarIcon(self.DEM_Downloader_Action)
self.iface.removeToolBarIcon(self.Coord2Layer_Action)
self.iface.removeToolBarIcon(self.GetAttribute_Action)
self.iface.removeToolBarIcon(self.MeasureLayer_Action)
self.iface.removeToolBarIcon(self.ExportASCII_Action)
self.iface.removeToolBarIcon(self.SelectByKeyAtt_Action)
self.iface.removeToolBarIcon(self.MagicStyles_Action)
self.iface.removeToolBarIcon(self.Tutoriais_Action)
# remove the toolbar
del self.toolbar
def toolButtonTriggered(self, action):
self.MainLFToolsButton.setDefaultAction(action)
def Coord2Layer(self):
processing.execAlgorithmDialog('lftools:coord2layer', {})
def GetAttribute(self):
processing.execAlgorithmDialog('lftools:getattributebylocation', {})
def MeasureLayer(self):
processing.execAlgorithmDialog('lftools:measure_layers', {})
def ExportASCII(self):
processing.execAlgorithmDialog('lftools:exportascii', {})
def SelectByKeyAtt(self):
processing.execAlgorithmDialog('lftools:selectbykeyatt', {})
def DEM_Downloader(self):
processing.execAlgorithmDialog('lftools:demdownloader', {})
def MagicStyles(self):
processing.execAlgorithmDialog('lftools:magicstyles', {})
def runUTM(self):
DefinirUTM(self.iface)
def runCopiarEstilo(self):
self.camada_copiada = copiar_estilo_camada_ativa(self.iface)
def runColarEstilo(self):
colar_estilo_em_camada_destino(self.iface, self.camada_copiada)
def runTutoriais(self):
webbrowser.open_new('https://www.youtube.com/@geoleandrofranca')
def runImportXYZ(self):
# Criar caixa de diálogo
dlg = ImportXYZ_Dialog()
# Mostrar caixa de diálogo
dlg.adjustSize()
dlg.show()
result = self.exec_dialog(dlg)
projeto = QgsProject.instance()
# Quando pressionado
if result == 1:
try:
coordX = dlg.coordX.text().replace(',', '.').strip()
coordY = dlg.coordY.text().replace(',', '.').strip()
coordZ = dlg.coordZ.text().replace(',', '.').strip()
crs = dlg.CRS.crs()
nome = dlg.Name.text()
nome_campo = self.tr('name', 'nome')
# Verificando SRC
if not crs.isValid():
raise ValueError(self.tr('Invalid CRS selected!', 'SRC inválido selecionado!'))
# Identificação e validação dos dados de entrada
if crs.isGeographic():
X = DMS2DD(coordX)
if X is None:
try:
X = float(coordX)
except:
raise ValueError(self.tr('Invalid X/longitude coordinate: {}', 'Coordenada X/longitude inválida: {}').format(coordX))
Y = DMS2DD(coordY)
if Y is None:
try:
Y = float(coordY)
except:
raise ValueError(self.tr('Invalid Y/latitude coordinate: {}', 'Coordenada Y/latitude inválida: {}').format(coordY))
else: # Coordenadas projetadas
try:
X = float(coordX)
except:
raise ValueError(self.tr('Invalid X coordinate: {}', 'Coordenada X inválida: {}').format(coordX))
try:
Y = float(coordY)
except:
raise ValueError(self.tr('Invalid Y coordinate: {}', 'Coordenada Y inválida: {}').format(coordY))
try:
Z = 0 if coordZ == '' else float(coordZ)
except:
raise ValueError(self.tr('Invalid Z coordinate: {}', 'Coordenada Z inválida: {}').format(coordZ))
# Criando camada pela primeira vez
if not projeto.mapLayer(self.layerid):
self.layer = QgsVectorLayer("PointZ?crs=" + crs.authid(), self.tr('Points XYZ', 'Pontos XYZ'), "memory")
self.DP = self.layer.dataProvider()
crs0 = crs
# adicionar campos
campos = [QgsField(nome_campo, QVariant.String),
QgsField('X', QVariant.String),
QgsField('Y', QVariant.String),
QgsField('Z', QVariant.String),
QgsField('CRS', QVariant.String)]
self.DP.addAttributes(campos)
self.layer.updateFields()
# Estilizar camada
labeling = LabelConf(nome_campo)
self.layer.setLabeling(labeling)
self.layer.setLabelsEnabled(True)
self.layer.triggerRepaint()
renderer = SymbolSimplePoint(self.layer)
self.layer.setRenderer(renderer)
self.layer.triggerRepaint()
# Adicionar camada
projeto.addMapLayer(self.layer)
# Armazenar id da camada
self.layerid = self.layer.id()
else:
crs0 = self.layer.crs()
# Adicionar feição
fields = self.layer.fields()
feat = QgsFeature(fields)
feat[nome_campo] = nome
feat['X'] = str(coordX)
feat['Y'] = str(coordY)
feat['Z'] = str(coordZ)
feat['CRS'] = str(crs.description())
geom = QgsGeometry(QgsPoint(X, Y, Z))
if crs0 != crs: # Transformar SRC, se necessário
coordinateTransformer = QgsCoordinateTransform()
coordinateTransformer.setDestinationCrs(crs0)
coordinateTransformer.setSourceCrs(crs)
geom.transform(coordinateTransformer)
feat.setGeometry(geom)
self.layer.startEditing()
self.layer.addFeatures([ feat ])
self.layer.commitChanges()
self.layer.triggerRepaint()
project_crs = QgsProject.instance().crs()
pt = QgsPointXY(X, Y) # no CRS de entrada (crs)
if crs != project_crs:
ct = QgsCoordinateTransform(crs, project_crs, QgsProject.instance())
pt = ct.transform(pt)
self.canvas.setCenter(pt)
self.canvas.refresh()
except Exception as e:
QMessageBox.information(self.iface.mainWindow(), QCoreApplication.translate('LFTools', "LFTools plugin error"), QCoreApplication.translate('LFTools', "There was an error with the input parameter:<br><strong>{}</strong>".format(e)))
return
def runDimensioning(self):
self.iface.messageBar().pushMessage(self.tr('Use snapping, if possible.', 'Use a Aderência, se possível.'), level=Qgis.Info, duration=10)
projeto = QgsProject.instance()
crs = projeto.crs()
# Criando camada pela primeira vez
if not projeto.mapLayer(self.layerid2):
#criar camada
layer = QgsVectorLayer("LineStringZ?crs=" + crs.authid(), self.tr('Dimensioning', 'Cotagem'), "memory")
self.layerid2 = layer.id()
# Adicionar estilos
estilo = os.path.join(os.path.dirname(os.path.dirname(__file__)), 'lftools/styles/cotagem_prof_leandro.qml' )
expr = '$length' if crs.isGeographic() else 'length($geometry)'
estilo = prepare_temp_qml(estilo, ['[EXPRESSION]'], [ expr ] )
layer.loadNamedStyle(estilo)
# Adicionar camada
projeto.addMapLayer(layer)
# Obter o nó da camada
layer_tree = projeto.layerTreeRoot()
layer_node = layer_tree.findLayer(layer.id())
if layer_node:
# Clonar e mover para o topo
parent = layer_node.parent()
clone_node = layer_node.clone()
layer_tree.insertChildNode(0, clone_node)
parent.removeChildNode(layer_node)
else:
layer = projeto.mapLayer(self.layerid2)
# Ativar camada
self.iface.setActiveLayer(layer)
# colocar no modo edição
layer.startEditing()
# habilitar ferramenta de vetorização
self.iface.actionAddFeature().trigger()
return