Repository navigation
Expand file tree
/
Copy pathgraph_canvas.py
More file actions
5815 lines (5279 loc) · 261 KB
/
Copy pathgraph_canvas.py
File metadata and controls
5815 lines (5279 loc) · 261 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
# SPDX-License-Identifier: BSD-3-Clause
"""Hardware-accelerated GTK4 Graph Canvas using Gtk.Snapshot and Gsk.PathBuilder."""
from __future__ import annotations
import math
import os
import subprocess
from typing import Any, Callable, Dict, List, Optional, Set, Tuple
import gi
gi.require_version("Gtk", "4.0")
gi.require_version("Gsk", "4.0")
gi.require_version("Graphene", "1.0")
from gi.repository import Gdk, Gio, GLib, GObject, Graphene, Gsk, Gtk, Pango
from .layout import (
CONTAINER_GAP_X,
CTRL_GROUP_HDR,
CTRL_GROUP_PAD,
CTRL_H_GAP,
CTRL_TOP_GAP,
H_GAP,
_assign_edge_ports,
_compute_node_geometry,
_is_node_capture,
_position_testbench_io_nodes,
layout_graph,
update_container_bounds_from_nodes,
)
from .model import (
ConfigNode,
GraphEdge,
GraphHistoryEntry,
GraphNode,
GraphPort,
GraphViewModel,
PipelineContainer,
UndoRedoManager,
debug_log_action,
)
from .parser import Topology2Workspace
def rgba(r: float, g: float, b: float, a: float = 1.0) -> Gdk.RGBA:
c = Gdk.RGBA()
c.red = r
c.green = g
c.blue = b
c.alpha = a
return c
# Color palette by node category
CATEGORY_COLORS: Dict[str, Tuple[Gdk.RGBA, Gdk.RGBA]] = {
"host": (rgba(0.14, 0.42, 0.78, 1.0), rgba(0.11, 0.16, 0.24, 0.96)),
"widget": (rgba(0.12, 0.56, 0.52, 1.0), rgba(0.11, 0.19, 0.20, 0.96)),
"mix": (rgba(0.78, 0.43, 0.12, 1.0), rgba(0.22, 0.16, 0.11, 0.96)),
"dai": (rgba(0.20, 0.62, 0.28, 1.0), rgba(0.11, 0.20, 0.14, 0.96)),
"pcm": (rgba(0.45, 0.32, 0.78, 1.0), rgba(0.16, 0.13, 0.24, 0.96)),
"control": (rgba(0.64, 0.30, 0.56, 1.0), rgba(0.20, 0.13, 0.19, 0.96)),
"control_mixer": (rgba(0.62, 0.26, 0.88, 1.0), rgba(0.18, 0.12, 0.25, 0.96)),
"control_switch": (rgba(0.86, 0.56, 0.12, 1.0), rgba(0.24, 0.18, 0.10, 0.96)),
"control_bytes": (rgba(0.12, 0.66, 0.84, 1.0), rgba(0.10, 0.19, 0.24, 0.96)),
"control_enum": (rgba(0.86, 0.24, 0.42, 1.0), rgba(0.24, 0.11, 0.16, 0.96)),
"base": (rgba(0.36, 0.44, 0.54, 1.0), rgba(0.14, 0.16, 0.20, 0.96)),
"pipeline": (rgba(0.25, 0.48, 0.72, 1.0), rgba(0.12, 0.17, 0.23, 0.96)),
"testbench_io": (rgba(0.15, 0.62, 0.42, 1.0), rgba(0.11, 0.18, 0.16, 0.97)),
"pin_fmt_in": (rgba(0.11, 0.46, 0.68, 1.0), rgba(0.08, 0.14, 0.21, 0.96)),
"pin_fmt_out": (rgba(0.13, 0.54, 0.42, 1.0), rgba(0.08, 0.16, 0.14, 0.96)),
}
BG_COLOR = rgba(0.08, 0.09, 0.12, 1.0)
GRID_COLOR = rgba(0.16, 0.18, 0.23, 1.0)
CONTAINER_FILL_PB = rgba(0.14, 0.24, 0.38, 0.22)
CONTAINER_FILL_CAP = rgba(0.14, 0.36, 0.26, 0.22)
CONTAINER_BORDER_PB = rgba(0.28, 0.52, 0.82, 0.48)
CONTAINER_BORDER_CAP = rgba(0.28, 0.72, 0.48, 0.48)
NODE_BORDER_NORMAL = rgba(0.30, 0.35, 0.44, 0.90)
NODE_BORDER_SELECTED = rgba(0.35, 0.78, 1.00, 1.00)
NODE_BORDER_PROBED = rgba(0.06, 0.73, 0.51, 0.98)
NODE_BORDER_POWERED = rgba(0.22, 0.74, 0.97, 0.72)
NODE_SHADOW_SELECTED = rgba(0.20, 0.68, 1.00, 0.45)
TAP_BG_ACTIVE = rgba(0.06, 0.73, 0.51, 0.95)
TAP_BG_IDLE = rgba(0.06, 0.09, 0.16, 0.50)
TAP_FG_IDLE = rgba(0.80, 0.84, 0.88, 0.90)
TELEM_SUB_FG = rgba(0.49, 0.83, 0.99, 0.95)
TEXT_WHITE = rgba(0.95, 0.97, 1.00, 1.0)
TEXT_MUTED = rgba(0.68, 0.74, 0.82, 1.0)
BADGE_BG = rgba(0.18, 0.22, 0.30, 0.95)
BADGE_FG = rgba(0.78, 0.88, 1.00, 1.0)
PORT_IN_COLOR = rgba(0.32, 0.82, 0.96, 1.0)
PORT_OUT_COLOR = rgba(0.98, 0.68, 0.26, 1.0)
PORT_HOVER_COLOR = rgba(1.0, 0.95, 0.40, 1.0)
EDGE_INTRA_COLOR = rgba(0.52, 0.78, 0.96, 0.92)
EDGE_INTER_COLOR = rgba(0.98, 0.68, 0.28, 0.95)
EDGE_SELECTED_COLOR = rgba(0.30, 0.95, 0.65, 1.0)
WIRE_DRAG_COLOR = rgba(1.0, 0.82, 0.32, 0.95)
DRAG_PAUSE_DELAY_MS = 220
class DropOutcomePreview:
"""Visual preview of the outcome if the currently dragged object is dropped at (sx, sy)."""
def __init__(
self,
action_kind: str, # "join_pipeline" | "create_pipeline" | "reposition"
headline: str,
detail: str,
sx: float,
sy: float,
wx: float,
wy: float,
target_pid: Optional[int] = None,
ghost_container: Optional[Tuple[float, float, float, float, str, bool]] = None,
ghost_node: Optional[Tuple[float, float, float, float, str, str]] = None,
ghost_wires: Optional[List[Tuple[float, float, float, float, bool]]] = None,
spliced_edge_id: Optional[str] = None,
) -> None:
self.action_kind = action_kind
self.headline = headline
self.detail = detail
self.sx = sx
self.sy = sy
self.wx = wx
self.wy = wy
self.target_pid = target_pid
self.ghost_container = ghost_container
self.ghost_node = ghost_node
self.ghost_wires = ghost_wires or []
self.spliced_edge_id = spliced_edge_id
class TopologyGraphCanvas(Gtk.Widget):
"""Custom GTK4 Widget rendering interactive Topology2 graphs via Gtk.Snapshot."""
__gtype_name__ = "TopologyGraphCanvas"
_active_drag_payload: Optional[str] = None
_clipboard_nodes: List[GraphNode] = []
_clipboard_containers: List[PipelineContainer] = []
_clipboard_edges: List[GraphEdge] = []
_clipboard_paste_count: int = 0
def __init__(
self,
on_selection_changed: Optional[Callable[[Optional[str], Optional[ConfigNode], str], None]] = None,
on_graph_modified: Optional[Callable[[], None]] = None,
on_history_changed: Optional[Callable[[], None]] = None,
on_kcontrol_changed: Optional[Callable[[GraphNode], None]] = None,
on_probe_tap_toggled: Optional[Callable[[Optional[str], int, str], None]] = None,
on_testbench_io_changed: Optional[Callable[[List[int]], None]] = None,
on_view_source_requested: Optional[Callable[[str, str, Optional[str], Optional[str]], None]] = None,
on_violation_bang_clicked: Optional[Callable[[str, Dict[str, Any]], None]] = None,
):
super().__init__()
self.set_hexpand(True)
self.set_vexpand(True)
self.set_focusable(True)
self.set_overflow(Gtk.Overflow.HIDDEN)
self.on_selection_changed = on_selection_changed
self.on_graph_modified = on_graph_modified
self.on_kcontrol_changed = on_kcontrol_changed
self.on_probe_tap_toggled = on_probe_tap_toggled
self.on_testbench_io_changed = on_testbench_io_changed
self.on_view_source_requested = on_view_source_requested
self.on_violation_bang_clicked = on_violation_bang_clicked
self._active_context_popover: Optional[Gtk.Popover] = None
self.live_node_telemetry: Dict[str, Dict[str, Any]] = {}
self.violating_edges: Dict[str, Dict[str, Any]] = {}
self.violating_ports: Set[Tuple[str, str, str]] = set()
self.violating_port_info: Dict[Tuple[str, str, str], Dict[str, Any]] = {}
self.ignore_tick0_underrun: bool = True
self.active_probe_node_id: Optional[str] = None
self.history = UndoRedoManager(on_history_changed=on_history_changed)
self._suppress_auto_history: bool = False
self._pending_drag_history_entry: Optional[GraphHistoryEntry] = None
self.workspace: Optional[Topology2Workspace] = None
self.vm: Optional[GraphViewModel] = None
# Camera transform
self.pan_x: float = 24.0
self.pan_y: float = 24.0
self.zoom: float = 1.0
self._is_fitted: bool = True
self._last_canvas_size: Tuple[int, int] = (0, 0)
self._pointer_pos: Optional[Tuple[float, float]] = None
# Selection state
self.selected_node_id: Optional[str] = None
self.selected_node_ids: Set[str] = set()
self.selected_edge_id: Optional[str] = None
self.selected_container_id: Optional[int] = None
self.selected_container_ids: Set[int] = set()
self.hovered_port: Optional[Tuple[str, str, str]] = None # (node_id, port_id, direction)
self.hovered_warning_pid: Optional[int] = None
# Interaction state
self._drag_mode: str = "none" # "none", "pan", "node", "container", "wire"
self._right_drag_mode: str = "none" # "none", "box_select", "pan", "objects"
self._selection_box_world: Optional[Tuple[float, float, float, float]] = None
self._box_select_additive: bool = False
self._box_select_initial_nodes: Set[str] = set()
self._box_select_initial_containers: Set[int] = set()
self._left_click_kept_multisel: bool = False
self._drag_start_screen: Tuple[float, float] = (0.0, 0.0)
self._drag_start_world: Tuple[float, float] = (0.0, 0.0)
self._drag_start_pan: Tuple[float, float] = (0.0, 0.0)
self._drag_node_initial: Tuple[float, float] = (0.0, 0.0)
self._drag_container_id: Optional[int] = None
self._drag_container_initial: Tuple[float, float] = (0.0, 0.0)
self._drag_children_initial: Dict[str, Tuple[float, float]] = {}
self._right_drag_nodes_initial: Dict[str, Tuple[float, float]] = {}
self._right_drag_containers_initial: Dict[int, Tuple[float, float]] = {}
self._wire_source: Optional[Tuple[str, str, float, float]] = None # (node_id, port_id, wx, wy)
self._wire_cursor_world: Tuple[float, float] = (0.0, 0.0)
# Drag-and-drop & drag-pause outcome preview state
self._dnd_payload: Optional[str] = None
self._dnd_screen_pos: Optional[Tuple[float, float]] = None
self._drag_pause_timer_id: Optional[int] = None
self.drop_preview: Optional[DropOutcomePreview] = None
# Compilation diagnostic highlight state (set when double-clicking an error/warning)
self.diag_highlight_node_id: Optional[str] = None
self.diag_highlight_container_id: Optional[int] = None
self.diag_highlight_edge_id: Optional[str] = None
self.diag_banner_text: Optional[str] = None
self.diag_banner_severity: str = "error"
# Pango layout cache: key -> Pango.Layout
self._layout_cache: Dict[Tuple[str, int, bool], Pango.Layout] = {}
self._setup_controllers()
def _setup_controllers(self) -> None:
# Primary left-click / drag gesture
click = Gtk.GestureClick.new()
click.set_button(1)
click.connect("pressed", self._on_left_pressed)
self.add_controller(click)
drag = Gtk.GestureDrag.new()
drag.set_button(1)
drag.connect("drag-begin", self._on_drag_begin)
drag.connect("drag-update", self._on_drag_update)
drag.connect("drag-end", self._on_drag_end)
self.add_controller(drag)
# Middle button (button 2) pan gesture
mid_drag = Gtk.GestureDrag.new()
mid_drag.set_button(2)
mid_drag.connect("drag-begin", self._on_pan_begin)
mid_drag.connect("drag-update", self._on_pan_update)
mid_drag.connect("drag-end", self._on_pan_end)
self.add_controller(mid_drag)
# Right button (button 3) click + drag gesture:
# Changes pointer cursor on hold and drags selected object(s), or pans whole view if none selected
right_click = Gtk.GestureClick.new()
right_click.set_button(3)
right_click.connect("pressed", self._on_right_pressed)
right_click.connect("released", self._on_right_released)
right_click.connect("stopped", lambda _g: self.set_cursor(None))
self.add_controller(right_click)
right_drag = Gtk.GestureDrag.new()
right_drag.set_button(3)
right_drag.connect("drag-begin", self._on_right_drag_begin)
right_drag.connect("drag-update", self._on_right_drag_update)
right_drag.connect("drag-end", self._on_right_drag_end)
self.add_controller(right_drag)
# Motion controller for cursor tracking (pointer-centered zoom) & port hover highlight
motion = Gtk.EventControllerMotion.new()
motion.connect("enter", self._on_motion_enter)
motion.connect("motion", self._on_motion)
self.add_controller(motion)
# Scroll controller for smooth cursor-centered zoom
scroll = Gtk.EventControllerScroll.new(Gtk.EventControllerScrollFlags.VERTICAL)
scroll.connect("scroll", self._on_scroll)
self.add_controller(scroll)
# Key controller for Delete, Fit (F), Auto-layout (L)
key_ctrl = Gtk.EventControllerKey.new()
key_ctrl.connect("key-pressed", self._on_key_pressed)
self.add_controller(key_ctrl)
# DropTarget for dragging Processing Modules or Pipelines from the Left Pane
drop_target = Gtk.DropTarget.new(GObject.TYPE_STRING, Gdk.DragAction.COPY)
drop_target.set_preload(True)
drop_target.connect("enter", self._on_dnd_enter)
drop_target.connect("motion", self._on_dnd_motion)
drop_target.connect("leave", self._on_dnd_leave)
drop_target.connect("drop", self._on_drop_item)
self.add_controller(drop_target)
def _has_selected_objects(self) -> bool:
if not self.vm:
return False
if self.selected_node_id and self.selected_node_id in self.vm.nodes:
return True
if any(nid in self.vm.nodes for nid in self.selected_node_ids):
return True
if self.selected_container_id is not None and self.selected_container_id in self.vm.containers:
return True
if any(pid in self.vm.containers for pid in self.selected_container_ids):
return True
return False
def _has_multi_selection(self) -> bool:
if not self.vm:
return False
valid_nids = [nid for nid in self.selected_node_ids if nid in self.vm.nodes]
valid_pids = [pid for pid in self.selected_container_ids if pid in self.vm.containers]
return len(valid_nids) > 1 or len(valid_pids) > 1 or (len(valid_nids) >= 1 and len(valid_pids) >= 1)
def _get_selection_bounds_world(self) -> Optional[Tuple[float, float, float, float]]:
"""Return (min_x, min_y, max_x, max_y) in world space for all currently selected objects."""
if not self.vm:
return None
sel_nids: Set[str] = {nid for nid in self.selected_node_ids if nid in self.vm.nodes}
if self.selected_node_id and self.selected_node_id in self.vm.nodes:
sel_nids.add(self.selected_node_id)
sel_pids: Set[int] = {pid for pid in self.selected_container_ids if pid in self.vm.containers}
if self.selected_container_id is not None and self.selected_container_id in self.vm.containers:
sel_pids.add(self.selected_container_id)
for pid in sel_pids:
for n in self.vm.nodes.values():
if n.pipeline_id == pid:
sel_nids.add(n.id)
all_nids = set(sel_nids)
for cid, cnode in self.vm.nodes.items():
if cnode.parent_node_id and cnode.parent_node_id in sel_nids:
all_nids.add(cid)
min_x = float("inf")
min_y = float("inf")
max_x = float("-inf")
max_y = float("-inf")
for pid in sel_pids:
cont = self.vm.containers[pid]
min_x = min(min_x, cont.x)
min_y = min(min_y, cont.y)
max_x = max(max_x, cont.x + cont.width)
max_y = max(max_y, cont.y + cont.height)
for nid in all_nids:
n = self.vm.nodes[nid]
min_x = min(min_x, n.x)
min_y = min(min_y, n.y)
max_x = max(max_x, n.x + n.width)
max_y = max(max_y, n.y + n.height)
if min_x == float("inf"):
return None
return (min_x, min_y, max_x, max_y)
def _is_point_in_current_selection(self, wx: float, wy: float) -> bool:
"""Return True if world point (wx, wy) hits a selected node/container or lies inside a multi-selection group box."""
if not self.vm or not self._has_selected_objects():
return False
nid = self._hit_test_node(wx, wy)
if nid and nid in self.vm.nodes:
node = self.vm.nodes[nid]
if nid in self.selected_node_ids or nid == self.selected_node_id:
return True
if node.parent_node_id and (
node.parent_node_id in self.selected_node_ids or node.parent_node_id == self.selected_node_id
):
return True
if node.pipeline_id is not None and (
node.pipeline_id in self.selected_container_ids or node.pipeline_id == self.selected_container_id
):
return True
pid = self._hit_test_container(wx, wy)
if pid is not None:
if pid in self.selected_container_ids or pid == self.selected_container_id:
return True
if any(
snid in self.vm.nodes and self.vm.nodes[snid].pipeline_id == pid
for snid in self.selected_node_ids
):
return True
if self._has_multi_selection():
bounds = self._get_selection_bounds_world()
if bounds is not None:
bx0, by0, bx1, by1 = bounds
pad = 8.0
if (bx0 - pad) <= wx <= (bx1 + pad) and (by0 - pad) <= wy <= (by1 + pad):
return True
return False
def clear_diagnostic_highlights(self) -> None:
self.diag_highlight_node_id = None
self.diag_highlight_container_id = None
self.diag_highlight_edge_id = None
self.diag_banner_text = None
self.queue_draw()
def set_ignore_tick0_underrun(self, ignore: bool) -> None:
self.ignore_tick0_underrun = bool(ignore)
self.queue_draw()
def set_live_telemetry_overlay(self, telem: Optional[Any]) -> None:
"""Populate live node telemetry, DAPM power badges, and violation status from TestbenchTelemetry."""
self.live_node_telemetry.clear()
self.violating_edges.clear()
self.violating_ports.clear()
self.violating_port_info.clear()
if telem is None or not self.vm:
self.queue_draw()
return
comps = getattr(telem, "components", []) or []
dapms = getattr(telem, "dapm_nodes", []) or []
pipes = getattr(telem, "pipelines", []) or []
cores = getattr(telem, "cores", []) or []
pipe_by_id = {int(getattr(p, "pipeline_id", -1)): p for p in pipes}
core_by_id = {int(getattr(c, "core_id", -1)): c for c in cores}
any_pipe_cpc_over: Dict[int, bool] = {}
max_pipe_peak_cyc: Dict[int, int] = {}
for c in comps:
pid_c = int(getattr(c, "pipeline_id", 0) or 0)
pk_c = int(getattr(c, "peak_cycles", 0) or 0)
eff_c = int(getattr(c, "effective_cpc", 0) or 0)
cpcv_c = int(getattr(c, "cpc_violations", 0) or 0)
if cpcv_c > 0 or (eff_c > 0 and pk_c > eff_c):
any_pipe_cpc_over[pid_c] = True
max_pipe_peak_cyc[pid_c] = max(max_pipe_peak_cyc.get(pid_c, 0), pk_c)
for nid, node in self.vm.nodes.items():
if node.class_category in ("Control", "TestbenchIO", "PinFormat"):
continue
matched_comp = None
for c in comps:
wname = getattr(c, "widget_name", "") or ""
if not wname:
continue
if wname == nid or wname == node.title or nid in wname or wname in nid:
matched_comp = c
break
if node.pipeline_id is not None and wname.startswith(f"{node.class_name}.{node.pipeline_id}."):
matched_comp = c
break
matched_dapm = None
for d in dapms:
dname = (d.get("name", "") if isinstance(d, dict) else getattr(d, "name", "")) or ""
if not dname:
continue
if dname == nid or dname == node.title or nid in dname or dname in nid:
matched_dapm = d
break
if matched_comp or matched_dapm:
d_nid = matched_dapm.get("node_id", 0) if isinstance(matched_dapm, dict) else getattr(matched_dapm, "node_id", 0)
d_name = matched_dapm.get("name", "") if isinstance(matched_dapm, dict) else getattr(matched_dapm, "name", "")
d_pwr = matched_dapm.get("power", 1) if isinstance(matched_dapm, dict) else getattr(matched_dapm, "power", 1)
cpc_v = int(getattr(matched_comp, "cpc_violations", 0) or 0) if matched_comp else 0
eff_cpc = int(getattr(matched_comp, "effective_cpc", 0) or 0) if matched_comp else 0
avg_cyc = int(getattr(matched_comp, "avg_cycles", 0) or 0) if matched_comp else 0
pk_cyc = int(getattr(matched_comp, "peak_cycles", 0) or 0) if matched_comp else 0
iters = int(getattr(matched_comp, "iterations", 0) or 0) if matched_comp else 0
ibs = int(getattr(matched_comp, "ibs", 0) or 0) if matched_comp else 0
obs = int(getattr(matched_comp, "obs", 0) or 0) if matched_comp else 0
pid_val = int(getattr(matched_comp, "pipeline_id", node.pipeline_id or 0)) if matched_comp else int(node.pipeline_id or 0)
cid_val = int(getattr(matched_comp, "core_id", 0)) if matched_comp else 0
p_obj = pipe_by_id.get(pid_val)
raw_pipe_xruns = int(getattr(p_obj, "xruns", getattr(p_obj, "xrun_count", 0)) or 0) if p_obj else 0
c_obj = core_by_id.get(cid_val)
raw_core_overruns = int(getattr(c_obj, "overruns", getattr(c_obj, "ll_deadline_violations", 0)) or 0) if c_obj else 0
in_pins = getattr(matched_comp, "in_pins", []) if matched_comp else []
out_pins = getattr(matched_comp, "out_pins", []) if matched_comp else []
fw_errs = getattr(matched_comp, "fw_errors", []) if matched_comp else []
def _pin_eff_xruns(pin_obj: Any, dir_str: str, idx_p: int) -> int:
p_idx = int(getattr(pin_obj, "pin_index", idx_p) or idx_p)
tot_x = max(
int(getattr(pin_obj, "xrun_count", 0) or 0),
int(getattr(pin_obj, "underrun_count", 0) or 0)
+ int(getattr(pin_obj, "overrun_count", 0) or 0),
)
t0_x = int(getattr(pin_obj, "tick0_xrun_count", 0) or 0)
p_logs = [
fe
for fe in (fw_errs or [])
if str(fe.get("pin_dir", "")).upper() == dir_str
and int(fe.get("pin_index", -1)) == p_idx
]
if p_logs and tot_x == 0:
tot_x = len(p_logs)
t0_x = sum(1 for fe in p_logs if int(fe.get("tick", 0) or 0) == 0)
if tot_x <= 0:
return 0
if self.ignore_tick0_underrun:
if t0_x > 0:
return max(0, tot_x - t0_x)
if iters <= 1:
return 0
return tot_x
violated_in_indices = [
int(getattr(p_in, "pin_index", idx_p) or idx_p)
for idx_p, p_in in enumerate(in_pins)
if _pin_eff_xruns(p_in, "IN", idx_p) > 0
]
violated_out_indices = [
int(getattr(p_out, "pin_index", idx_p) or idx_p)
for idx_p, p_out in enumerate(out_pins)
if _pin_eff_xruns(p_out, "OUT", idx_p) > 0
]
raw_mod_err = int(getattr(matched_comp, "error_count", 0) or 0) if matched_comp else 0
t0_mod_err = int(getattr(matched_comp, "tick0_error_count", 0) or 0) if matched_comp else 0
mod_errs = (
max(0, raw_mod_err - t0_mod_err)
if (self.ignore_tick0_underrun and t0_mod_err > 0)
else (0 if (self.ignore_tick0_underrun and iters <= 1) else raw_mod_err)
)
pin_underrun = bool(violated_in_indices or violated_out_indices)
has_cpc_over = cpc_v > 0 or (eff_cpc > 0 and pk_cyc > eff_cpc)
# Only attribute pipeline XRUN / core overrun to this module if it violated CPC
# or if no module in the pipeline violated CPC and this module is the peak-cycle culprit
is_xrun_culprit = has_cpc_over or (
not any_pipe_cpc_over.get(pid_val, False)
and pk_cyc > 0
and pk_cyc == max_pipe_peak_cyc.get(pid_val, 0)
)
pipe_xruns = raw_pipe_xruns if is_xrun_culprit else 0
core_overruns = raw_core_overruns if is_xrun_culprit else 0
has_violation = bool(
has_cpc_over or pin_underrun or mod_errs > 0 or pipe_xruns > 0 or core_overruns > 0
)
v_cnt = (
cpc_v
if cpc_v > 0
else (
pipe_xruns
+ core_overruns
+ len(violated_in_indices)
+ len(violated_out_indices)
+ mod_errs
+ (1 if has_cpc_over else 0)
)
)
# Build concise violation reason and pin tags for this module only (no cascading to neighbors)
violation_reasons: List[str] = []
pill_parts: List[str] = []
if has_cpc_over:
violation_reasons.append(f"CPC:{pk_cyc}>{eff_cpc}(v={max(1, cpc_v)})")
pill_parts.append("CPC")
for p_idx in violated_in_indices:
violation_reasons.append(f"IN[{p_idx}] UNDERRUN")
pill_parts.append(f"IN[{p_idx}]")
for p_idx in violated_out_indices:
violation_reasons.append(f"OUT[{p_idx}] STALL")
pill_parts.append(f"OUT[{p_idx}]")
if mod_errs > 0 and not (violated_in_indices or violated_out_indices):
violation_reasons.append(f"FW_ERR(v={mod_errs})")
pill_parts.append("FW_ERR")
if not violation_reasons and (pipe_xruns > 0 or core_overruns > 0):
violation_reasons.append(f"XRUN(v={pipe_xruns or core_overruns})")
pill_parts.append("XRUN")
reason_str = "+".join(pill_parts[:2]) if pill_parts else "VIOL"
violation_pill_tag = f"! {reason_str} v={max(1, v_cnt)}"
telem_entry: Dict[str, Any] = {
"comp_id": int(getattr(matched_comp, "resource_id", getattr(matched_comp, "comp_id", 0))) if matched_comp else int(d_nid),
"widget_name": (getattr(matched_comp, "widget_name", "") if matched_comp else d_name) or nid,
"pipeline_id": pid_val,
"avg_kcps": float(getattr(matched_comp, "avg_kcps", 0.0)) if matched_comp else 0.0,
"peak_kcps": float(getattr(matched_comp, "peak_kcps", 0.0)) if matched_comp else 0.0,
"domain": str(getattr(matched_comp, "domain", "LL")) if matched_comp else "LL",
"mem_domain": str(getattr(matched_comp, "mem_domain", "SRAM")) if matched_comp else "SRAM",
"core_id": cid_val,
"in_rms_db": float(getattr(matched_comp, "in_rms_db", -120.0)) if matched_comp else -120.0,
"out_rms_db": float(getattr(matched_comp, "out_rms_db", -120.0)) if matched_comp else -120.0,
"powered": bool(d_pwr) if matched_dapm else True,
"has_violation": has_violation,
"direct_violation": has_violation,
"violation_reasons": violation_reasons,
"violation_pill_tag": violation_pill_tag,
"violated_in_pins": violated_in_indices,
"violated_out_pins": violated_out_indices,
"violation_count": v_cnt,
"cpc_violations": cpc_v,
"effective_cpc": eff_cpc,
"avg_cycles": avg_cyc,
"peak_cycles": pk_cyc,
"pipe_xruns": pipe_xruns,
"core_overruns": core_overruns,
"pin_underrun": pin_underrun,
"mod_obj": matched_comp,
}
self.live_node_telemetry[nid] = telem_entry
# Mark ONLY the specific violated pin port(s) on this violating module
for p_idx in violated_in_indices:
port_obj = (
node.in_ports[p_idx]
if p_idx < len(node.in_ports)
else (node.in_ports[0] if node.in_ports else None)
)
if port_obj is not None:
pkey = (nid, port_obj.id, "in")
self.violating_ports.add(pkey)
self.violating_port_info[pkey] = {
"primary_nid": nid,
"primary_telem": telem_entry,
"pin_label": f"IN[{p_idx}]",
"reason": f"IN[{p_idx}] UNDERRUN",
}
for p_idx in violated_out_indices:
port_obj = (
node.out_ports[p_idx]
if p_idx < len(node.out_ports)
else (node.out_ports[0] if node.out_ports else None)
)
if port_obj is not None:
pkey = (nid, port_obj.id, "out")
self.violating_ports.add(pkey)
self.violating_port_info[pkey] = {
"primary_nid": nid,
"primary_telem": telem_entry,
"pin_label": f"OUT[{p_idx}]",
"reason": f"OUT[{p_idx}] STALL",
}
self.queue_draw()
def set_graph(self, vm: GraphViewModel, workspace: Optional[Topology2Workspace] = None) -> None:
"""Load a new GraphViewModel, auto-layout its nodes, and trigger snapshot redraw."""
self.workspace = workspace
self.vm = vm
self.selected_node_id = None
self.selected_node_ids.clear()
self.selected_edge_id = None
self.selected_container_id = None
self.selected_container_ids.clear()
self.hovered_warning_pid = None
self._pending_drag_history_entry = None
self.clear_diagnostic_highlights()
self.history.clear()
self._layout_cache.clear()
layout_graph(vm)
self.fit_to_view()
if self.on_selection_changed:
self.on_selection_changed(vm.title, vm.root_config, vm.subtitle)
self.queue_draw()
def _capture_history_entry(self, description: str) -> Optional[GraphHistoryEntry]:
if not self.vm:
return None
return GraphHistoryEntry(
description=description,
vm_snapshot=self.vm.clone(),
selected_node_id=self.selected_node_id,
selected_node_ids=set(self.selected_node_ids),
selected_edge_id=self.selected_edge_id,
selected_container_id=self.selected_container_id,
selected_container_ids=set(self.selected_container_ids),
)
def record_undo_snapshot(self, description: str) -> None:
"""Record a snapshot of the current graph state onto the Undo stack before a mutation."""
if self._suppress_auto_history or not self.vm:
return
debug_log_action("CANVAS-MUTATE", description, f"graph={self.vm.title}")
entry = self._capture_history_entry(description)
if entry is not None:
self.history.push_undo_entry(entry)
def _notify_current_selection(self) -> None:
if not self.vm or not self.on_selection_changed:
return
if self.selected_node_id and self.selected_node_id in self.vm.nodes:
node = self.vm.nodes[self.selected_node_id]
extra_cnt = len(self.selected_node_ids) - 1 if self.selected_node_id in self.selected_node_ids else len(self.selected_node_ids)
title = f"{node.title} (+{extra_cnt} selected)" if extra_cnt > 0 else node.title
self.on_selection_changed(title, node.config, node.subtitle)
elif self.selected_edge_id:
edge = next((e for e in self.vm.edges if e.id == self.selected_edge_id), None)
if edge:
self.on_selection_changed(
f"Route: {edge.source_node} ({edge.source_port}) → {edge.sink_node} ({edge.sink_port})",
edge.config,
"Object.Base.route",
)
else:
self.on_selection_changed(self.vm.title, self.vm.root_config, self.vm.subtitle)
elif self.selected_container_id is not None and self.selected_container_id in self.vm.containers:
cont = self.vm.containers[self.selected_container_id]
self.on_selection_changed(
f"Pipeline {self.selected_container_id}: {cont.class_name}",
cont.config,
f"Direction: {cont.direction}",
)
else:
self.on_selection_changed(self.vm.title, self.vm.root_config, self.vm.subtitle)
def _restore_history_entry(self, entry: GraphHistoryEntry) -> None:
self._clear_drop_preview()
self.vm = entry.vm_snapshot.clone()
self.selected_node_id = entry.selected_node_id if entry.selected_node_id in self.vm.nodes else None
self.selected_node_ids = {nid for nid in entry.selected_node_ids if nid in self.vm.nodes}
self.selected_edge_id = (
entry.selected_edge_id
if any(e.id == entry.selected_edge_id for e in self.vm.edges)
else None
)
self.selected_container_id = (
entry.selected_container_id
if entry.selected_container_id in self.vm.containers
else None
)
self.selected_container_ids = {pid for pid in entry.selected_container_ids if pid in self.vm.containers}
self._layout_cache.clear()
self._notify_current_selection()
if self.on_graph_modified:
self.on_graph_modified()
self.queue_draw()
def undo(self) -> Optional[str]:
"""Undo the last graph or attribute modification and return its description."""
if not self.vm or not self.history.can_undo:
return None
curr = self._capture_history_entry("")
if curr is None:
return None
res = self.history.undo(curr)
if res is None:
return None
prev_entry, desc = res
self._restore_history_entry(prev_entry)
return desc
def redo(self) -> Optional[str]:
"""Redo the last undone graph or attribute modification and return its description."""
if not self.vm or not self.history.can_redo:
return None
curr = self._capture_history_entry("")
if curr is None:
return None
res = self.history.redo(curr)
if res is None:
return None
next_entry, desc = res
self._restore_history_entry(next_entry)
return desc
def relayout_graph(self) -> None:
"""Record an undo snapshot and re-run Sugiyama DAG auto-layout on the active graph."""
if not self.vm:
return
self.record_undo_snapshot("Auto-layout graph")
layout_graph(self.vm)
self.vm.dirty = True
self.fit_to_view()
if self.on_graph_modified:
self.on_graph_modified()
self.queue_draw()
def select_node(self, node_id: Optional[str], additive: bool = False) -> None:
self.selected_edge_id = None
if node_id is None:
self.selected_node_id = None
self.selected_node_ids.clear()
self.selected_container_id = None
self.selected_container_ids.clear()
else:
if additive:
if node_id in self.selected_node_ids:
self.selected_node_ids.remove(node_id)
self.selected_node_id = next(iter(self.selected_node_ids), None)
else:
self.selected_node_ids.add(node_id)
self.selected_node_id = node_id
else:
self.selected_node_ids = {node_id}
self.selected_node_id = node_id
self.selected_container_id = None
self.selected_container_ids.clear()
if self.vm and self.selected_node_id and self.selected_node_id in self.vm.nodes:
node = self.vm.nodes[self.selected_node_id]
debug_log_action(
"CANVAS-SELECT",
f"Select node {node.id}",
f"class={node.class_name} category={node.class_category} pipe={node.pipeline_id}",
)
if self.on_selection_changed:
self.on_selection_changed(node.title, node.config, node.subtitle)
self.queue_draw()
def _get_graph_bounds(self) -> Tuple[float, float, float, float]:
"""Return (min_x, min_y, graph_w, graph_h) in world coordinates."""
if not self.vm or not self.vm.nodes:
return (0.0, 0.0, 200.0, 150.0)
min_x = min(n.x for n in self.vm.nodes.values())
min_y = min(n.y for n in self.vm.nodes.values())
max_x = max(n.x + n.width for n in self.vm.nodes.values())
max_y = max(n.y + n.height for n in self.vm.nodes.values())
for c in self.vm.containers.values():
min_x = min(min_x, c.x)
min_y = min(min_y, c.y)
max_x = max(max_x, c.x + c.width)
max_y = max(max_y, c.y + c.height)
graph_w = max(max_x - min_x, 200.0)
graph_h = max(max_y - min_y, 150.0)
return (min_x, min_y, graph_w, graph_h)
def _compute_fit_zoom(self, alloc_w: float, alloc_h: float, graph_w: float, graph_h: float) -> float:
pad = min(44.0, max(16.0, alloc_w * 0.04), max(16.0, alloc_h * 0.04))
zx = max(40.0, alloc_w - 2.0 * pad) / graph_w
zy = max(40.0, alloc_h - 2.0 * pad) / graph_h
return max(0.08, min(4.0, min(zx, zy)))
def fit_to_view(self, width: Optional[float] = None, height: Optional[float] = None) -> None:
"""Center and scale camera to fit the active graph."""
self._is_fitted = True
if not self.vm or not self.vm.nodes:
self.pan_x = 30.0
self.pan_y = 30.0
self.zoom = 1.0
self.queue_draw()
return
min_x, min_y, graph_w, graph_h = self._get_graph_bounds()
alloc_w = float(width if width is not None else (self.get_width() or 860))
alloc_h = float(height if height is not None else (self.get_height() or 600))
self.zoom = self._compute_fit_zoom(alloc_w, alloc_h, graph_w, graph_h)
self.pan_x = (alloc_w - graph_w * self.zoom) / 2.0 - min_x * self.zoom
self.pan_y = (alloc_h - graph_h * self.zoom) / 2.0 - min_y * self.zoom
self.queue_draw()
def focus_on_world_rect(self, wx: float, wy: float, ww: float, wh: float) -> None:
"""Center and zoom the canvas camera onto a specific world rectangle `(wx, wy, ww, wh)`."""
self._is_fitted = False
alloc_w = float(self.get_width() or 860)
alloc_h = float(self.get_height() or 600)
pad_w = max(ww + 220.0, 480.0)
pad_h = max(wh + 180.0, 320.0)
self.zoom = max(0.35, min(1.35, min(alloc_w / pad_w, alloc_h / pad_h)))
cx = wx + ww / 2.0
cy = wy + wh / 2.0
self.pan_x = (alloc_w / 2.0) - cx * self.zoom
self.pan_y = (alloc_h / 2.0) - cy * self.zoom
self.queue_draw()
def focus_diagnostic(self, diag: object) -> None:
"""Focus and highlight the failing object on the main graph canvas for a CompileDiagnostic."""
if not self.vm:
return
self.diag_highlight_node_id = None
self.diag_highlight_container_id = None
self.diag_highlight_edge_id = None
sev = getattr(diag, "severity", "error")
msg = getattr(diag, "message", "")
sym = getattr(diag, "symbol_or_attr", None)
tk = getattr(diag, "target_kind", "root")
tid = getattr(diag, "target_id", None)
lno = getattr(diag, "line_no", None)
cno = getattr(diag, "col_no", None)
loc_tag = f" (line {lno}{f':{cno}' if cno else ''})" if lno else ""
sym_tag = f" [{sym}]" if sym and sym not in msg else ""
self.diag_banner_severity = sev
self.diag_banner_text = f"{'ERROR' if sev == 'error' else 'WARNING'}{loc_tag}{sym_tag}: {msg}"
if tk == "node" and tid and tid in self.vm.nodes:
self.diag_highlight_node_id = tid
self.select_node(tid)
n = self.vm.nodes[tid]
self.focus_on_world_rect(n.x, n.y, n.width, n.height)
return
if tk == "container" and tid and str(tid).isdigit() and int(tid) in self.vm.containers:
pid = int(tid)
self.diag_highlight_container_id = pid
self.selected_node_id = None
self.selected_node_ids.clear()
self.selected_edge_id = None
self.selected_container_id = pid
self.selected_container_ids = {pid}
cont = self.vm.containers[pid]
if self.on_selection_changed:
self.on_selection_changed(
f"Pipeline {pid}: {cont.class_name}",
cont.config,
f"Direction: {cont.direction}",
)
self.focus_on_world_rect(cont.x, cont.y, cont.width, cont.height)
return
if tk == "edge" and tid:
edge = next((e for e in self.vm.edges if e.id == tid), None)
if edge:
self.diag_highlight_edge_id = edge.id
self.selected_node_id = None
self.selected_node_ids.clear()
self.selected_container_id = None
self.selected_container_ids.clear()
self.selected_edge_id = edge.id
if self.on_selection_changed:
self.on_selection_changed(
f"Route: {edge.source_node} ({edge.source_port}) → {edge.sink_node} ({edge.sink_port})",
edge.config,
"Object.Base.route",
)
u = self.vm.nodes.get(edge.source_node)
v = self.vm.nodes.get(edge.sink_node)
if u and v:
min_x = min(u.x, v.x)
min_y = min(u.y, v.y)
max_x = max(u.x + u.width, v.x + v.width)
max_y = max(u.y + u.height, v.y + v.height)
self.focus_on_world_rect(min_x, min_y, max_x - min_x, max_y - min_y)
else:
self.queue_draw()
return
# Default / Define / Root level error: select topology root config so Define (Active Variables) is shown
self.select_node(None)
if self.on_selection_changed:
self.on_selection_changed(self.vm.title, self.vm.root_config, self.vm.subtitle)
# If a Define variable corresponds to a specific node or pipeline container on the graph, highlight & pan to it
if sym:
def_node = self.vm.root_config.get_child("Define (Active Variables)")
def_val = str(def_node.get_scalar(sym) or "").strip("'\"") if def_node else ""
if def_val in self.vm.nodes:
n = self.vm.nodes[def_val]
self.diag_highlight_node_id = def_val
self.focus_on_world_rect(n.x, n.y, n.width, n.height)
return
if sym.endswith("_PIPELINE_ID") and def_val.isdigit() and int(def_val) in self.vm.containers:
pid = int(def_val)
c = self.vm.containers[pid]
self.diag_highlight_container_id = pid
self.focus_on_world_rect(c.x, c.y, c.width, c.height)
return
for pid, c in self.vm.containers.items():
if sym in c.enabled_by:
self.diag_highlight_container_id = pid
self.focus_on_world_rect(c.x, c.y, c.width, c.height)
return
self.fit_to_view()
def _handle_canvas_resize(self, new_w: int, new_h: int) -> None:
"""Scale and re-center the graph when the canvas widget is resized."""
old_w, old_h = self._last_canvas_size
self._last_canvas_size = (new_w, new_h)
if not self.vm or not self.vm.nodes:
return
if old_w <= 0 or old_h <= 0 or self._is_fitted:
self.fit_to_view(float(new_w), float(new_h))
return
# User has manually zoomed/panned: scale zoom proportionally with canvas resize
# while keeping the viewport center world point anchored at the new canvas center.
_, _, graph_w, graph_h = self._get_graph_bounds()
old_fit = self._compute_fit_zoom(float(old_w), float(old_h), graph_w, graph_h)
new_fit = self._compute_fit_zoom(float(new_w), float(new_h), graph_w, graph_h)
scale_ratio = (new_fit / old_fit) if old_fit > 0 else 1.0
if abs(scale_ratio - 1.0) < 1e-4:
# Fallback if fit axis didn't change: scale by geometric mean of dimension ratios
scale_ratio = math.sqrt((new_w / float(old_w)) * (new_h / float(old_h)))
wx_center, wy_center = self.screen_to_world(old_w / 2.0, old_h / 2.0)
self.zoom = max(0.08, min(5.0, self.zoom * scale_ratio))
self.pan_x = (new_w / 2.0) - wx_center * self.zoom
self.pan_y = (new_h / 2.0) - wy_center * self.zoom
def screen_to_world(self, sx: float, sy: float) -> Tuple[float, float]:
return ((sx - self.pan_x) / self.zoom, (sy - self.pan_y) / self.zoom)
def _get_pango_layout(self, text: str, size_pt: int = 10, bold: bool = False) -> Pango.Layout:
key = (text, size_pt, bold)
layout = self._layout_cache.get(key)
if layout is None:
layout = self.create_pango_layout(text)
font_desc = Pango.FontDescription.from_string(
f"Sans {'Bold ' if bold else ''}{size_pt}"
)
layout.set_font_description(font_desc)
self._layout_cache[key] = layout