-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathcoordinator.py
More file actions
574 lines (450 loc) · 22.4 KB
/
coordinator.py
File metadata and controls
574 lines (450 loc) · 22.4 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
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
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
# -*- coding: utf-8 -*-
"""
/***************************************************************************
Yacub
A QGIS plugin
makes coordinate discovery and editing easier
Generated by Plugin Builder: http://g-sherman.github.io/Qgis-Plugin-Builder/
-------------------
begin : 2019-05-04
git sha : $Format:%H$
copyright : (C) 2019 by Jonas Küpper
email : qgis@ag99.de
***************************************************************************/
/***************************************************************************
* *
* 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. *
* *
***************************************************************************/
"""
from functools import partial
import os.path
from PyQt5.Qt import Qt, QSettings, QTranslator, qVersion, QApplication, QCoreApplication, QIcon, QColor,\
QMouseEvent, QEvent, QLocale
from PyQt5.QtWidgets import QAction, QMainWindow
from PyQt5 import QtCore
from qgis.gui import QgsProjectionSelectionDialog, QgsVertexMarker, QgsMapToolEmitPoint, QgsMapTool, \
QgsMapToolCapture, QgsMapMouseEvent, QgsMapToolCapture
from qgis.core import QgsProject, QgsMessageLog, QgsCoordinateReferenceSystem, QgsCoordinateTransform, \
QgsPointXY, QgsGeometry, QgsVectorLayer, QgsRasterLayer, QgsVectorLayerUtils
from qgis.PyQt import sip
from .coordinator_dockwidget import CoordinatorDockWidget
from .resources import *
from .funcs import coordinatorLog, CoordinatorTranslator as CT
class Coordinator():
"""YACUP plugin"""
def __init__(self, iface, mainWindow = None):
"""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
"""
# store references to important stuff from QGIS
self.iface = iface
self.canvas = iface.mapCanvas()
self._project = QgsProject.instance()
self._observingLayer = None
self._uiHook = mainWindow if isinstance(mainWindow, QMainWindow) else iface
# region: LOCALE - UNUSED
# initialize plugin directory
self.plugin_dir = os.path.dirname(__file__)
#
#initialize locale
localeString = QSettings().value('locale/userLocale')
if(localeString):
locale = localeString[0:2]
else:
locale = QLocale().language()
locale_path = os.path.join(
self.plugin_dir,
'i18n',
'coordinator_{}.qm'.format(locale))
if os.path.exists(locale_path):
self.translator = QTranslator()
self.translator.load(locale_path)
QCoreApplication.installTranslator(self.translator)
# endregion
# plugin housekeeping:
self.openPanelAction = None
self.pluginIsActive = False
self.dockwidget = None
# Init CRS Transformation:
self._inputCrs = None
self._outputCrs = None
# self._transform : input -> output transformation
# self._canvasTransform: input -> canvas transformation
self.__initTransformers()
# initialize canvas marker icon:
self.marker = QgsVertexMarker(self.canvas)
self.marker.hide()
self.marker.setColor(QColor(255, 0, 0))
self.marker.setIconSize(14)
self.marker.setIconType(QgsVertexMarker.ICON_CIRCLE) # See the enum IconType from http://www.qgis.org/api/classQgsVertexMarker.html
self.marker.setPenWidth(3)
# init point picker:
self.mapTool = QgsMapToolEmitPoint(self.canvas)
# LIFECYCLE :
def initGui(self):
"""Create the menu entry inside the QGIS GUI."""
icon = QIcon(':/plugins/coordinator/icons/marker.svg')
menuTitle = CT.tr("Open Coordinator")
self.openPanelAction = QAction(icon, menuTitle)
self.openPanelAction.triggered.connect(self.run)
self.iface.pluginMenu().addAction( self.openPanelAction )
#--------------------------------------------------------------------------
def onClosePlugin(self):
"""Cleanup necessary items here when plugin dockwidget is closed"""
# remove the marker from the canvas:
self.marker.hide()
self.dockwidget.closingPlugin.disconnect(self.onClosePlugin)
# disconnect from the GUI-signals
self._disconnectExternalSignals()
self.pluginIsActive = False
def unload(self):
"""Removes the plugin menu item from QGIS GUI."""
self.iface.pluginMenu().removeAction( self.openPanelAction )
self.marker.hide()
self._disconnectExternalSignals()
#--------------------------------------------------------------------------
# PRIVATE HELPERS:
def __initTransformers(self):
"""Initializes both coordinate transform object needed: the transformation from the
input CRS to the output CRS (self._transform) and a tranformer from the input CRS to
the current canvas CRS."""
inputCrs = self._inputCrs if self._inputCrs != None else QgsCoordinateReferenceSystem("EPSG:4326")
outputCrs = self._outputCrs if self._outputCrs != None else QgsCoordinateReferenceSystem("EPSG:4326")
self._transform = QgsCoordinateTransform(
inputCrs,
outputCrs,
self._project)
canvasCrs = self.canvas.mapSettings().destinationCrs()
# coordinatorLog("init canvas transform with %s -> %s"
# % (inputCrs.authid(), canvasCrs.authid() if canvasCrs else "NONE!!")
# )
self._canvasTransform = QgsCoordinateTransform(
inputCrs,
canvasCrs,
self._project)
def __checkEnableAddFeatureButton(self):
shouldEnable = bool(self.dockwidget.hasInput() and self.__compatibleMapTool())
return shouldEnable
def __compatibleMapTool(self):
newTool = self.canvas.mapTool()
if( newTool != None and (newTool.flags() & QgsMapTool.EditTool) ) :
newTool = sip.cast(newTool, QgsMapToolCapture)
# pre-check probably fixing issue #3 regarding Enums with Qt >= 5.11:
# --> https://www.riverbankcomputing.com/static/Docs/PyQt5/gotchas.html#enums
try:
validModes = (
QgsMapToolCapture.CaptureMode.CapturePoint,
QgsMapToolCapture.CaptureMode.CapturePolygon,
QgsMapToolCapture.CaptureMode.CaptureLine
)
except AttributeError:
validModes = (
QgsMapToolCapture.CapturePoint,
QgsMapToolCapture.CapturePolygon,
QgsMapToolCapture.CaptureLine
)
if newTool.mode() in validModes:
return newTool
return False
def _disconnectExternalSignals(self):
try: self.iface.mapCanvas().destinationCrsChanged.disconnect(self.mapCanvasCrsChanged)
except TypeError: pass
try: self.canvas.mapToolSet.disconnect(self.mapToolChanged)
except TypeError: pass
try: self.iface.currentLayerChanged.disconnect(self.currentLayerChanged)
except TypeError: pass
try: self.iface.projectRead.disconnect(self.projectRead)
except TypeError: pass
if (self._observingLayer != None) and sip.isdeleted(self._observingLayer):
self._observingLayer = None
if self._observingLayer:
try: self._observingLayer.crsChanged.disconnect(self.layerChangedCrs)
except TypeError: pass
def _currentEffectiveCrsInMap(self):
activeLayer = self.iface.activeLayer()
if(activeLayer):
if type(activeLayer) == QgsVectorLayer:
return activeLayer.sourceCrs()
elif type(activeLayer) == QgsRasterLayer:
return activeLayer.crs()
else:
return self.canvas.mapSettings().destinationCrs()
def _warnIfPointOutsideCanvas(self):
if(self.dockwidget.hasInput() and not self.canvas.extent().contains(self.inputCoordinatesInCanvasCrs())):
self.setWarningMessage(CT.tr("outside of map extent"))
else:
self.setWarningMessage(None)
#--------------------------------------------------------------------------
# GETTERS/SETTERS
def setInputCrs(self, crs):
oldCrs = self._inputCrs
if (oldCrs == None) or ( crs.authid() != oldCrs.authid() ) :
#coordinatorLog("setting input CRS to %s" % crs.authid())
currentCoordinates = self.dockwidget.inputCoordinates()
self._inputCrs = crs
self.dockwidget.setSectionCrs(CoordinatorDockWidget.SectionInput, crs)
self._transform.setSourceCrs(crs)
self._canvasTransform.setSourceCrs(crs)
if(oldCrs != None and self.dockwidget.hasInput()):
# make sure we transform the currently set coordinate
# to the new Coordinate System :
t = QgsCoordinateTransform(oldCrs, crs, QgsProject.instance())
transformedPoint = t.transform(QgsPointXY(currentCoordinates[0], currentCoordinates[1]))
self.dockwidget.setInputPoint(transformedPoint)
else:
self.dockwidget.clearSection(CoordinatorDockWidget.SectionBoth)
def inputCrs(self) :
return self._inputCrs
def setOutputCrs(self, crs):
#coordinatorLog("changing output CRS %s -> %s" % (self._outputCrs.authid() if self._outputCrs else "NONE!", crs.authid()) )
oldCrs = self._outputCrs
if ( oldCrs == None ) or (oldCrs.authid() != crs.authid()) :
self._outputCrs = crs
self.dockwidget.setSectionCrs(CoordinatorDockWidget.SectionOutput, crs)
self._transform.setDestinationCrs(crs)
self.process()
def outputCrs(self):
return self._outputCrs
def setWarningMessage(self, message):
self.dockwidget.setWarningMessage(message)
# ACTIONS :
def openCrsSelectionDialogForSection(self, section):
projSelector = QgsProjectionSelectionDialog()
if(projSelector.exec()):
selectedCrs = projSelector.crs()
# workaround for checking if there was no CRS selected
# but user clicked 'OK': check if authid-string is empty:
if not selectedCrs.authid() :
return
if section == CoordinatorDockWidget.SectionInput:
self.setInputCrs(selectedCrs)
elif section == CoordinatorDockWidget.SectionOutput:
self.setOutputCrs(selectedCrs)
def setOutputCrsToCanvasCrs(self):
crs = self.canvas.mapSettings().destinationCrs()
self.setOutputCrs(crs)
def connectCrsToCanvas(self, section, connect) :
#coordinatorLog("%s %s" % (section, connect))
if section == CoordinatorDockWidget.SectionOutput:
if(connect): # connect to map
# disable dialog for selecting output CRS:
self.dockwidget.outputCrs.clicked.disconnect()
# set CRS to be canvas' CRS and follow it
self.setOutputCrsToCanvasCrs()
else:
# enable dialog selection
self.dockwidget.outputCrs.clicked.connect(partial(self.openCrsSelectionDialogForSection, CoordinatorDockWidget.SectionOutput))
def addCurrentCoordinatesToDigitizeSession(self):
editTool = self.__compatibleMapTool()
if(not editTool):
return False
result = False
point = self.inputCoordinatesInCanvasCrs()
if( editTool.mode() == QgsMapToolCapture.CaptureMode.CapturePoint):
#coordinatorLog("Point Capture!")
layer = self.iface.activeLayer()
# if canvas CRS is not layer CRS we need to transform first:
transform = QgsCoordinateTransform(
self.canvas.mapSettings().destinationCrs(),
layer.sourceCrs(),
self._project)
point = transform.transform(point, QgsCoordinateTransform.ForwardTransform)
geometry = QgsGeometry.fromPointXY(point)
feature = QgsVectorLayerUtils.createFeature(layer, geometry, {}, layer.createExpressionContext() )
if( (len(layer.fields()) < 1) or self.iface.openFeatureForm(layer, feature)):
result = layer.addFeature(feature)
if(result):
#coordinatorLog("Point successfully written to layer")
pass
layer.triggerRepaint()
elif (
(editTool.mode() == QgsMapToolCapture.CaptureMode.CapturePolygon)
or (editTool.mode() == QgsMapToolCapture.CaptureMode.CaptureLine)
):
#coordinatorLog("Rubberband Capture!")
result = (editTool.addVertex(point) == 0)
else:
return False
if(result):
self.dockwidget.showInfoMessage(CT.tr("coordinate added"),1500)
else:
self.setWarningMessage(CT.tr("adding coordinate failed"))
return result
def switchInputOutputCrs(self):
inputCrs = self._inputCrs
self.setInputCrs(self._outputCrs)
self.setOutputCrs(inputCrs)
if self.dockwidget.outputCrsConn.isChecked() and (self._outputCrs.authid() != self._inputCrs.authid()) :
self.dockwidget.outputCrsConn.setChecked(False)
def _showMarker(self, show):
if show and self.dockwidget.hasInput():
self.marker.show()
else:
self.marker.hide()
# API :
def enableMarker(self, show):
self._showMarker(show)
self.dockwidget.showMarker.setChecked(show)
# PIPELINE :
def ensureValidInputGui(self):
self.dockwidget.addFeatureButton.setEnabled(self.__checkEnableAddFeatureButton())
self._warnIfPointOutsideCanvas()
# make sure we show the marker now:
if self.dockwidget.hasInput():
if self.dockwidget.showMarker.isChecked():
self.marker.show()
else:
self.marker.hide()
self.dockwidget.setInputToDMS(
self.dockwidget.inputAsDMS.isChecked()
& self._inputCrs.isGeographic()
)
def process(self):
#coordinatorLog("about to process input")
if(self.dockwidget.hasInput()):
(x, y) = self.dockwidget.inputCoordinates()
# coordinatorLog("Input: %f %f " % (x, y) )
transformedPoint = self._transform.transform(QgsPointXY(x, y))
# coordinatorLog("Transformed point: %f %f " % (transformedPoint.x(), transformedPoint.y()) )
self.dockwidget.setResultPoint(transformedPoint)
self.marker.setCenter(self.inputCoordinatesInCanvasCrs())
else:
self.dockwidget.clearFieldsInSection(CoordinatorDockWidget.SectionOutput)
def reset(self):
self.__initTransformers()
self.dockwidget.resetInterface()
self.dockwidget.setEastingInverted(False)
self.dockwidget.setNorthingInverted(False)
def inputCoordinatesInCanvasCrs(self):
(x, y) = self.dockwidget.inputCoordinates()
result = self._canvasTransform.transform(QgsPointXY(x, y))
#coordinatorLog("transformation: (%s,%s) are (%s,%s)" % (x,y, result.x(), result.y()))
#coordinatorLog(" %s -> %s" % (self._canvasTransform.sourceCrs().authid(), self._canvasTransform.destinationCrs().authid()) )
return result
# SLOTS :
def mapCanvasCrsChanged(self):
self._canvasTransform.setDestinationCrs(self.canvas.mapSettings().destinationCrs())
#if(self.dockwidget.outputCrsConn.isChecked()):
# self.setOutputCrs(self.canvas.mapSettings().destinationCrs())
def inputCoordinatesChanged(self):
#Coordinator.log("Input changed")
self.process()
self.ensureValidInputGui()
def inputFormatChanged(self):
self.ensureValidInputGui()
def outputFormatChanged(self):
self.process()
def moveCanvasButtonClicked(self):
self.canvas.setCenter(self.inputCoordinatesInCanvasCrs())
def mapCrsConnectionButtonToggled(self, forSection, enabled):
self.connectCrsToCanvas(forSection, enabled)
def showMarkerButtonToggled(self, show):
self._showMarker(show)
def captureCoordsButtonToggled(self, enabled):
#coordinatorLog( "enable Capture Coords: %s" % enabled)
if(enabled):
self.canvas.setMapTool(self.mapTool)
self.mapTool.canvasClicked.connect(self.canvasClickedWithPicker)
else:
try:
self.mapTool.canvasClicked.disconnect(self.canvasClickedWithPicker)
except TypeError:
pass
self.canvas.unsetMapTool(self.mapTool)
def canvasClickedWithPicker(self, point, button):
# button is the MouseButton
#coordinatorLog(type(button).__name__)
if QApplication.keyboardModifiers() and Qt.ControlModifier:
self.setInputCrs(self.canvas.mapSettings().destinationCrs())
# coordinatorLog("Current Canvas Transform is %s -> %s (we do the reverse to get input)"
# % (self._canvasTransform.sourceCrs().authid(), self._canvasTransform.destinationCrs().authid())
# )
point = self._canvasTransform.transform(point, QgsCoordinateTransform.ReverseTransform)
self.dockwidget.setInputPoint(point)
def canvasMoved(self):
self._warnIfPointOutsideCanvas()
def mapToolChanged(self):
#coordinatorLog("map tools changed")
#coordinatorLog( type( self.canvas.mapTool() ).__name__ )
currentMapTool = self.canvas.mapTool()
if(currentMapTool == self.mapTool):
# user selected our coordinate capture tool -> do nothing
pass
elif( self.__checkEnableAddFeatureButton() ):
# user selected a tool to modify features -> enable our add feature button
self.dockwidget.addFeatureButton.setEnabled(True)
self.dockwidget.captureCoordButton.setChecked(False)
else:
# user selected a totally unrelated tool -> make sure our coordinate capture tool is disabled
self.dockwidget.captureCoordButton.setChecked(False)
self.dockwidget.addFeatureButton.setEnabled(False)
def addFeatureClicked(self):
self.addCurrentCoordinatesToDigitizeSession()
def projectRead(self):
#coordinatorLog("new project")
self._project = QgsProject.instance()
self.reset()
def currentLayerChanged(self, layer):
if self._observingLayer:
self._observingLayer.crsChanged.disconnect(self.layerChangedCrs)
if layer:
self._observingLayer = layer
self._observingLayer.crsChanged.connect(self.layerChangedCrs)
#coordinatorLog("%s" % type(layer).__name__)
if self.dockwidget.outputCrsConn.isChecked():
self.setOutputCrs(self._currentEffectiveCrsInMap())
def layerChangedCrs(self):
#coordinatorLog("%s" % type(layer).__name__)
if self.dockwidget.outputCrsConn.isChecked():
self.setOutputCrs(self._currentEffectiveCrsInMap())
def run(self):
"""Run method that loads and starts the plugin"""
#coordinatorLog("run", "Coordinator")
if not self.pluginIsActive:
self.pluginIsActive = True
#QgsMessageLog.logMessage("Starting", "Coordinator")
# dockwidget may not exist if:
# first run of plugin
# removed on close (see self.onClosePlugin method)
if self.dockwidget == None:
# Create the dockwidget (after translation) and keep reference
self.dockwidget = CoordinatorDockWidget()
#for child in self.dockwidget.children():
# self.log("Child: %s" % child.objectName())
# MA LOGIC:
# EXTERNAL connections
self.canvas.destinationCrsChanged.connect(self.mapCanvasCrsChanged)
self.canvas.mapToolSet.connect(self.mapToolChanged)
self.canvas.extentsChanged.connect(self.canvasMoved)
self.iface.projectRead.connect(self.projectRead)
self.iface.currentLayerChanged.connect(self.currentLayerChanged)
# CONNECT the initially active buttons from the GUI:
self.dockwidget.selectCrsButton.clicked.connect(partial(self.openCrsSelectionDialogForSection, CoordinatorDockWidget.SectionInput) )
self.dockwidget.mapConnectionChanged.connect(self.mapCrsConnectionButtonToggled)
# set the inital CRS:
self.setInputCrs(QgsCoordinateReferenceSystem("EPSG:4326"))
self.setOutputCrs(self.canvas.mapSettings().destinationCrs())
# connect the marker button :
self.dockwidget.showMarker.clicked.connect(self.showMarkerButtonToggled)
self.dockwidget.moveCanvas.clicked.connect(self.moveCanvasButtonClicked)
self.dockwidget.captureCoordButton.clicked.connect(self.captureCoordsButtonToggled)
self.dockwidget.addFeatureButton.clicked.connect(self.addFeatureClicked)
self.dockwidget.inputFormatButtonGroup.buttonClicked.connect(self.inputFormatChanged)
self.dockwidget.resultFormatButtonGroup.buttonClicked.connect(self.outputFormatChanged)
self.dockwidget.inputChanged.connect(self.inputCoordinatesChanged)
# connect to provide cleanup on closing of dockwidget
self.dockwidget.closingPlugin.connect(self.onClosePlugin)
# SETUP:
self.enableMarker(True)
self._canvasTransform.setDestinationCrs(self.canvas.mapSettings().destinationCrs())
# show the dockwidget
# TODO: fix to allow choice of dock location
self._uiHook.addDockWidget(Qt.LeftDockWidgetArea, self.dockwidget)
self.dockwidget.show()