generated from teksi/template
-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathtwwmaptooladdfeature.py
514 lines (448 loc) · 18.3 KB
/
twwmaptooladdfeature.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
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
# -----------------------------------------------------------
#
# TEKSI Wastewater
#
# Copyright (C) 2014 Matthias Kuhn
# -----------------------------------------------------------
#
# licensed under the terms of GNU GPL 2
#
# 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.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, print to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
# ---------------------------------------------------------------------
"""
Some map tools for digitizing features
"""
import math
from qgis.core import (
NULL,
Qgis,
QgsFeature,
QgsFeatureRequest,
QgsGeometry,
QgsPoint,
QgsPointXY,
QgsSettings,
QgsSnappingConfig,
QgsTolerance,
QgsWkbTypes,
)
from qgis.gui import (
QgisInterface,
QgsAttributeEditorContext,
QgsMapCanvas,
QgsMapCanvasSnappingUtils,
QgsMapTool,
QgsMapToolAdvancedDigitizing,
QgsMessageBar,
QgsRubberBand,
QgsVertexMarker,
)
from qgis.PyQt.QtCore import Qt, pyqtSignal
from qgis.PyQt.QtGui import QColor, QCursor
from qgis.PyQt.QtWidgets import (
QApplication,
QDialog,
QDialogButtonBox,
QGridLayout,
QLabel,
QLineEdit,
)
from ..utils.twwlayermanager import TwwLayerManager
class TwwRubberBand3D(QgsRubberBand):
def __init__(self, map_canvas: QgsMapCanvas, geometry_type):
QgsRubberBand.__init__(self, map_canvas, geometry_type)
self.points = []
def addPoint3D(self, point):
assert isinstance(point, QgsPoint)
QgsRubberBand.addPoint(self, QgsPointXY(point.x(), point.y()))
# Workaround crash with QGIS 3.10.2 (https://github.com/qgis/QGIS/issues/34557)
new_point = QgsPoint(point.x(), point.y(), point.z(), point.m(), point.wkbType())
self.points.append(new_point)
def reset3D(self):
QgsRubberBand.reset(self)
self.points = []
def asGeometry3D(self):
def ensure_z(z):
if math.isnan(z):
return QgsSettings().value(
"/qgis/digitizing/default_z_value", Qgis.DEFAULT_Z_COORDINATE
)
return z
wkt = (
"LineStringZ("
+ ", ".join([f"{p.x()} {p.y()} {ensure_z(p.z())}" for p in self.points])
+ ")"
)
return QgsGeometry.fromWkt(wkt)
class TwwMapToolAddFeature(QgsMapToolAdvancedDigitizing):
"""
Base class for adding features
"""
def __init__(self, iface: QgisInterface, layer):
QgsMapToolAdvancedDigitizing.__init__(self, iface.mapCanvas(), iface.cadDockWidget())
self.iface = iface
self.canvas = iface.mapCanvas()
self.layer = layer
self.rubberband = TwwRubberBand3D(iface.mapCanvas(), layer.geometryType())
self.rubberband.setColor(QColor("#ee5555"))
self.rubberband.setWidth(1)
self.temp_rubberband = QgsRubberBand(iface.mapCanvas(), layer.geometryType())
self.temp_rubberband.setColor(QColor("#ee5555"))
self.temp_rubberband.setWidth(1)
self.temp_rubberband.setLineStyle(Qt.DotLine)
def activate(self):
"""
When activating the map tool
"""
QgsMapToolAdvancedDigitizing.activate(self)
self.canvas.setCursor(QCursor(Qt.CrossCursor))
def deactivate(self):
"""
On deactivating the map tool
"""
QgsMapToolAdvancedDigitizing.deactivate(self)
self.canvas.unsetCursor()
# pylint: disable=no-self-use
def isZoomTool(self):
"""
This is no zoom tool
"""
return False
# ===========================================================================
# Events
# ===========================================================================
def cadCanvasReleaseEvent(self, event):
"""
Called when a mouse button is
:param event:
:return:
"""
if event.button() == Qt.RightButton:
self.right_clicked(event)
else:
self.left_clicked(event)
def left_clicked(self, event):
"""
When the canvas is left clicked we add a new point to the rubberband.
:type event: QMouseEvent
"""
mousepos = self.canvas.getCoordinateTransform().toMapCoordinates(
event.pos().x(), event.pos().y()
)
self.rubberband.addPoint(mousepos)
self.temp_rubberband.reset()
def right_clicked(self, _):
"""
On a right click we create a new feature from the existing rubberband and show the add
dialog
"""
f = QgsFeature(self.layer.fields())
f.setGeometry(self.rubberband.asGeometry())
dlg = self.iface.getFeatureForm(self.layer, f)
dlg.setMode(QgsAttributeEditorContext.AddFeatureMode)
dlg.exec_()
self.rubberband.reset3D()
self.temp_rubberband.reset()
def cadCanvasMoveEvent(self, event):
"""
When the mouse is moved the rubberband needs to be updated
:param event: The coordinates etc.
"""
# When a generated event arrives it's a QMoveEvent... No idea why, but this prevents from an exception
try:
QgsMapToolAdvancedDigitizing.cadCanvasMoveEvent(self, event)
mousepos = event.mapPoint()
self.temp_rubberband.movePoint(mousepos)
self.mouse_move(event)
except TypeError:
pass
def mouse_move(self, event):
pass
class TwwMapToolAddReach(TwwMapToolAddFeature):
"""
Create a new reach with the mouse.
Will snap to wastewater nodes for the first and last point and auto-connect
these.
"""
first_snapping_match = None
last_snapping_match = None
last_feature_attributes = None
def __init__(self, iface: QgisInterface, layer):
TwwMapToolAddFeature.__init__(self, iface, layer)
self.snapping_marker = None
self.node_layer = TwwLayerManager.layer("vw_wastewater_node")
assert self.node_layer is not None
self.reach_layer = TwwLayerManager.layer("vw_tww_reach")
assert self.reach_layer is not None
self.setAdvancedDigitizingAllowed(True)
self.setAutoSnapEnabled(True)
layer_snapping_configs = [
{"layer": self.node_layer, "mode": QgsSnappingConfig.Vertex},
{"layer": self.reach_layer, "mode": QgsSnappingConfig.VertexAndSegment},
]
self.snapping_configs = []
self.snapping_utils = QgsMapCanvasSnappingUtils(self.iface.mapCanvas())
for lsc in layer_snapping_configs:
config = QgsSnappingConfig()
config.setMode(QgsSnappingConfig.AdvancedConfiguration)
config.setEnabled(True)
settings = QgsSnappingConfig.IndividualLayerSettings(
True, lsc["mode"], 10, QgsTolerance.Pixels
)
config.setIndividualLayerSettings(lsc["layer"], settings)
self.snapping_configs.append(config)
def left_clicked(self, event):
"""
The mouse is clicked: snap to neary points which are on the wastewater node layer
and update the rubberband
:param event: The coordinates etc.
"""
point3d, match = self.snap(event)
if self.rubberband.numberOfVertices() == 0:
self.first_snapping_match = match
self.last_snapping_match = match
self.rubberband.addPoint3D(point3d)
self.temp_rubberband.reset()
self.temp_rubberband.addPoint(QgsPointXY(point3d.x(), point3d.y()))
if self.snapping_marker is not None:
self.iface.mapCanvas().scene().removeItem(self.snapping_marker)
self.snapping_marker = None
def mouse_move(self, event):
_, match = self.snap(event)
# snap indicator
if not match.isValid():
if self.snapping_marker is not None:
self.iface.mapCanvas().scene().removeItem(self.snapping_marker)
self.snapping_marker = None
return
# TODO QGIS 3: see if vertices can be removed
# we have a valid match
if self.snapping_marker is None:
self.snapping_marker = QgsVertexMarker(self.iface.mapCanvas())
self.snapping_marker.setPenWidth(3)
self.snapping_marker.setColor(QColor(Qt.magenta))
if match.hasVertex():
if match.layer():
icon_type = QgsVertexMarker.ICON_BOX # vertex snap
else:
icon_type = QgsVertexMarker.ICON_X # intersection snap
else:
icon_type = QgsVertexMarker.ICON_DOUBLE_TRIANGLE # must be segment snap
self.snapping_marker.setIconType(icon_type)
self.snapping_marker.setCenter(match.point())
def snap(self, event):
"""
Snap to nearby points on the wastewater node layer which may be used as connection
points for this reach.
:param event: The mouse event
:return: The snapped position in map coordinates
"""
for config in self.snapping_configs:
self.snapping_utils.setConfig(config)
match = self.snapping_utils.snapToMap(QgsPointXY(event.originalMapPoint()))
if match.isValid():
return QgsPoint(match.point()), match
# if no match, snap to all layers (according to map settings) and try to grab Z
match = (
self.iface.mapCanvas().snappingUtils().snapToMap(QgsPointXY(event.originalMapPoint()))
)
if match.isValid() and match.hasVertex():
if match.layer():
req = QgsFeatureRequest(match.featureId())
f = next(match.layer().getFeatures(req))
assert f.isValid()
(ok, vertex_id) = f.geometry().vertexIdFromVertexNr(match.vertexIndex())
assert ok
point = f.geometry().constGet().vertexAt(vertex_id)
assert isinstance(point, QgsPoint)
return point, match
else:
return QgsPoint(match.point()), match
return QgsPoint(event.originalMapPoint()), match
def right_clicked(self, _):
"""
The party is over, the reach digitized. Create a feature from the rubberband and
show the feature form.
"""
self.temp_rubberband.reset()
if self.snapping_marker is not None:
self.iface.mapCanvas().scene().removeItem(self.snapping_marker)
self.snapping_marker = None
if len(self.rubberband.points) >= 2:
fields = self.layer.fields()
f = QgsFeature(fields)
if not self.last_feature_attributes:
self.last_feature_attributes = [None] * fields.count()
for idx, field in enumerate(fields):
if field.name() in [
"clear_height",
"material",
"ch_usage_current",
"ch_function_hierarchic",
"ch_function_hydraulic",
"horizontal_positioning",
"ws_status",
"ws_year_of_construction",
"ws_fk_owner",
"ws_fk_operator",
"inside_coating",
"fk_pipe_profile",
"remark",
]:
f.setAttribute(idx, self.last_feature_attributes[idx])
else:
# try client side default value first
v = self.layer.defaultValue(idx, f)
if v != NULL:
f.setAttribute(idx, v)
else:
f.setAttribute(idx, self.layer.dataProvider().defaultValue(idx))
f.setGeometry(self.rubberband.asGeometry3D())
snapping_results = {
"from": self.first_snapping_match,
"to": self.last_snapping_match,
}
for dest, match in list(snapping_results.items()):
level_field_index = self.layer.fields().indexFromName(f"rp_{dest}_level")
pt_idx = 0 if dest == "from" else -1
if match.isValid() and match.layer() in (
self.node_layer,
self.reach_layer,
):
request = QgsFeatureRequest(match.featureId())
network_element = next(match.layer().getFeatures(request))
assert network_element.isValid()
# set the related network element
field = self.layer.fields().indexFromName(
f"rp_{dest}_fk_wastewater_networkelement"
)
f.setAttribute(field, network_element.attribute("obj_id"))
# assign level if the match is a node or if we have 3D from snapping
if match.layer() == self.node_layer:
level = network_element["bottom_level"]
f.setAttribute(level_field_index, level)
elif self.rubberband.points[pt_idx].z() != 0:
level = self.rubberband.points[pt_idx].z()
level = level if not math.isnan(level) else NULL
f.setAttribute(level_field_index, level)
dlg = self.iface.getFeatureForm(self.layer, f)
dlg.setMode(QgsAttributeEditorContext.AddFeatureMode)
dlg.exec_()
self.last_feature_attributes = dlg.feature().attributes()
self.rubberband.reset3D()
class TwwMapToolDigitizeDrainageChannel(QgsMapTool):
"""
This is used to digitize a drainage channel.
It lets you digitize two points and then creates a polygon based on these two points
by adding an orthogonal offset at each side.
Input:
x==============x
Output:
----------------
| |
----------------
Usage:
Connect to the signals deactivated() and geometryDigitized()
If geometryDigitized() is called you can use the member variable geometry
which will contain a rectangle polygon
deactivated() will be emited after a right click
"""
geometryDigitized = pyqtSignal()
def __init__(self, iface, layer):
QgsMapTool.__init__(self, iface.mapCanvas())
self.iface = iface
self.canvas = iface.mapCanvas()
self.layer = layer
self.rubberband = QgsRubberBand(iface.mapCanvas(), QgsWkbTypes.LineGeometry)
self.rubberband.setColor(QColor("#ee5555"))
self.rubberband.setWidth(2)
self.firstPoint = None
self.messageBarItem = None
self.geometry = None
def activate(self):
"""
Map tool is activated
"""
QgsMapTool.activate(self)
self.canvas.setCursor(QCursor(Qt.CrossCursor))
msgtitle = self.tr("Digitizing Drainage Channel")
msg = self.tr("Digitize start and end point. Rightclick to abort.")
self.messageBarItem = QgsMessageBar.createMessage(msgtitle, msg)
self.iface.messageBar().pushItem(self.messageBarItem)
def deactivate(self):
"""
Map tool is deactivated
"""
QgsMapTool.deactivate(self)
self.iface.messageBar().popWidget(self.messageBarItem)
try:
self.iface.mapCanvas().scene().removeItem(self.rubberband)
del self.rubberband
except AttributeError:
# Called repeatedly... bail out
pass
self.canvas.unsetCursor()
def canvasMoveEvent(self, event):
"""
Mouse is moved: Update rubberband
:param event: coordinates etc.
"""
mousepos = event.mapPoint()
self.rubberband.movePoint(mousepos)
def canvasReleaseEvent(self, event):
"""
Canvas is released. This means:
* start digitizing
* stop digitizing (create a rectangle
* if the Ctrl-modifier is pressed, ask for the rectangle width
:param event: coordinates etc.
"""
if event.button() == Qt.RightButton:
self.deactivate()
else:
mousepos = self.canvas.getCoordinateTransform().toMapCoordinates(
event.pos().x(), event.pos().y()
)
self.rubberband.addPoint(mousepos)
if self.firstPoint: # If the first point was set before, we are doing the second one
lp1 = self.rubberband.asGeometry().asPolyline()[0]
lp2 = self.rubberband.asGeometry().asPolyline()[1]
width = 0.1
if QApplication.keyboardModifiers() & Qt.ControlModifier:
dlg = QDialog()
dlg.setLayout(QGridLayout())
dlg.layout().addWidget(QLabel(self.tr("Enter width")))
txt = QLineEdit("0.2")
dlg.layout().addWidget(txt)
bb = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel)
dlg.layout().addWidget(bb)
bb.accepted.connect(dlg.accept)
bb.rejected.connect(dlg.reject)
if dlg.exec_():
try:
width = float(txt.text()) / 2
except ValueError:
width = 0.1
length = math.sqrt(math.pow(lp1.x() - lp2.x(), 2) + math.pow(lp1.y() - lp2.y(), 2))
xd = lp2.x() - lp1.x()
yd = lp2.y() - lp1.y()
pt1 = QgsPointXY(lp1.x() + width * (yd / length), lp1.y() - width * (xd / length))
pt2 = QgsPointXY(lp1.x() - width * (yd / length), lp1.y() + width * (xd / length))
pt3 = QgsPointXY(lp2.x() - width * (yd / length), lp2.y() + width * (xd / length))
pt4 = QgsPointXY(lp2.x() + width * (yd / length), lp2.y() - width * (xd / length))
self.geometry = QgsGeometry.fromPolygonXY([[pt1, pt2, pt3, pt4, pt1]])
self.geometryDigitized.emit()
self.firstPoint = mousepos