-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathplugin.py
More file actions
1801 lines (1675 loc) · 66.5 KB
/
Copy pathplugin.py
File metadata and controls
1801 lines (1675 loc) · 66.5 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
"""QGIS plugin lifecycle and the persistent EVEL toolbar."""
from __future__ import annotations
from qgis.PyQt.QtCore import Qt
from qgis.PyQt.QtWidgets import (
QAction,
QApplication,
QDialog,
QMenu,
QStyle,
QToolButton,
)
from qgis.core import Qgis, QgsMessageLog, QgsProject, QgsVectorLayer
from .layers import (
DuctLayerCatalog,
DuctLayerOption,
DuctWorkflow,
EVELProjectInspector,
ConnectionPointInspector,
HydrantInspector,
ProjectInspection,
SewerManholeInspector,
SewerPumpingStationInspector,
)
from .map_tools import (
AddGravityDuctController,
AddWaterDuctController,
ConnectionPointConfiguratorController,
EditDuctController,
FlowDirectionController,
HydrantConfiguratorController,
NodeConfiguratorController,
SewerManholeConfiguratorController,
SewerPumpingStationConfiguratorController,
)
from .importer import EvelImportTargetInspector
from .ui import (
DiagnosticsDialog,
EvelClearDataDialog,
EvelImportDialog,
CoordinateDuctDialog,
CoordinateDuctInputError,
VisualNodeConfiguratorDialog,
)
from .ui.light_style import apply_evel_toolbar_light_style
from .ui.icon_catalog import (
ICON_ADD_DUCT,
ICON_CHECK_NETWORK,
ICON_CLEAR_DATA,
ICON_CONFIGURE_NODE,
ICON_CONNECTION_POINT,
ICON_COORDINATE_DUCT,
ICON_EDIT_DUCT,
ICON_ERROR,
ICON_HYDRANT,
ICON_IMPORT,
ICON_PUMPING_STATION,
ICON_REFRESH,
ICON_REPAIR_NETWORK,
ICON_REVERSE_FLOW,
ICON_SEWER_MANHOLE,
ICON_STATUS_OK,
ICON_STATUS_WARNING,
catalog_icon,
set_catalog_icon,
)
MESSAGE_TAG = "EVEL Võrgutööriistad"
TOOLBAR_OBJECT_NAME = "EVELNetworkToolsToolbar"
class EVELNetworkToolsPlugin:
def __init__(self, iface):
self.iface = iface
self.toolbar = None
self.status_action = None
self.status_menu = None
self.add_duct_action = None
self.add_duct_menu = None
self.edit_duct_action = None
self.configure_node_action = None
self.hydrant_action = None
self.connection_point_action = None
self.sewer_manhole_action = None
self.sewer_pumping_station_action = None
self.import_action = None
self.clear_data_action = None
self.reverse_action = None
self.check_action = None
self.repair_action = None
self._connections = []
self._inspection: ProjectInspection | None = None
self._inspector = EVELProjectInspector()
self._duct_catalog = DuctLayerCatalog(self._inspector)
self._duct_options: tuple[DuctLayerOption, ...] = ()
self._selected_duct_layer_id = ""
self._sewer_manhole_inspector = SewerManholeInspector()
self._hydrant_inspector = HydrantInspector()
self._hydrant_ready = False
self._connection_point_inspector = ConnectionPointInspector()
self._connection_point_ready = False
self._sewer_manhole_ready = False
self._sewer_pumping_station_inspector = (
SewerPumpingStationInspector()
)
self._sewer_pumping_station_ready = False
self._import_target_inspector = EvelImportTargetInspector()
self._import_ready = False
self._import_reason = ""
self._import_dialog: EvelImportDialog | None = None
self._clear_data_dialog: EvelClearDataDialog | None = None
self._diagnostics_dialog: DiagnosticsDialog | None = None
self._add_controller: AddWaterDuctController | None = None
self._gravity_controller: AddGravityDuctController | None = None
self._edit_duct_controller: EditDuctController | None = None
self._flow_direction_controller: FlowDirectionController | None = None
self._node_configurator: NodeConfiguratorController | None = None
self._hydrant_configurator: HydrantConfiguratorController | None = None
self._connection_point_configurator: (
ConnectionPointConfiguratorController | None
) = None
self._sewer_manhole_configurator: (
SewerManholeConfiguratorController | None
) = None
self._sewer_pumping_station_configurator: (
SewerPumpingStationConfiguratorController | None
) = None
def initGui(self): # noqa: N802 - QGIS plugin API name
self.toolbar = self.iface.addToolBar("EVEL Võrgutööriistad")
self.toolbar.setObjectName(TOOLBAR_OBJECT_NAME)
self.status_action = QAction("EVEL · olek", self.iface.mainWindow())
self.status_action.setObjectName("EVELNetworkStatusAction")
self.status_action.triggered.connect(self.show_diagnostics)
self.status_menu = QMenu(self.iface.mainWindow())
self.status_menu.setObjectName("EVELStatusMenu")
self.status_menu.setToolTipsVisible(True)
self.status_action.setMenu(self.status_menu)
self.toolbar.addAction(self.status_action)
apply_evel_toolbar_light_style(self.toolbar, self.status_menu)
status_button = self.toolbar.widgetForAction(self.status_action)
if isinstance(status_button, QToolButton):
status_button.setObjectName("EVELStatusToolButton")
status_button.setPopupMode(QToolButton.InstantPopup)
status_button.setToolButtonStyle(Qt.ToolButtonTextBesideIcon)
self._connect(self.status_menu.aboutToShow, self._rebuild_status_menu)
self.toolbar.addSeparator()
self.add_duct_action = self._add_tool_action(
"Lisa toru",
"EVELAddDuctAction",
ICON_ADD_DUCT,
)
self.add_duct_action.setCheckable(True)
self.add_duct_menu = QMenu(self.iface.mainWindow())
self.add_duct_menu.setObjectName("EVELAddDuctMenu")
apply_evel_toolbar_light_style(
self.toolbar,
self.add_duct_menu,
)
self.add_duct_action.setMenu(self.add_duct_menu)
add_button = self.toolbar.widgetForAction(self.add_duct_action)
if isinstance(add_button, QToolButton):
add_button.setPopupMode(QToolButton.InstantPopup)
self._add_controller = AddWaterDuctController(
self.iface,
self.add_duct_action,
self.refresh_state,
)
self._gravity_controller = AddGravityDuctController(
self.iface,
self.add_duct_action,
self.refresh_state,
)
self.edit_duct_action = self._add_tool_action(
"Vaata/muuda toru",
"EVELEditDuctAction",
ICON_EDIT_DUCT,
)
self.edit_duct_action.setCheckable(True)
self.edit_duct_action.triggered.connect(self._toggle_edit_duct)
self._edit_duct_controller = EditDuctController(
self.iface,
self.edit_duct_action,
self.refresh_state,
)
self.configure_node_action = self._add_tool_action(
"Konfigureeri sõlm",
"EVELConfigureWaterNodeAction",
ICON_CONFIGURE_NODE,
)
self.configure_node_action.setCheckable(True)
self.configure_node_action.triggered.connect(
self._toggle_configure_node
)
self._node_configurator = NodeConfiguratorController(
self.iface,
self.configure_node_action,
self.refresh_state,
dialog_class=VisualNodeConfiguratorDialog,
)
self.hydrant_action = self._add_tool_action(
"Hüdrant",
"EVELHydrantAction",
ICON_HYDRANT,
)
self.hydrant_action.setCheckable(True)
self.hydrant_action.triggered.connect(self._toggle_hydrant)
self._hydrant_configurator = HydrantConfiguratorController(
self.iface,
self.hydrant_action,
self.refresh_state,
)
self.connection_point_action = self._add_tool_action(
"Liitumispunkt",
"EVELConnectionPointAction",
ICON_CONNECTION_POINT,
)
self.connection_point_action.setCheckable(True)
self.connection_point_action.triggered.connect(
self._toggle_connection_point
)
self._connection_point_configurator = (
ConnectionPointConfiguratorController(
self.iface,
self.connection_point_action,
self.refresh_state,
)
)
self.sewer_manhole_action = self._add_tool_action(
"Kaev / põlv",
"EVELSewerManholeClockAction",
ICON_SEWER_MANHOLE,
)
self.sewer_manhole_action.setCheckable(True)
self.sewer_manhole_action.triggered.connect(
self._toggle_sewer_manhole
)
self._sewer_manhole_configurator = (
SewerManholeConfiguratorController(
self.iface,
self.sewer_manhole_action,
self.refresh_state,
)
)
self.sewer_pumping_station_action = self._add_tool_action(
"Pumpla",
"EVELSewerPumpingStationAction",
ICON_PUMPING_STATION,
)
self.sewer_pumping_station_action.setCheckable(True)
self.sewer_pumping_station_action.triggered.connect(
self._toggle_sewer_pumping_station
)
self._sewer_pumping_station_configurator = (
SewerPumpingStationConfiguratorController(
self.iface,
self.sewer_pumping_station_action,
self.refresh_state,
)
)
self.toolbar.addSeparator()
self.import_action = self._add_tool_action(
"Impordi",
"EVELImportAction",
ICON_IMPORT,
)
self.import_action.triggered.connect(self._open_importer)
self.clear_data_action = self._add_tool_action(
"Tühjenda",
"EVELClearImportDataAction",
ICON_CLEAR_DATA,
)
self.clear_data_action.triggered.connect(self._open_data_clearer)
self.reverse_action = self._add_tool_action(
"Pööra suund",
"EVELReverseWaterDuctAction",
ICON_REVERSE_FLOW,
)
self.reverse_action.setCheckable(True)
self.reverse_action.triggered.connect(
self._toggle_flow_direction
)
self._flow_direction_controller = FlowDirectionController(
self.iface,
self.reverse_action,
self.refresh_state,
)
self.check_action = self._add_tool_action(
"Kontrolli",
"EVELCheckWaterNetworkAction",
ICON_CHECK_NETWORK,
)
self.repair_action = self._add_tool_action(
"Paranda",
"EVELRepairWaterDuctAction",
ICON_REPAIR_NETWORK,
)
for action in self._interactive_tool_actions():
self._connect(action.toggled, self._on_tool_toggled)
project = QgsProject.instance()
self._connect(self.iface.currentLayerChanged, self.refresh_state)
self._connect(project.readProject, self.refresh_state)
self._connect(project.cleared, self.refresh_state)
self._connect(project.layersAdded, self.refresh_state)
self._connect(project.layersRemoved, self.refresh_state)
self._connect(project.transactionModeChanged, self.refresh_state)
self.refresh_state()
def unload(self):
if self._diagnostics_dialog is not None:
self._diagnostics_dialog.close()
self._diagnostics_dialog = None
if self._import_dialog is not None:
self._import_dialog.close()
self._import_dialog = None
if self._clear_data_dialog is not None:
self._clear_data_dialog.close()
self._clear_data_dialog = None
if self._add_controller is not None:
self._add_controller.cancel()
self._add_controller = None
if self._gravity_controller is not None:
self._gravity_controller.cancel()
self._gravity_controller = None
if self._edit_duct_controller is not None:
self._edit_duct_controller.cancel()
self._edit_duct_controller = None
if self._flow_direction_controller is not None:
self._flow_direction_controller.cancel()
self._flow_direction_controller = None
if self._node_configurator is not None:
self._node_configurator.cancel()
self._node_configurator = None
if self._hydrant_configurator is not None:
self._hydrant_configurator.cancel()
self._hydrant_configurator = None
if self._connection_point_configurator is not None:
self._connection_point_configurator.cancel()
self._connection_point_configurator = None
if self._sewer_manhole_configurator is not None:
self._sewer_manhole_configurator.cancel()
self._sewer_manhole_configurator = None
if self._sewer_pumping_station_configurator is not None:
self._sewer_pumping_station_configurator.cancel()
self._sewer_pumping_station_configurator = None
for signal, slot in reversed(self._connections):
try:
signal.disconnect(slot)
except (RuntimeError, TypeError):
pass
self._connections.clear()
if self.toolbar is not None:
self.toolbar.clear()
self.toolbar.deleteLater()
self.toolbar = None
self.status_action = None
self.status_menu = None
self.add_duct_action = None
self.add_duct_menu = None
self.edit_duct_action = None
self.configure_node_action = None
self.hydrant_action = None
self.connection_point_action = None
self.sewer_manhole_action = None
self.sewer_pumping_station_action = None
self.import_action = None
self.clear_data_action = None
self.reverse_action = None
self.check_action = None
self.repair_action = None
self._inspection = None
self._duct_options = ()
self._selected_duct_layer_id = ""
self._sewer_manhole_ready = False
self._hydrant_ready = False
self._connection_point_ready = False
self._sewer_pumping_station_ready = False
self._import_ready = False
self._import_reason = ""
def refresh_state(self, *_args) -> None:
"""Re-evaluate the open project and update toolbar feedback."""
project = QgsProject.instance()
active_layer = self.iface.activeLayer()
try:
self._duct_options = self._duct_catalog.discover(project)
except Exception as error: # pragma: no cover - QGIS runtime guard
self._duct_options = ()
QgsMessageLog.logMessage(
f"Torukihtide kataloogi koostamine ebaõnnestus: {error}",
MESSAGE_TAG,
Qgis.MessageLevel.Critical,
)
try:
self._inspection = self._resolve_project_water_inspection(
project,
active_layer,
)
except Exception as error: # pragma: no cover - QGIS runtime guard
self._inspection = None
QgsMessageLog.logMessage(
f"Käivitusdiagnostika ebaõnnestus: {error}",
MESSAGE_TAG,
Qgis.MessageLevel.Critical,
)
self._sewer_manhole_ready = (
self._sewer_manhole_inspector.is_available(project)
)
self._hydrant_ready = self._hydrant_inspector.is_available(project)
self._connection_point_ready = (
self._connection_point_inspector.is_available(project)
)
self._sewer_pumping_station_ready = (
self._sewer_pumping_station_inspector.is_available(project)
)
self._import_ready, self._import_reason = (
self._import_target_inspector.is_available(project)
)
self._rebuild_add_duct_menu()
self._update_tool_actions()
self._update_status_action()
def _resolve_project_water_inspection(
self,
project: QgsProject,
active_layer,
) -> ProjectInspection:
"""Resolve water topology from a pipe layer, not any active display layer."""
water_options = tuple(
option
for option in self._duct_options
if option.workflow is DuctWorkflow.WATER_TOPOLOGY
and option.inspection is not None
)
active_id = active_layer.id() if active_layer is not None else ""
active_option = next(
(
option
for option in water_options
if option.layer.id() == active_id
),
None,
)
if active_option is not None:
return active_option.inspection
if self._is_usable_water_edge_candidate(active_layer):
return self._inspector.inspect(project, active_layer)
active_network_id = self._layer_default_int(
active_layer,
"NETWORK_ID",
)
matching_option = next(
(
option
for option in water_options
if option.enabled
and option.network_id == active_network_id
),
None,
)
if matching_option is not None:
return matching_option.inspection
enabled_option = next(
(option for option in water_options if option.enabled),
None,
)
if enabled_option is not None:
return enabled_option.inspection
option_by_layer_id = {
option.layer.id(): option
for option in water_options
}
first_project_inspection = None
for layer in project.mapLayers().values():
if not isinstance(layer, QgsVectorLayer):
continue
if not self._is_usable_water_edge_candidate(layer):
continue
option = option_by_layer_id.get(layer.id())
candidate = (
option.inspection
if option is not None
else self._inspector.inspect(project, layer)
)
if first_project_inspection is None:
first_project_inspection = candidate
if candidate.can_add_water_duct:
return candidate
if water_options:
return water_options[0].inspection
if first_project_inspection is not None:
return first_project_inspection
return self._inspector.inspect(project, None)
def show_diagnostics(self, *_args) -> None:
"""Open or refresh the copyable detailed diagnostics window."""
self.refresh_state()
report = self._diagnostics_report()
status_text = self._status_headline()
status_icon = (
self.status_action.icon()
if self.status_action is not None
else catalog_icon(ICON_ERROR)
)
dialog = self._diagnostics_dialog
if dialog is not None:
try:
dialog.set_report(report, status_text, status_icon)
dialog.show()
dialog.raise_()
dialog.activateWindow()
return
except RuntimeError:
self._diagnostics_dialog = None
dialog = DiagnosticsDialog(
report,
status_text,
status_icon,
parent=self.iface.mainWindow(),
)
dialog.destroyed.connect(self._diagnostics_dialog_reference)
self._diagnostics_dialog = dialog
dialog.show()
dialog.raise_()
dialog.activateWindow()
has_error, has_warning, _message = self._status_details()
if has_error:
level = Qgis.MessageLevel.Critical
elif has_warning:
level = Qgis.MessageLevel.Warning
else:
level = Qgis.MessageLevel.Success
QgsMessageLog.logMessage(report, MESSAGE_TAG, level)
def _diagnostics_dialog_reference(self, *_args) -> None:
self._diagnostics_dialog = None
def _add_tool_action(
self,
text: str,
object_name: str,
icon_name: str,
) -> QAction:
action = QAction(text, self.iface.mainWindow())
set_catalog_icon(action, icon_name)
action.setObjectName(object_name)
action.setEnabled(False)
action.setToolTip(f"{text}: tööriist on arendamisel.")
self.toolbar.addAction(action)
return action
def _update_status_action(self) -> None:
if self.status_action is None:
return
has_error, has_warning, message = self._status_details()
if has_error:
icon = catalog_icon(ICON_ERROR)
fallback = QStyle.SP_MessageBoxCritical
elif has_warning:
icon = catalog_icon(ICON_STATUS_WARNING)
fallback = QStyle.SP_MessageBoxWarning
else:
icon = catalog_icon(ICON_STATUS_OK)
fallback = QStyle.SP_DialogApplyButton
if icon.isNull():
icon = QApplication.style().standardIcon(fallback)
self.status_action.setIcon(icon)
layer_label = self._active_layer_label()
tool_name, guidance, compact_guidance = self._active_tool_guidance()
if tool_name is not None:
summary = (
f"{tool_name} · {self._ellipsize(layer_label, 26)} — "
f"{compact_guidance}"
)
elif has_error:
summary = (
f"EVEL · {self._ellipsize(layer_label, 30)} — "
"vajab tähelepanu"
)
elif has_warning:
summary = (
f"EVEL · {self._ellipsize(layer_label, 30)} — "
"kontrolli hoiatusi"
)
else:
summary = f"EVEL · {self._ellipsize(layer_label, 34)} — vali tööriist"
self.status_action.setText(summary)
self.status_action.setToolTip(
"EVEL Võrgutööriistad\n"
f"Aktiivne kiht: {layer_label}\n"
f"Tööriist: {tool_name or 'ükski kaarditööriist pole aktiivne'}\n"
f"Järgmine samm: {guidance}\n"
f"Olek: {message}\n"
"Klõpsa olekupaneeli avamiseks."
)
self._rebuild_status_menu()
self._update_open_diagnostics_dialog()
def _status_details(self) -> tuple[bool, bool, str]:
"""Return the current project severity and its concise explanation."""
active_option = self._active_duct_option()
inspection = self._inspection
if active_option is not None:
has_error = not active_option.enabled
has_warning = bool(
active_option.inspection
and active_option.inspection.warnings
and not has_error
)
message = (
f"Aktiivne torukiht „{active_option.label}“ on kasutatav."
if active_option.enabled
else active_option.reason
)
return has_error, has_warning, message
usable = self._has_usable_workflow()
if not usable:
message = (
inspection.short_message()
if inspection is not None
else "Käivitusdiagnostika ebaõnnestus."
)
return True, False, message
if inspection is not None and inspection.errors:
return (
False,
True,
"Osa veevõrgu töövoogudest pole kasutatav: "
+ inspection.short_message(),
)
if inspection is not None and inspection.warnings:
return False, True, inspection.short_message()
active_layer = self.iface.activeLayer()
if active_layer is None:
message = "EVEL-i tööriistad on kasutatavad; aktiivset kihti pole."
elif self._is_evel_project_layer(active_layer):
message = (
f"Aktiivne EVEL-i kiht „{self._active_layer_label()}“; "
"tööriistad on kasutatavad."
)
else:
message = (
"EVEL-i tööriistad on kasutatavad; aktiivne kiht "
f"„{self._active_layer_label()}“ ei ole EVEL-i projektikiht."
)
return False, False, message
def _has_usable_workflow(self) -> bool:
return bool(
any(option.enabled for option in self._duct_options)
or (
self._inspection is not None
and self._inspection.can_add_water_duct
)
or self._hydrant_ready
or self._connection_point_ready
or self._sewer_manhole_ready
or self._sewer_pumping_station_ready
or self._import_ready
)
@staticmethod
def _is_water_edge_layer(layer) -> bool:
if layer is None:
return False
role = str(layer.customProperty("evel_topology_role", "")).casefold()
table = str(layer.customProperty("evel_project_table", "")).casefold()
return role == "water_edge" or table == "sn_water_duct"
@classmethod
def _is_usable_water_edge_candidate(cls, layer) -> bool:
if not cls._is_water_edge_layer(layer):
return False
component_key = str(
layer.customProperty("evel_preview_checkbox", "")
).strip().casefold()
if component_key == "cbwaterabandoned":
return False
return "REMOVAL_YEAR" not in layer.subsetString().upper()
@staticmethod
def _is_evel_project_layer(layer) -> bool:
if layer is None:
return False
value = layer.customProperty("evel_project_layer", False)
if isinstance(value, bool):
return value
return str(value).strip().casefold() in {"1", "true", "yes", "on"}
@staticmethod
def _layer_default_int(layer, field_name: str) -> int | None:
if not isinstance(layer, QgsVectorLayer):
return None
field_index = layer.fields().lookupField(field_name)
if field_index < 0:
return None
expression = layer.defaultValueDefinition(
field_index
).expression().strip()
if not expression:
return None
try:
return int(expression.strip("'\""))
except (TypeError, ValueError):
return None
def _status_headline(self) -> str:
has_error, has_warning, _message = self._status_details()
if has_error:
return "EVEL vajab tähelepanu"
if has_warning:
return "EVEL on kasutatav hoiatustega"
return "EVEL on valmis"
def _tool_groups(self):
"""Return toolbar actions grouped by the user's network workflow."""
return (
(
"Torud",
(
self.add_duct_action,
self.edit_duct_action,
self.reverse_action,
),
),
(
"Sõlmed ja rajatised",
(
self.configure_node_action,
self.hydrant_action,
self.connection_point_action,
self.sewer_manhole_action,
self.sewer_pumping_station_action,
),
),
(
"Andmed",
(self.import_action, self.clear_data_action),
),
(
"Kontroll",
(self.check_action, self.repair_action),
),
)
def _interactive_tool_actions(self) -> tuple[QAction, ...]:
"""Return actions which represent an active map interaction."""
return tuple(
action
for action in (
self.add_duct_action,
self.edit_duct_action,
self.configure_node_action,
self.hydrant_action,
self.connection_point_action,
self.sewer_manhole_action,
self.sewer_pumping_station_action,
self.reverse_action,
)
if action is not None
)
def _active_layer_label(self) -> str:
layer = self.iface.activeLayer()
if layer is None:
return "kiht puudub"
try:
return layer.name() or "nimetu kiht"
except RuntimeError:
return "kiht pole enam saadaval"
def _active_tool_guidance(self) -> tuple[str | None, str, str]:
guidance_by_action = (
(
self.add_duct_action,
"Klõpsa kaardil toru alguspunktil ja jätka joonestamist.",
"klõpsa alguspunktil",
),
(
self.edit_duct_action,
"Klõpsa kaardil olemasoleval EVEL-i torul.",
"klõpsa torul",
),
(
self.configure_node_action,
"Klõpsa kaardil veesõlmel, mida soovid konfigureerida.",
"klõpsa veesõlmel",
),
(
self.hydrant_action,
"Klõpsa hüdrandil, veesõlmel või veetorul.",
"klõpsa objektil",
),
(
self.connection_point_action,
"Klõpsa liitumispunktil või vee-/kanalisatsioonisõlmel.",
"klõpsa punktil või sõlmel",
),
(
self.sewer_manhole_action,
"Klõpsa isevoolsel torul või kanalisatsioonisõlmel.",
"klõpsa torul või sõlmel",
),
(
self.sewer_pumping_station_action,
"Klõpsa kanalisatsioonitorul või -sõlmel.",
"klõpsa torul või sõlmel",
),
(
self.reverse_action,
"Klõpsa torul voolusuuna määramiseks või pööramiseks.",
"klõpsa torul",
),
)
for action, guidance, compact_guidance in guidance_by_action:
if action is not None and action.isChecked():
return action.text(), guidance, compact_guidance
ready = any(
action is not None and action.isEnabled()
for _group, actions in self._tool_groups()
for action in actions
)
if ready:
return None, "Vali sobiv tööriist.", "vali tööriist"
if self.iface.activeLayer() is None:
return (
None,
"Ava EVEL-i projekt või vali toetatud võrgukiht.",
"vali võrgukiht",
)
if self._inspection is not None:
return (
None,
self._inspection.short_message(),
"kontrolli projekti",
)
return None, "Kontrolli projekti valmisolekut.", "kontrolli projekti"
@staticmethod
def _ellipsize(text: str, limit: int) -> str:
if len(text) <= limit:
return text
return text[: max(1, limit - 1)].rstrip() + "…"
@staticmethod
def _tool_reason(action: QAction) -> str:
lines = [line.strip() for line in action.toolTip().splitlines()]
lines = [line for line in lines if line]
if lines and lines[0].rstrip(":") == action.text().rstrip(":"):
lines = lines[1:]
return " ".join(lines) or (
"Tööriist on kasutatav."
if action.isEnabled()
else "Tööriist ei ole praeguses projektikontekstis kasutatav."
)
def _diagnostics_report(self) -> str:
"""Build a complete plain-text snapshot without exposing data sources."""
project = QgsProject.instance()
has_error, has_warning, message = self._status_details()
tool_name, guidance, _compact = self._active_tool_guidance()
project_title = project.title().strip() or "pealkiri puudub"
project_file = project.fileName().strip() or "salvestamata projekt"
severity = (
"VIGA" if has_error else "HOIATUS" if has_warning else "VALMIS"
)
lines = [
"EVEL VÕRGUTÖÖRIISTADE DIAGNOSTIKA",
"=================================",
f"Olek: {severity} — {self._status_headline()}",
f"Kokkuvõte: {message}",
f"Projekt: {project_title}",
f"Projektifail: {project_file}",
f"Aktiivne kiht: {self._active_layer_label()}",
(
"Aktiivne tööriist: "
+ (tool_name or "ükski kaarditööriist pole aktiivne")
),
f"Järgmine samm: {guidance}",
"",
"PROJEKTIDIAGNOSTIKA",
"--------------------",
]
inspection = self._inspection
if inspection is None:
lines.append("Käivitusdiagnostikat ei õnnestunud koostada.")
elif not inspection.diagnostics:
lines.append("Diagnostikakirjeid pole.")
else:
level_labels = {
"error": "VIGA",
"warning": "HOIATUS",
"info": "INFO",
}
for item in inspection.diagnostics:
level_label = level_labels.get(
item.level.value,
item.level.value.upper(),
)
lines.append(f"[{level_label}] {item.code}")
lines.append(f" {item.message}")
if item.layer_id:
lines.append(f" Kihi ID: {item.layer_id}")
lines.append("")
if lines[-1] == "":
lines.pop()
lines.extend(
[
"",
"TORUKIHTIDE VALIKUD",
"-------------------",
]
)
if not self._duct_options:
lines.append("Toetatud torukihte ei leitud.")
else:
workflow_labels = {
DuctWorkflow.WATER_TOPOLOGY: "vee topoloogia",
DuctWorkflow.GRAVITY_GEOMETRY: "isevoolne geomeetria",
}
for option in self._duct_options:
state = "VALMIS" if option.enabled else "POLE SAADAVAL"
lines.append(f"[{state}] {option.label}")
lines.append(
" Töövoog: "
+ workflow_labels.get(option.workflow, option.workflow.value)
)
lines.append(f" Võrgu ID: {option.network_id}")
lines.append(f" Võrgutüübi ID: {option.nettype_id}")
lines.append(f" Põhjus: {option.reason or '—'}")
lines.extend(
[
"",
"TÖÖRIISTADE VALMISOLEK",
"----------------------",
]
)
for group_name, actions in self._tool_groups():
lines.append(group_name.upper())
for action in actions:
if action is None:
continue
state = "VALMIS" if action.isEnabled() else "POLE SAADAVAL"
lines.append(f" [{state}] {action.text()}")
lines.append(f" {self._tool_reason(action)}")
return "\n".join(lines).rstrip() + "\n"
def _update_open_diagnostics_dialog(self) -> None:
dialog = self._diagnostics_dialog
if dialog is None or self.status_action is None:
return
try:
dialog.set_report(
self._diagnostics_report(),
self._status_headline(),
self.status_action.icon(),
)
except RuntimeError:
self._diagnostics_dialog = None
def _rebuild_status_menu(self) -> None:
menu = self.status_menu