-
Notifications
You must be signed in to change notification settings - Fork 7
/
lftools.py
277 lines (235 loc) · 12 KB
/
lftools.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
# -*- 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 : geoleandro.franca@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. *
* *
***************************************************************************/
"""
__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 (QgsProcessingAlgorithm,
QgsProject,
QgsApplication,
QgsExpression)
from qgis.PyQt.QtCore import QVariant
from PyQt5.QtCore import QCoreApplication
from PyQt5.QtWidgets import QMessageBox
from .lftools_provider import LFToolsProvider
from .translations.translate import translate
from lftools.geocapt.topogeo import dms2dd as DMS2DD
from .geocapt.tools import *
from .expressions import *
from .LFTools_Dialog import ImportXYZ_Dialog
from qgis.PyQt.QtCore import QUrl, QCoreApplication, QSettings, QTranslator
from qgis.PyQt.QtGui import QIcon
from qgis.PyQt.QtWidgets import QAction, QMenu, QToolButton
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)
cmd_folder = os.path.split(inspect.getfile(inspect.currentframe()))[0]
if cmd_folder not in sys.path:
sys.path.insert(0, cmd_folder)
LOC = QgsApplication.locale()[:2]
def tr(*string):
return translate(string, LOC)
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 = ''
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, 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, 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)
# Copiar estilo da camada ativa
icon = QIcon(self.plugin_dir + '/images/tools/COPY_STYLE.svg')
self.CopiarEstilo_Action = QAction(icon, tr('Copy layer style', 'Copiar estilo da camada'), self.iface.mainWindow())
self.CopiarEstilo_Action.setObjectName('ImportXYZ')
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, tr('Paste style to the layer', 'Colar estilo na camada'), self.iface.mainWindow())
self.ColarEstilo_Action.setObjectName('ImportXYZ')
self.ColarEstilo_Action.triggered.connect(self.runColarEstilo)
self.toolbar.addAction(self.ColarEstilo_Action)
# Principais ferramentas LFTools (Mão na roda)
menu = QMenu()
menu.setObjectName('MainLFTools')
# Adicionando principais ferramentas
icon = QIcon(self.plugin_dir + '/images/easy.png')
self.Coord2Layer_Action = menu.addAction(icon, tr('Table to point layer', 'Planilha para camada de pontos'), self.Coord2Layer)
self.Coord2Layer_Action.setObjectName('CoordToLayer')
icon = QIcon(self.plugin_dir + '/images/easy.png')
self.GetAttribute_Action = menu.addAction(icon, tr('Get attribute by location', 'Pegar atributo pela localização'), self.GetAttribute)
self.GetAttribute_Action.setObjectName('GetAttribute')
icon = QIcon(self.plugin_dir + '/images/easy.png')
self.MeasureLayer_Action = menu.addAction(icon, tr('Measure layers', 'Medir camadas'), self.MeasureLayer)
self.MeasureLayer_Action.setObjectName('MeasureLayer')
icon = QIcon(self.plugin_dir + '/images/easy.png')
self.ExportASCII_Action = menu.addAction(icon, tr('Export expression as ASCII', 'Exportar expressão como ASCII'), self.ExportASCII)
self.ExportASCII_Action.setObjectName('ExportASCII')
# Adicionando conjunto de botões
self.MainLFToolsButton = QToolButton()
self.MainLFToolsButton.setMenu(menu)
self.MainLFToolsButton.setDefaultAction(self.Coord2Layer_Action)
self.MainLFToolsButton.setPopupMode(QToolButton.MenuButtonPopup)
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, 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.CopiarEstilo_Action)
self.iface.removeToolBarIcon(self.ColarEstilo_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.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 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 = dlg.exec_()
projeto = QgsProject.instance()
# Quando pressionado
if result == 1:
try:
coordX = dlg.coordX.text().replace(',', '.')
coordY = dlg.coordY.text().replace(',', '.')
coordZ = dlg.coordZ.text().replace(',', '.')
crs = dlg.CRS.crs()
nome = dlg.Name.text()
nome_campo = tr('name', 'nome')
# Identificação e validação dos dados de entrada
if crs.isGeographic():
# GMS para graus decimais
X = DMS2DD(coordX)
Y = DMS2DD(coordY)
else:
X = float(coordX)
Y = float(coordY)
Z = 0 if coordZ == '' else float(coordZ)
# Criando camada pela primeira vez
if not projeto.mapLayer(self.layerid):
self.layer = QgsVectorLayer("PointZ?crs=" + crs.authid(), tr('Points XYZ', 'Pontos XYZ'), "memory")
self.DP = self.layer.dataProvider()
# adicionar campos
campos = [QgsField(nome_campo, QVariant.String),
QgsField('X', QVariant.String),
QgsField('Y', QVariant.String),
QgsField('Z', QVariant.String)]
self.DP.addAttributes(campos)
self.layer.updateFields()
# Rotular pelo nome
try:
layer_settings = QgsPalLayerSettings()
layer_settings.fieldName = nome_campo
self.layer.setLabeling(QgsVectorLayerSimpleLabeling(layer_settings))
self.layer.setLabelsEnabled(True)
except:
self.layer.setCustomProperty("labeling", "pal")
self.layer.setCustomProperty("labeling/enabled", "true")
self.layer.setCustomProperty("labeling/fieldName", nome_campo)
# Adicionar camada
projeto.addMapLayer(self.layer)
# Armazenar id da camada
self.layerid = self.layer.id()
# 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)
geom = QgsGeometry(QgsPoint(X, Y, Z))
feat.setGeometry(geom)
self.layer.startEditing()
self.layer.addFeatures([ feat ])
self.layer.commitChanges()
self.canvas.setCenter(QgsPointXY(X, Y))
except Exception as e:
QMessageBox.information(self.iface.mainWindow(), QCoreApplication.translate('LFTools', "LFTools plugin error"), QCoreApplication.translate('LFTools', tr("There was an error with the input parameter:<br><strong>{}</strong>").format(e)))
return