-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathelevation_floater.py
More file actions
1480 lines (1292 loc) · 69.6 KB
/
elevation_floater.py
File metadata and controls
1480 lines (1292 loc) · 69.6 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
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding: utf-8 -*-
"""
Lightweight elevation floater controller.
Shows an interpolated value from a selected raster DEM near the mouse cursor
while the checkbox in the dock widget is enabled. It does NOT take over the
active map tool; it listens to canvas cursor movement.
"""
import math
from typing import Optional, Tuple
from qgis.PyQt import QtCore, QtGui, QtWidgets
from qgis.PyQt.QtCore import Qt, QEvent, QPoint
from qgis.core import (
QgsProject,
QgsCoordinateTransform,
QgsCoordinateTransformContext,
QgsCoordinateReferenceSystem,
QgsPointXY,
QgsMapLayer,
QgsRaster,
QgsRectangle,
QgsVectorLayer,
QgsFeatureRequest,
QgsWkbTypes,
)
# ---- Style knobs --------------------------------------------------------------
BUBBLE_BG_RGBA = (240, 240, 240, 170)
BUBBLE_BORDER_RGBA = (0, 0, 0, 100)
BUBBLE_RADIUS = 8
LABEL_FONT_FAMILY = "Calibri"
LABEL_FONT_FALLBACK = "Arial"
LABEL_FONT_SIZE_PT = 9
LABEL_HPAD = 6
LABEL_VPAD = 2
OFFSET_DX = 14
OFFSET_DY = 10
SHADOW_BLUR = 12
SHADOW_COLOR = QtGui.QColor(0, 0, 0, 60)
class _FloaterWidget(QtWidgets.QWidget):
def __init__(self, parent=None):
super().__init__(parent)
self.setWindowFlags(Qt.FramelessWindowHint | Qt.BypassWindowManagerHint)
self.setAttribute(Qt.WA_TransparentForMouseEvents, True)
self.setAttribute(Qt.WA_TranslucentBackground, True)
self.setAutoFillBackground(False)
self.label = QtWidgets.QLabel("—", self)
font = QtGui.QFont()
fam_ok = QtGui.QFontInfo(QtGui.QFont(LABEL_FONT_FAMILY)).family() != ""
font.setFamily(LABEL_FONT_FAMILY if fam_ok else LABEL_FONT_FALLBACK)
font.setPointSize(LABEL_FONT_SIZE_PT)
self.label.setFont(font)
# Enable rich text formatting for HTML content
self.label.setTextFormat(Qt.RichText)
self._text_color = QtGui.QColor(34, 34, 34)
self._bg_color = QtGui.QColor(*BUBBLE_BG_RGBA)
self.label.setStyleSheet("QLabel { color: #222; }")
layout = QtWidgets.QHBoxLayout(self)
layout.setContentsMargins(LABEL_HPAD, LABEL_VPAD, LABEL_HPAD, LABEL_VPAD)
layout.setSpacing(0)
layout.addWidget(self.label)
shadow = QtWidgets.QGraphicsDropShadowEffect(self)
shadow.setBlurRadius(SHADOW_BLUR)
shadow.setOffset(0, 0)
shadow.setColor(SHADOW_COLOR)
self.setGraphicsEffect(shadow)
self.adjustSize()
def set_text(self, text: str):
self.label.setText(text)
self.adjustSize()
self.update()
def move_near_global(self, global_pos: QtCore.QPoint, dx=OFFSET_DX, dy=OFFSET_DY):
if self.parent():
local = self.parent().mapFromGlobal(global_pos)
self.move(local + QPoint(dx, dy))
else:
self.move(global_pos + QPoint(dx, dy))
def paintEvent(self, e):
p = QtGui.QPainter(self)
p.setRenderHint(QtGui.QPainter.Antialiasing, True)
rect = self.rect().adjusted(0, 0, -1, -1)
p.setBrush(self._bg_color)
p.setPen(QtCore.Qt.NoPen)
p.drawRoundedRect(rect, getattr(self, '_corner_radius', BUBBLE_RADIUS), getattr(self, '_corner_radius', BUBBLE_RADIUS))
pen = QtGui.QPen(QtGui.QColor(*BUBBLE_BORDER_RGBA))
pen.setWidth(1)
p.setPen(pen)
p.setBrush(QtCore.Qt.NoBrush)
p.drawRoundedRect(rect, getattr(self, '_corner_radius', BUBBLE_RADIUS), getattr(self, '_corner_radius', BUBBLE_RADIUS))
def apply_style(self, font: QtGui.QFont, point_size: int, text_color: QtGui.QColor, bg_color: QtGui.QColor):
font_to_set = QtGui.QFont(font)
font_to_set.setPointSize(point_size)
self.label.setFont(font_to_set)
self._text_color = QtGui.QColor(text_color)
self._bg_color = QtGui.QColor(bg_color)
self.label.setStyleSheet(f"QLabel {{ color: {self._text_color.name()}; }}")
self.adjustSize()
self.update()
class _CanvasInOutWatcher(QtCore.QObject):
def __init__(self, floater, parent=None):
super().__init__(parent)
self._floater = floater
def eventFilter(self, obj, ev):
t = ev.type()
if t in (QEvent.Enter, QEvent.HoverEnter, QEvent.FocusIn):
self._floater.show()
elif t in (QEvent.Leave, QEvent.HoverLeave, QEvent.FocusOut, QEvent.WindowDeactivate):
self._floater.hide()
return False
class RasterInterpolator:
def __init__(self, raster_layer, band=1):
self.layer = raster_layer
self.dp = raster_layer.dataProvider()
self.band = int(band)
try:
self.nodata = self.dp.sourceNoDataValue(self.band) if self.dp.sourceHasNoDataValue(self.band) else None
except Exception:
self.nodata = None
self.extent = self.dp.extent()
self.width = self.dp.xSize()
self.height = self.dp.ySize()
try:
self.xres = self.extent.width() / self.width
self.yres = self.extent.height() / self.height
except Exception:
try:
self.xres = self.layer.rasterUnitsPerPixelX()
self.yres = self.layer.rasterUnitsPerPixelY()
except Exception:
self.xres = 1.0
self.yres = 1.0
def _is_nodata(self, v):
if v is None:
return True
try:
fv = float(v)
if math.isnan(fv):
return True
if self.nodata is not None and fv == self.nodata:
return True
return False
except Exception:
return False
def nearest(self, pt_layer_crs: QgsPointXY):
try:
val, ok = self.dp.sample(pt_layer_crs, self.band)
except Exception:
return None
if not ok or self._is_nodata(val):
return None
try:
return float(val)
except Exception:
return None
def bilinear(self, pt_layer_crs: QgsPointXY):
x = pt_layer_crs.x()
y = pt_layer_crs.y()
try:
col = int(round((x - self.extent.xMinimum()) / self.xres))
row = int(round((self.extent.yMaximum() - y) / self.yres))
except Exception:
return self.nearest(pt_layer_crs)
xMin = self.extent.xMinimum() + (col - 1) * self.xres
xMax = xMin + 2 * self.xres
yMax = self.extent.yMaximum() - (row - 1) * self.yres
yMin = yMax - 2 * self.yres
if (xMin < self.extent.xMinimum() or xMax > self.extent.xMaximum() or
yMin < self.extent.yMinimum() or yMax > self.extent.yMaximum()):
return self.nearest(pt_layer_crs)
pixel_extent = QgsRectangle(xMin, yMin, xMax, yMax)
block = self.dp.block(self.band, pixel_extent, 2, 2)
if block is None or block.width() != 2 or block.height() != 2:
return self.nearest(pt_layer_crs)
v12 = block.value(0, 0)
v22 = block.value(0, 1)
v11 = block.value(1, 0)
v21 = block.value(1, 1)
if any(self._is_nodata(v) for v in (v11, v12, v21, v22)):
return self.nearest(pt_layer_crs)
x1 = xMin + self.xres / 2.0
x2 = xMax - self.xres / 2.0
y1 = yMin + self.yres / 2.0
y2 = yMax - self.yres / 2.0
denom = (x2 - x1) * (y2 - y1)
if denom == 0:
return self.nearest(pt_layer_crs)
val = (
v11 * (x2 - x) * (y2 - y)
+ v21 * (x - x1) * (y2 - y)
+ v12 * (x2 - x) * (y - y1)
+ v22 * (x - x1) * (y - y1)
) / denom
try:
fv = float(val)
if self._is_nodata(fv):
return None
return fv
except Exception:
return None
class ElevationFloaterController(QtCore.QObject):
"""Attaches to the canvas and shows an interpolated DEM value near cursor."""
def __init__(self, iface):
super().__init__(iface.mainWindow() if iface else None)
self.iface = iface
self.canvas = self.iface.mapCanvas() if self.iface else None
# Snap utilities for getting snapped coordinates
self.snapper = self.canvas.snappingUtils() if self.canvas else None
self._floater: Optional[_FloaterWidget] = None
self._watcher: Optional[_CanvasInOutWatcher] = None
self._interp: Optional[RasterInterpolator] = None
self._to_raster: Optional[QgsCoordinateTransform] = None
self._band: int = 1
self._format: str = "{value:.3f}"
self._nodata_text: str = "NoData"
self._connected = False
# User-configurable display toggles
self.show_extension: bool = True
self.show_elevation: bool = True
self.show_depth: bool = True
# Parameters for depth preview
self.minimum_cover_m: float = 0.9
self.diameter_m: float = 0.150
self.slope_m_per_m: float = 0.005
self.initial_depth_m: float = 0.0
# State for click sequence
self._have_upstream: bool = False
self._upstream_map_point: Optional[QgsPointXY] = None
self._upstream_ground_elev: Optional[float] = None
self._upstream_bottom_elev: Optional[float] = None
# Track when we inherit depth from existing segment
self._inherited_depth: Optional[float] = None
# Track depth from current snap match (for hover preview)
self._current_snap_depth: Optional[float] = None
# Optional dedicated measure CRS
self._measure_crs: Optional[QgsCoordinateReferenceSystem] = None
# Style
self._font = QtGui.QFont(LABEL_FONT_FAMILY)
self._font_size = LABEL_FONT_SIZE_PT
self._bold_labels = True
self._text_color = QtGui.QColor(34, 34, 34)
self._bg_color = QtGui.QColor(*BUBBLE_BG_RGBA)
# Gating: only show when editing on selected line layer
self._gate_layer_id: Optional[str] = None
# Click storage for segment attribute writing
self._stored_clicks = [] # List of {map_point, ground_elev, bottom_elev, timestamp}
# Track features in buffer at session start to identify truly new ones
self._buffer_features_at_session_start = set()
def start(self, raster_layer, band=1, number_format="{value:.3f}", nodata_text="NoData"):
if not self.canvas or not raster_layer:
raise RuntimeError("Canvas or raster layer not available")
self._band = int(band)
self._format = number_format
self._nodata_text = nodata_text
ctxt: QgsCoordinateTransformContext = QgsProject.instance().transformContext()
self._to_raster = QgsCoordinateTransform(
self.canvas.mapSettings().destinationCrs(), raster_layer.crs(), ctxt
)
self._interp = RasterInterpolator(raster_layer, band=self._band)
parent_for_overlay = self.canvas.viewport() or self.canvas
if self._floater is None:
self._floater = _FloaterWidget(parent=parent_for_overlay)
self._floater.hide()
# Apply current style
self._floater.apply_style(self._font, self._font_size, self._text_color, self._bg_color)
# Corner radius
try:
self._floater._corner_radius = getattr(self, '_corner_radius', BUBBLE_RADIUS)
except Exception:
pass
if self._watcher is None:
self._watcher = _CanvasInOutWatcher(self._floater, parent=self.canvas)
self.canvas.installEventFilter(self._watcher)
if self.canvas.viewport() is not None:
self.canvas.viewport().installEventFilter(self._watcher)
if not self._connected:
self.canvas.xyCoordinates.connect(self._on_xy_raw)
# Install low-level event filter for press events on viewport
self.canvas.viewport().installEventFilter(self)
self._connected = True
def stop(self):
if not self.canvas:
return
if self._connected:
try:
self.canvas.xyCoordinates.disconnect(self._on_xy_raw)
except Exception:
pass
self._connected = False
# Remove viewport press filter
try:
if self.canvas.viewport() is not None:
self.canvas.viewport().removeEventFilter(self)
except Exception:
pass
if self._watcher:
try:
self.canvas.removeEventFilter(self._watcher)
except Exception:
pass
try:
if self.canvas.viewport() is not None:
self.canvas.viewport().removeEventFilter(self._watcher)
except Exception:
pass
if self._floater:
self._floater.hide()
# ------------------------------------------------------------------
def _on_xy_raw(self, map_pt: QgsPointXY):
"""Handle raw xyCoordinates signal and check for snapped coordinates"""
try:
# Convert map coordinates back to screen coordinates to check for snapping
screen_pt = self.canvas.getCoordinateTransform().transform(map_pt)
screen_pos = QtCore.QPoint(int(screen_pt.x()), int(screen_pt.y()))
# Check if snapping occurred and get snap results
snapped_pt = map_pt # Default to original
snap_depth = None
if self.snapper:
snap_match = self.snapper.snapToMap(screen_pos)
if snap_match.isValid():
snapped_pt = snap_match.point()
# If we snapped, compute max coincident depth at snapped coord (before first click)
if not self._have_upstream:
snap_depth = self._find_existing_depth_at_point(snapped_pt, None)
# Store snap depth for use in _compose_text
self._current_snap_depth = snap_depth
self._on_xy(snapped_pt)
except Exception:
# Fallback to original coordinates
self._current_snap_depth = None
self._on_xy(map_pt)
def _on_xy(self, map_pt: QgsPointXY):
# Guard against removed raster providers
if not self._interp or not self._to_raster or not self._floater:
return
# Gate: show only when editing on selected line layer
if not self._passes_gate():
self._floater.hide()
return
try:
# touch provider to see if valid
_ = self._interp.dp
except Exception:
return
try:
lyr_pt = self._to_raster.transform(QgsPointXY(map_pt))
except Exception:
self._floater.set_text("CRS xform error")
self._floater.move_near_global(QtGui.QCursor.pos())
return
try:
elev = self._interp.bilinear(lyr_pt)
except Exception:
return
text = self._compose_text(map_pt, elev)
self._floater.set_text(text)
self._floater.move_near_global(QtGui.QCursor.pos(), dx=getattr(self, '_offset_x', OFFSET_DX), dy=getattr(self, '_offset_y', OFFSET_DY))
if not self._floater.isVisible():
self._floater.show()
# Build display text
def _compose_text(self, map_pt: QgsPointXY, elev: Optional[float]) -> str:
lines = []
# Extension (distance)
if self.show_extension and self._have_upstream and self._upstream_map_point is not None:
try:
dist = self._distance_m(self._upstream_map_point, map_pt)
lines.append(f"ext={dist:.2f}")
except Exception:
pass
# Elevation
if self.show_elevation:
if elev is None:
lines.append(f"elev={self._nodata_text}")
else:
lines.append(f"elev={float(elev):.2f}")
# Depth preview - different logic for before vs after first click
if self.show_depth:
if self._have_upstream and self._upstream_bottom_elev is not None:
# Normal depth calculation when we have upstream point
try:
dist = self._distance_m(self._upstream_map_point, map_pt)
downstream_candidate = self._upstream_bottom_elev - dist * max(0.0, float(self.slope_m_per_m))
# If current elev known, enforce minimum cover
if elev is not None:
# Use integer math to avoid floating-point precision issues
min_cover_mm = int(round(float(self.minimum_cover_m) * 1000))
diameter_mm = int(round(float(self.diameter_m) * 1000))
total_depth = (min_cover_mm + diameter_mm) / 1000.0
min_bottom = float(elev) - total_depth
downstream_bottom = min(downstream_candidate, min_bottom)
depth_val = float(elev) - downstream_bottom
else:
depth_val = float('nan')
# Show if this is first point and depth was inherited
if dist < 0.01 and self._inherited_depth is not None: # Within 1cm = first click
lines.append(f"<b><i><font color=\"#aa0000\">depth={depth_val:.2f}</font></i></b>")
else:
lines.append(f"depth={depth_val:.2f}")
except Exception:
pass
else:
# Before first click: show depth from snap match if available
if self._current_snap_depth is not None:
# Use consistent bold+italic red formatting for inherited depth
lines.append(f'<b><i><font color="#aa0000">depth={self._current_snap_depth:.2f}</font></i></b>')
if not lines:
# Default to elevation text if nothing selected
return self._nodata_text if elev is None else self._format.format(value=float(elev))
# Layout mode: vertical vs horizontal
if getattr(self, '_layout_mode', 'vertical') == 'horizontal':
sep = " "
else:
sep = "<br/>"
if self._bold_labels:
def bold_label(line: str) -> str:
try:
# Skip HTML formatting for lines that already contain HTML tags
if '<' in line and '>' in line:
return line
key, val = line.split("=", 1)
return f"<b>{key}</b>={val}"
except Exception:
return line
parts = [bold_label(l) for l in lines]
else:
parts = lines
html = sep.join(parts)
# Use rich text rendering
self._floater.label.setTextFormat(Qt.RichText)
return html
# Distance in meters using canvas mapSettings distances
def _distance_m(self, a: QgsPointXY, b: QgsPointXY) -> float:
# Prefer configured measure CRS; else canvas destination CRS; else raster CRS
crs = self._measure_crs or self.canvas.mapSettings().destinationCrs()
if not crs or not crs.isValid():
crs = self.layer.crs() if hasattr(self, 'layer') else self.canvas.mapSettings().destinationCrs()
if crs.isGeographic():
# Transform to raster CRS (likely projected) for distance calc
if self._to_raster is not None:
pa = self._to_raster.transform(QgsPointXY(a))
pb = self._to_raster.transform(QgsPointXY(b))
dx = pb.x() - pa.x()
dy = pb.y() - pa.y()
return (dx * dx + dy * dy) ** 0.5
# Projected CRS in meters typically
dx = b.x() - a.x()
dy = b.y() - a.y()
return (dx * dx + dy * dy) ** 0.5
def _get_snapped_or_raw_point(self, screen_pos):
"""Get snapped coordinates if available, otherwise raw coordinates"""
try:
if self.snapper:
snap_match = self.snapper.snapToMap(screen_pos)
if snap_match.isValid():
# Return snapped point coordinates
return snap_match.point()
# Fallback to raw coordinates
return self.canvas.getCoordinateTransform().toMapCoordinates(screen_pos.x(), screen_pos.y())
except Exception:
# Emergency fallback
return self.canvas.getCoordinateTransform().toMapCoordinates(screen_pos.x(), screen_pos.y())
def _find_existing_depth_at_point(self, map_pt: QgsPointXY, tolerance: Optional[float] = None):
"""Find existing segment depth at the given coordinates
Args:
map_pt: Point coordinates to search for
tolerance: Search tolerance in map units. If None, uses a small pixel-based tolerance.
Returns:
float or None: Maximum existing depth value if any coincident endpoints are found, None otherwise
"""
if not self._current_layer:
return None
try:
# Derive tolerance from pixels if not provided
if tolerance is None and self.canvas is not None:
# 5 pixels radius converted to map units
tolerance = max(self.canvas.mapUnitsPerPixel() * 5.0, 1e-6)
elif tolerance is None:
tolerance = 0.001
# Get field mappings for depth fields
field_mapping = self._get_field_mapping()
p1_h_idx = field_mapping.get('p1_h', -1)
p2_h_idx = field_mapping.get('p2_h', -1)
if p1_h_idx < 0 and p2_h_idx < 0:
return None # No depth fields available
# Search for features with endpoints at or very near this coordinate
search_rect = QgsRectangle(
map_pt.x() - tolerance, map_pt.y() - tolerance,
map_pt.x() + tolerance, map_pt.y() + tolerance
)
# Get all features in the search area
request = QgsFeatureRequest().setFilterRect(search_rect)
features = list(self._current_layer.getFeatures(request))
# Also inspect edit buffer added features if present
try:
eb = self._current_layer.editBuffer()
if eb:
for f in eb.addedFeatures().values():
try:
g = f.geometry()
if g and not g.isEmpty() and g.boundingBox().intersects(search_rect):
features.append(f)
except Exception:
pass
except Exception:
pass
# Debug: Commented out verbose depth search logging
# print(f"[SEWERAGE DEBUG] Searching for existing depth at {map_pt.x():.6f}, {map_pt.y():.6f}")
# print(f"[SEWERAGE DEBUG] Found {len(features)} features in search area")
max_depth: Optional[float] = None
for feature in features:
geom = feature.geometry()
if not geom or geom.isEmpty():
continue
if geom.type() != QgsWkbTypes.LineGeometry:
continue
# Resolve first and last points of the polyline
try:
if geom.isMultipart():
lines = geom.asMultiPolyline()
if not lines:
continue
# Evaluate all parts to catch endpoints that coincide
parts = lines
else:
parts = [geom.asPolyline()]
except Exception:
continue
candidate_depths = []
for pts in parts:
if len(pts) < 2:
continue
p1 = QgsPointXY(pts[0])
p2 = QgsPointXY(pts[-1])
# Check proximity to start/end
d1 = ((p1.x() - map_pt.x()) ** 2 + (p1.y() - map_pt.y()) ** 2) ** 0.5
d2 = ((p2.x() - map_pt.x()) ** 2 + (p2.y() - map_pt.y()) ** 2) ** 0.5
if d1 <= tolerance and p1_h_idx >= 0:
candidate_depths.append(feature.attribute(p1_h_idx))
if d2 <= tolerance and p2_h_idx >= 0:
candidate_depths.append(feature.attribute(p2_h_idx))
for val in candidate_depths:
if val is None or val == '':
continue
try:
depth_float = float(val)
# Debug: Commented out verbose candidate depth logging
# print(f"[SEWERAGE DEBUG] Candidate depth {depth_float:.3f}m on feature {feature.id()}")
if max_depth is None or depth_float > max_depth:
max_depth = depth_float
except (ValueError, TypeError):
continue
except Exception as e:
# print(f"[SEWERAGE DEBUG] Error searching for existing depth: {e}")
pass
# Debug: Commented out verbose depth selection logging
# print(f"[SEWERAGE DEBUG] Selected maximum coincident depth: {max_depth:.3f}m")
pass
return max_depth
def _get_depth_from_snap_match(self, snap_match):
"""Extract depth value from a snap match result"""
try:
# Get the feature and vertex index from snap match
if hasattr(snap_match, 'layer') and hasattr(snap_match, 'featureId'):
layer = snap_match.layer()
if layer != self._current_layer:
return None # Only check our current layer
feature_id = snap_match.featureId()
vertex_index = getattr(snap_match, 'vertexIndex', lambda: -1)()
# Get the feature
feature = layer.getFeature(feature_id)
if not feature.isValid():
return None
# Get field mappings
field_mapping = self._get_field_mapping()
p1_h_idx = field_mapping.get('p1_h', -1)
p2_h_idx = field_mapping.get('p2_h', -1)
# Determine if this is start (p1) or end (p2) vertex
geom = feature.geometry()
if geom and not geom.isEmpty():
if geom.type() == QgsWkbTypes.LineGeometry:
# For linestring, vertex 0 = p1, last vertex = p2
vertex_count = geom.constGet().numPoints() if hasattr(geom.constGet(), 'numPoints') else 0
if vertex_index == 0 and p1_h_idx >= 0:
# First vertex = p1
depth_value = feature.attribute(p1_h_idx)
elif vertex_index == vertex_count - 1 and p2_h_idx >= 0:
# Last vertex = p2
depth_value = feature.attribute(p2_h_idx)
else:
return None # Middle vertex, no depth info
if depth_value is not None and depth_value != '':
try:
return float(depth_value)
except (ValueError, TypeError):
pass
except Exception as e:
# print(f"[SEWERAGE DEBUG] Error getting depth from snap match: {e}")
pass
# Event filter to catch clicks without stealing the active tool
def eventFilter(self, obj, ev):
if self.canvas and obj is self.canvas.viewport():
t = ev.type()
if t == QtCore.QEvent.MouseButtonPress:
btn = ev.button()
pos = ev.pos()
# Use snapped coordinates if available, otherwise raw coordinates
map_pt = self._get_snapped_or_raw_point(pos)
# Gate check
if not self._passes_gate():
return super().eventFilter(obj, ev)
if btn == QtCore.Qt.LeftButton:
self._handle_left_click(map_pt)
elif btn == QtCore.Qt.RightButton:
# Reset and allow native context menu to proceed
self._reset_sequence()
return super().eventFilter(obj, ev)
def _handle_left_click(self, map_pt: QgsPointXY):
# Bail if raster was removed
if not self._interp or not self._to_raster:
return
try:
_ = self._interp.dp
except Exception:
return
try:
lyr_pt = self._to_raster.transform(QgsPointXY(map_pt))
except Exception:
return
try:
elev = self._interp.bilinear(lyr_pt) if self._interp else None
except Exception:
return
import time
current_time = time.time()
if not self._have_upstream:
# First click: clear any old stored clicks from previous drawing session
if self._stored_clicks:
# print(f"[SEWERAGE DEBUG] Clearing {len(self._stored_clicks)} old stored clicks before new drawing")
self._stored_clicks = []
# Capture current buffer state at start of new drawing session
try:
if self._current_layer and self._current_layer.editBuffer():
current_buffer_features = set(self._current_layer.editBuffer().addedFeatures().keys())
self._buffer_features_at_session_start = current_buffer_features
# print(f"[SEWERAGE DEBUG] Session start - buffer contains: {sorted(current_buffer_features)}")
else:
self._buffer_features_at_session_start = set()
except Exception as e:
# print(f"[SEWERAGE DEBUG] Error capturing buffer state: {e}")
self._buffer_features_at_session_start = set()
# First click: set upstream point and upstream bottom by rule
self._upstream_map_point = QgsPointXY(map_pt)
self._upstream_ground_elev = float(elev) if elev is not None else None
# Check for existing depth at this coordinate (with preference over initial_depth_m)
existing_depth = self._find_existing_depth_at_point(map_pt, None)
effective_initial_depth = self.initial_depth_m
if existing_depth is not None:
# Use existing depth instead of initial_depth_m parameter
effective_initial_depth = existing_depth
self._inherited_depth = existing_depth
# print(f"[SEWERAGE DEBUG] Using existing depth {existing_depth:.3f}m instead of initial depth {self.initial_depth_m:.3f}m")
else:
self._inherited_depth = None
if effective_initial_depth > 0.0:
upstream_bottom = (self._upstream_ground_elev if self._upstream_ground_elev is not None else 0.0) - float(effective_initial_depth)
else:
# Minimum cover + diameter (use integer math to avoid floating-point precision issues)
if self._upstream_ground_elev is not None:
# Convert to mm, add as integers, convert back to meters
min_cover_mm = int(round(float(self.minimum_cover_m) * 1000))
diameter_mm = int(round(float(self.diameter_m) * 1000))
total_depth = (min_cover_mm + diameter_mm) / 1000.0
upstream_bottom = self._upstream_ground_elev - total_depth
else:
upstream_bottom = None
self._upstream_bottom_elev = upstream_bottom
self._have_upstream = True
# Store first click
upstream_depth = (self._upstream_ground_elev - upstream_bottom) if (self._upstream_ground_elev is not None and upstream_bottom is not None) else None
click_data = {
'map_point': QgsPointXY(map_pt),
'ground_elev': self._upstream_ground_elev,
'bottom_elev': upstream_bottom,
'depth': upstream_depth,
'timestamp': current_time
}
self._stored_clicks.append(click_data)
# print(f"[SEWERAGE DEBUG] Stored first click: {map_pt.x():.2f}, {map_pt.y():.2f}, elev={self._upstream_ground_elev}, depth={upstream_depth}")
else:
# Second and subsequent clicks: finalize current downstream as new upstream
if self._upstream_bottom_elev is None:
return
# Compute downstream bottom at clicked point
try:
dist = self._distance_m(self._upstream_map_point, map_pt)
candidate = self._upstream_bottom_elev - dist * max(0.0, float(self.slope_m_per_m))
if elev is not None:
# Use integer math to avoid floating-point precision issues
min_cover_mm = int(round(float(self.minimum_cover_m) * 1000))
diameter_mm = int(round(float(self.diameter_m) * 1000))
total_depth = (min_cover_mm + diameter_mm) / 1000.0
min_bottom = float(elev) - total_depth
downstream_bottom = min(candidate, min_bottom)
else:
downstream_bottom = candidate
# Store this click
downstream_depth = (float(elev) - downstream_bottom) if (elev is not None and downstream_bottom is not None) else None
click_data = {
'map_point': QgsPointXY(map_pt),
'ground_elev': float(elev) if elev is not None else None,
'bottom_elev': downstream_bottom,
'depth': downstream_depth,
'timestamp': current_time
}
self._stored_clicks.append(click_data)
# print(f"[SEWERAGE DEBUG] Stored click {len(self._stored_clicks)}: {map_pt.x():.2f}, {map_pt.y():.2f}, elev={elev}, depth={downstream_depth}")
# Now set new upstream for next segment
self._upstream_map_point = QgsPointXY(map_pt)
self._upstream_ground_elev = float(elev) if elev is not None else None
self._upstream_bottom_elev = downstream_bottom
except Exception:
pass
def _reset_sequence(self):
self._have_upstream = False
self._upstream_map_point = None
self._upstream_ground_elev = None
self._upstream_bottom_elev = None
self._inherited_depth = None
self._current_snap_depth = None
# DON'T clear stored clicks here - let red_basica workflow complete first
# print("[SEWERAGE DEBUG] Reset sequence (right-click) but keeping stored clicks for red_basica workflow")
# External API --------------------------------------------------------------
def set_measure_crs(self, crs: QgsCoordinateReferenceSystem):
self._measure_crs = crs
def set_style(self, font: QtGui.QFont, size_pt: int, text_color: QtGui.QColor, bg_color: QtGui.QColor, bold_labels: bool):
self._font = QtGui.QFont(font)
self._font_size = int(size_pt)
self._text_color = QtGui.QColor(text_color)
self._bg_color = QtGui.QColor(bg_color)
self._bold_labels = bool(bold_labels)
if self._floater:
self._floater.apply_style(self._font, self._font_size, self._text_color, self._bg_color)
def set_layout_mode(self, mode: str):
# 'vertical' or 'horizontal'
self._layout_mode = mode if mode in ('vertical', 'horizontal') else 'vertical'
def set_bubble_style(self, corner_radius: float, offset_x: int, offset_y: int):
try:
self._corner_radius = float(corner_radius)
self._offset_x = int(offset_x)
self._offset_y = int(offset_y)
if self._floater:
self._floater._corner_radius = self._corner_radius
except Exception:
pass
def set_gate_line_layer(self, layer):
try:
# Disconnect from previous layer if any
if hasattr(self, '_current_layer') and self._current_layer is not None:
try:
self._current_layer.featureAdded.disconnect(self._on_feature_added)
self._current_layer.featuresDeleted.disconnect(self._on_features_deleted)
except Exception:
pass
self._gate_layer_id = layer.id() if layer is not None else None
self._current_layer = layer
# Connect to new layer signals if valid
if layer is not None:
try:
layer.featureAdded.connect(self._on_feature_added)
layer.featuresDeleted.connect(self._on_features_deleted)
# Track recent feature operations for red_basica detection
self._recent_deletions = []
self._pending_additions = []
# print(f"[SEWERAGE DEBUG] Connected signals to layer: {layer.name()} (ID: {layer.id()})")
except Exception as e:
# print(f"[SEWERAGE DEBUG] Failed to connect signals: {e}")
pass
else:
pass
# print("[SEWERAGE DEBUG] No layer provided for signal connection")
except Exception:
self._gate_layer_id = None
self._current_layer = None
def _passes_gate(self) -> bool:
if self._gate_layer_id is None:
return False
try:
from qgis.core import QgsProject
from qgis.gui import QgsMapToolDigitizeFeature
lyr = QgsProject.instance().mapLayer(self._gate_layer_id)
if lyr is None:
return False
# Active layer must be the gated one
active = self.iface.activeLayer() if self.iface else None
if active is None or active.id() != lyr.id():
return False
# If layer is editable, show; if not, hide
if not lyr.isEditable():
return False
# NEW: Only work when using "Add Line Feature" tool (digitizing tool)
if self.canvas and self.canvas.mapTool():
current_tool = self.canvas.mapTool()
# Check if it's a digitizing tool (Add Feature tool)
if not isinstance(current_tool, QgsMapToolDigitizeFeature):
return False
return True
except Exception:
return False
# Layer signal handlers for red_basica integration -------------------------
def _on_features_deleted(self, fids):
"""Track deletions - red_basica deletes multi-vertex then adds 2-vertex segments"""
import time
try:
# print(f"[SEWERAGE DEBUG] Features deleted: {list(fids)}")
self._recent_deletions.append({
'fids': list(fids),
'timestamp': time.time()
})
# Keep only recent deletions (last 5 seconds)
current_time = time.time()
self._recent_deletions = [d for d in self._recent_deletions if current_time - d['timestamp'] < 5.0]
except Exception as e:
# print(f"[SEWERAGE DEBUG] Error in _on_features_deleted: {e}")
pass
def _on_feature_added(self, fid):
"""Track additions - detect red_basica pattern and match to stored clicks"""
import time
try:
current_time = time.time()
# print(f"[SEWERAGE DEBUG] Feature added: {fid}")
# print(f"[SEWERAGE DEBUG] Stored clicks count: {len(self._stored_clicks)}")
# print(f"[SEWERAGE DEBUG] Recent deletions: {len(self._recent_deletions)}")
# Simplified detection: if we have stored clicks and this is a negative ID, process it
# The key insight: red_basica always creates negative IDs, so any negative ID + stored clicks = process
should_process = self._stored_clicks and fid < 0
# print(f"[SEWERAGE DEBUG] Should process: stored_clicks={len(self._stored_clicks)}, negative_id={fid < 0}")
if should_process:
# print(f"[SEWERAGE DEBUG] Triggering segment processing for fid: {fid}")
# Add to pending list and wait for more features to be added
if not hasattr(self, '_pending_fids'):
self._pending_fids = []
self._pending_fids.append(fid)
# Delay processing longer to allow all segments to be added
QtCore.QTimer.singleShot(500, lambda: self._process_pending_segments())
else:
if not self._stored_clicks:
pass
# print("[SEWERAGE DEBUG] No stored clicks - skipping processing")
elif fid >= 0:
pass
# print("[SEWERAGE DEBUG] Positive feature ID - likely not red_basica - skipping processing")
except Exception as e:
# print(f"[SEWERAGE DEBUG] Error in _on_feature_added: {e}")
pass
def _process_pending_segments(self):
"""Process all pending segments after collecting multiple feature additions"""
if hasattr(self, '_pending_fids'):
# print(f"[SEWERAGE DEBUG] Processing {len(self._pending_fids)} pending segments")
self._process_new_segments(self._pending_fids)
self._pending_fids = [] # Clear pending list
else:
pass
# print("[SEWERAGE DEBUG] No pending segments to process")
def _process_new_segments(self, recent_fids):
"""Match newly added 2-vertex segments to stored clicks and write attributes"""
# print(f"[SEWERAGE DEBUG] Processing new segments, recent_fids: {recent_fids}")
# print(f"[SEWERAGE DEBUG] Has stored clicks: {bool(self._stored_clicks)}")
# print(f"[SEWERAGE DEBUG] Has current layer: {bool(self._current_layer)}")
if not self._stored_clicks or not self._current_layer:
# print("[SEWERAGE DEBUG] Early return - missing clicks or layer")
return
# Keep a copy of current clicks for downstream recalculation
stored_clicks_copy = list(self._stored_clicks)
try:
# print(f"[SEWERAGE DEBUG] Layer is editable: {self._current_layer.isEditable()}")
# print(f"[SEWERAGE DEBUG] Layer feature count: {self._current_layer.featureCount()}")
# Get features from edit buffer (for newly added features with negative IDs)
edit_buffer = self._current_layer.editBuffer()
if edit_buffer:
added_features = edit_buffer.addedFeatures()
# print(f"[SEWERAGE DEBUG] Edit buffer has {len(added_features)} added features")
# print(f"[SEWERAGE DEBUG] Added feature IDs: {list(added_features.keys())}")
# Filter to only NEW features (not in buffer at session start)
new_feature_ids = set(added_features.keys()) - self._buffer_features_at_session_start