Repository navigation
Expand file tree
/
Copy pathwindow.py
More file actions
5872 lines (5389 loc) · 270 KB
/
Copy pathwindow.py
File metadata and controls
5872 lines (5389 loc) · 270 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
"""Main GTK4 Window with 3 horizontal panels:
- Left: 4 vertical sub-panes (Base Classes, Processing Modules, Pipelines, Machine Topologies)
- Middle: Gtk.Snapshot Graph Canvas + bottom Compile/Testbench waveform & log drawer
- Right: Tree view of attributes of the selected graph node
"""
from __future__ import annotations
from dataclasses import dataclass, field
import json
import os
import re
import shutil
import subprocess
import sys
import threading
from typing import Any, Callable, Dict, List, Optional, Tuple
import gi
gi.require_version("Gtk", "4.0")
from gi.repository import Gdk, Gio, GLib, Gtk, Pango
from . import __version__ as TOOL_VERSION
from .compiler import (
CompileDiagnostic,
CompileResult,
TopologyCompiler,
classify_log_line,
parse_compile_diagnostics,
)
from .graph_canvas import TopologyGraphCanvas
from .layout import _compute_node_geometry, layout_graph
from .left_panes import LeftNavigationPanel
from .model import (
ConfigNode,
GraphNode,
GraphViewModel,
debug_log_action,
debug_log_command,
debug_log_line,
)
from .parser import Topology2Workspace
from .right_inspector import RightAttributeInspector
from .serializer import (
_extract_active_pipeline_ids,
generate_compilable_conf,
get_editable_conf_text_for_vm,
serialize_graph_for_save,
)
from .testbench import (
KcontrolTelemetryItem,
SOF_CDEV_WIN_DEBUG,
SOF_CDEV_WIN_FW_REGS,
SOF_CDEV_WIN_PERF,
SOF_PCM_OP_CAPTURE_BUFFER,
SOF_PCM_OP_START_TONE,
SOF_PCM_OP_STOP_TONE,
SOF_PM_OP_RELEASE_HOLD,
SOF_PM_OP_WAKE_HOLD,
SOF_WORKLOAD_MEM_DRAM,
SOF_WORKLOAD_MEM_SRAM,
SOF_WORKLOAD_SIM_OFF,
SOF_WORKLOAD_SIM_REALTIME,
SOF_WORKLOAD_SIM_VIRTUAL,
TestbenchRunResult,
TestbenchRunner,
TestbenchTelemetry,
WaveformSnapshotWidget,
SchedulingTelemetryWidget,
)
from .text_editor import TopologyTextEditor
@dataclass
class GraphTabPage:
"""State for an open file tab in the Main Graph Notebook (holding both Graph Canvas and Text Editor)."""
tab_key: str
pane_kind: str
primary_id: str
secondary_id: Optional[str]
canvas: TopologyGraphCanvas
text_editor: TopologyTextEditor
view_stack: Gtk.Stack
mode_switch_btn: Gtk.ToggleButton
tab_box: Gtk.Box
title_lbl: Gtk.Label
is_untitled: bool = False
text_needs_refresh_from_graph: bool = True
stream_waveforms: Dict[str, Tuple[List[float], List[float]]] = field(default_factory=dict)
last_tb_summary: str = ""
last_telemetry: Optional[TestbenchTelemetry] = None
class Topology2MainWindow(Gtk.ApplicationWindow):
"""Main GTK4 Application Window for SOF Builder (Topology2 Visual Editor & Testbench Studio)."""
def __init__(self, app: Gtk.Application, initial_dir: Optional[str] = None):
super().__init__(application=app, title="SOF Builder — Topology2 Visual Graph Editor & Testbench")
self.set_decorated(True)
self._ui_window_width: int = 1560
self._ui_window_height: int = 940
self._ui_window_maximized: bool = True
self._saved_total_w: int = 0
self._saved_total_h: int = 0
self._saved_hpaned_outer_pos: Optional[int] = None
self._saved_hpaned_inner_pos: Optional[int] = None
self._saved_center_vpaned_pos: Optional[int] = None
self._hpaned_outer_ratio: float = 0.25
self._hpaned_inner_ratio: float = 0.50
self._center_vpaned_ratio: float = 0.68
self._saved_left_vpaned_main_pos: int = 345
self._saved_left_vpaned_top_pos: int = 165
self._saved_left_vpaned_bot_pos: int = 185
self._saved_treeview_col_widths: Dict[str, List[int]] = {}
self._saved_open_tabs: List[Dict[str, Any]] = []
self._saved_active_tab_key: str = ""
self._saved_topology2_dir: str = ""
self._restoring_session_tabs: bool = False
self._applying_programmatic_paned_pos: bool = True
self._paned_layout_ready: bool = False
self._paned_sync_seq: int = 0
self._save_ui_state_timer_id: Optional[int] = None
self._load_ui_state()
self.set_default_size(self._ui_window_width, self._ui_window_height)
if self._ui_window_maximized:
self.maximize()
win_key = Gtk.EventControllerKey.new()
win_key.connect("key-pressed", self._on_window_key_pressed)
self.add_controller(win_key)
self.connect("close-request", self._on_window_close_request)
self.workspace: Optional[Topology2Workspace] = None
self.compiler: Optional[TopologyCompiler] = None
self.tb_runner: Optional[TestbenchRunner] = None
self.last_compiled_tplg: Optional[str] = None
self.last_output_wav: Optional[str] = None
self.last_telemetry: Optional[TestbenchTelemetry] = None
self._discovered_kcontrols: List[KcontrolTelemetryItem] = []
self._pending_kctl_overrides: Dict[str, List[int]] = {}
self._pending_bytes_overrides: Dict[str, str] = {}
self._syncing_remote_controls: bool = False
self._log_line_diagnostics: Dict[int, CompileDiagnostic] = {}
self._last_compile_diagnostics: List[CompileDiagnostic] = []
self._last_conf_path: str = ""
self._last_allocated_width: int = 0
self._last_allocated_height: int = 0
self._rt_timer_id: Optional[int] = None
self._rt_poll_busy: bool = False
self._pipeline_sync_seq: int = 0
self.graph_tabs: List[GraphTabPage] = []
self._new_file_counter: int = 0
self.target_platform: str = "mtl"
self.target_harness_kind: str = "hda_analog"
self.target_platform_def_path: str = "platform/intel/mtl.conf"
self.target_variant_name: str = "sof-hda-generic"
self._fallback_canvas = TopologyGraphCanvas(
on_selection_changed=self._on_canvas_selection_changed,
on_graph_modified=self._on_graph_modified,
on_history_changed=self._update_undo_redo_buttons,
on_kcontrol_changed=self._on_canvas_kcontrol_changed,
on_probe_tap_toggled=self._on_canvas_probe_tap_toggled,
on_testbench_io_changed=self._on_canvas_testbench_io_changed,
on_view_source_requested=self._on_view_source_requested,
on_violation_bang_clicked=self._on_canvas_violation_bang_clicked,
)
self._build_header_bar()
self._build_main_3panel_layout()
# Load initial topology2 directory if valid
default_dir = self._discover_default_topology2_dir(initial_dir)
if default_dir and os.path.isdir(default_dir):
self.load_topology2_directory(default_dir)
def _discover_default_topology2_dir(self, initial_dir: Optional[str] = None) -> str:
"""Locate a valid tools/topology/topology2 workspace directory without hardcoded user paths."""
if initial_dir:
abs_init = os.path.abspath(initial_dir)
if os.path.isdir(abs_init):
return abs_init
candidates: List[str] = []
env_tplg2 = os.environ.get("SOF_TOPOLOGY2_DIR", "").strip()
if env_tplg2:
candidates.append(os.path.abspath(env_tplg2))
env_sof = os.environ.get("SOF_ROOT", "").strip()
if env_sof:
candidates.append(os.path.abspath(os.path.join(env_sof, "tools", "topology", "topology2")))
if self._saved_topology2_dir:
candidates.append(self._saved_topology2_dir)
# Check current working directory and ancestors for an SOF checkout
cur = os.path.abspath(os.getcwd())
for _ in range(5):
candidates.append(os.path.join(cur, "tools", "topology", "topology2"))
if os.path.basename(cur) == "topology2" and os.path.isdir(os.path.join(cur, "include")):
candidates.append(cur)
parent = os.path.dirname(cur)
if parent == cur:
break
cur = parent
# Also check sibling SOF checkouts relative to the repository root
pkg_root = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "..", ".."))
for sib in ("sof", "sof-arl/sof-arl", "sof-arl", "sof-ptl", "sof-tgl"):
candidates.append(os.path.join(pkg_root, sib, "tools", "topology", "topology2"))
for cand in candidates:
if cand and os.path.isdir(cand) and os.path.isdir(os.path.join(cand, "include")):
return cand
for cand in candidates:
if cand and os.path.isdir(cand):
return cand
return ""
@property
def canvas(self) -> TopologyGraphCanvas:
"""Return the active tab's TopologyGraphCanvas (or fallback canvas before any tab is opened)."""
active_tab = self.get_active_tab()
if active_tab is not None:
return active_tab.canvas
return self._fallback_canvas
def get_active_tab(self) -> Optional[GraphTabPage]:
"""Return the currently selected GraphTabPage in the Main Graph Notebook."""
if not self.graph_tabs:
return None
if hasattr(self, "graph_notebook") and self.graph_notebook is not None:
page_num = self.graph_notebook.get_current_page()
if page_num >= 0:
page_widget = self.graph_notebook.get_nth_page(page_num)
for tab in self.graph_tabs:
if tab.view_stack is page_widget or tab.canvas is page_widget:
return tab
return self.graph_tabs[-1]
def _on_window_key_pressed(
self,
_ctrl: Gtk.EventControllerKey,
keyval: int,
_keycode: int,
state: Gdk.ModifierType,
) -> bool:
if keyval == Gdk.KEY_F11:
if self.is_fullscreen():
self.unfullscreen()
else:
self.fullscreen()
return True
focus = self.get_focus()
ctrl_held = bool(state & Gdk.ModifierType.CONTROL_MASK)
shift_held = bool(state & Gdk.ModifierType.SHIFT_MASK)
# File / Tab / Mode shortcuts that work even when focus is inside TextView
if ctrl_held and not isinstance(focus, Gtk.Editable):
if keyval in (Gdk.KEY_t, Gdk.KEY_T) and not shift_held:
self.toggle_active_tab_text_mode()
return True
if keyval in (Gdk.KEY_s, Gdk.KEY_S):
if shift_held:
self.action_save_as()
else:
self.action_save()
return True
if keyval in (Gdk.KEY_o, Gdk.KEY_O):
if shift_held:
self._on_open_dir_clicked(None)
else:
self.action_open_file()
return True
if keyval in (Gdk.KEY_w, Gdk.KEY_W) and not shift_held:
self.close_current_tab()
return True
if keyval in (Gdk.KEY_e, Gdk.KEY_E) and not shift_held:
self.action_export_pdf()
return True
if keyval in (Gdk.KEY_n, Gdk.KEY_N) and not shift_held:
self.action_new_monolithic_topology()
return True
if shift_held and keyval in (Gdk.KEY_m, Gdk.KEY_M):
self.action_new_module()
return True
if shift_held and keyval in (Gdk.KEY_p, Gdk.KEY_P):
self.action_new_feature_topology()
return True
if shift_held and keyval in (Gdk.KEY_f, Gdk.KEY_F):
self.action_new_function_topology()
return True
# Canvas-specific editing & view shortcuts (do not intercept when typing in Entry or TextView)
if not isinstance(focus, (Gtk.Editable, Gtk.TextView)):
if ctrl_held:
if keyval in (Gdk.KEY_z, Gdk.KEY_Z):
if shift_held:
self._on_redo_clicked(None)
else:
self._on_undo_clicked(None)
return True
if keyval in (Gdk.KEY_y, Gdk.KEY_Y):
self._on_redo_clicked(None)
return True
if keyval in (Gdk.KEY_a, Gdk.KEY_A) and not shift_held:
self.action_select_all()
return True
if keyval in (Gdk.KEY_c, Gdk.KEY_C) and not shift_held:
self.action_copy()
return True
if keyval in (Gdk.KEY_x, Gdk.KEY_X) and not shift_held:
self.action_cut()
return True
if keyval in (Gdk.KEY_v, Gdk.KEY_V) and not shift_held:
self.action_paste()
return True
else:
if keyval in (Gdk.KEY_Delete, Gdk.KEY_BackSpace):
self.action_delete_selected()
return True
if keyval in (Gdk.KEY_f, Gdk.KEY_F):
self.canvas.fit_to_view()
return True
if keyval in (Gdk.KEY_l, Gdk.KEY_L):
self._on_relayout_clicked(None)
return True
return False
def _register_win_action(self, name: str, callback: Callable[[], None]) -> Gio.SimpleAction:
act = Gio.SimpleAction.new(name, None)
act.connect("activate", lambda _a, _p: callback())
self.add_action(act)
return act
def _register_stateful_str_action(
self,
name: str,
initial_val: str,
callback: Callable[[str], None],
) -> Gio.SimpleAction:
act = Gio.SimpleAction.new_stateful(
name,
GLib.VariantType.new("s"),
GLib.Variant.new_string(initial_val),
)
def on_activate(action: Gio.SimpleAction, param: Optional[GLib.Variant]) -> None:
if param is None:
return
val = param.get_string()
action.set_state(GLib.Variant.new_string(val))
callback(val)
act.connect("activate", on_activate)
self.add_action(act)
return act
@staticmethod
def _append_str_action_item(menu: Gio.Menu, label: str, action_name: str, target_val: str) -> None:
item = Gio.MenuItem.new(label, None)
item.set_action_and_target_value(action_name, GLib.Variant.new_string(target_val))
menu.append_item(item)
def _build_menubar(self) -> Gtk.PopoverMenuBar:
"""Create the main application Gtk.PopoverMenuBar with File, Edit, View, and Target menus."""
# Register window Gio.SimpleActions
self._register_win_action("new_module", lambda: self.action_new_module())
self._register_win_action("new_feature_topology", lambda: self.action_new_feature_topology())
self._register_win_action("new_function_topology", lambda: self.action_new_function_topology())
self._register_win_action("new_monolithic_topology", lambda: self.action_new_monolithic_topology())
self._register_win_action("open_file", self.action_open_file)
self._register_win_action("open_dir", lambda: self._on_open_dir_clicked(None))
self._register_win_action("save", lambda: self.action_save())
self._register_win_action("save_as", self.action_save_as)
self._register_win_action("export_conf", lambda: self._on_export_conf_clicked(None))
self._register_win_action("export_pdf", self.action_export_pdf)
self._register_win_action("close_tab", lambda: self.close_current_tab())
self.undo_action = self._register_win_action("undo", lambda: self._on_undo_clicked(None))
self.undo_action.set_enabled(False)
self.redo_action = self._register_win_action("redo", lambda: self._on_redo_clicked(None))
self.redo_action.set_enabled(False)
self._register_win_action("select_all", lambda: self.action_select_all())
self._register_win_action("cut", lambda: self.action_cut())
self._register_win_action("copy", lambda: self.action_copy())
self._register_win_action("paste", lambda: self.action_paste())
self._register_win_action("delete_selected", self.action_delete_selected)
self._register_win_action("fit_graph", lambda: self.canvas.fit_to_view())
self._register_win_action("auto_layout", lambda: self._on_relayout_clicked(None))
self._register_win_action("toggle_text_mode", lambda: self.toggle_active_tab_text_mode())
self._register_win_action("zoom_in", lambda: self.canvas.zoom_in())
self._register_win_action("zoom_out", lambda: self.canvas.zoom_out())
self._register_win_action("reset_zoom", lambda: self.canvas.reset_zoom_1to1())
self._register_win_action(
"toggle_fullscreen",
lambda: self.unfullscreen() if self.is_fullscreen() else self.fullscreen(),
)
# Target Menu Actions
self.target_platform_action = self._register_stateful_str_action(
"select_target_platform",
self.target_platform,
self.action_select_target_platform,
)
self.target_harness_action = self._register_stateful_str_action(
"select_target_harness",
self.target_harness_kind,
self.action_select_target_harness,
)
self.target_platform_def_action = self._register_stateful_str_action(
"select_platform_def",
self.target_platform_def_path,
self.action_select_platform_def,
)
self.target_variant_action = self._register_stateful_str_action(
"select_target_variant",
self.target_variant_name,
self.action_select_target_variant,
)
self._register_win_action("open_active_platform_def", lambda: self.action_open_active_platform_def())
self._register_win_action("about", self.action_show_about)
app = self.get_application()
if app is not None:
accels = {
"win.new_module": ["<Control><Shift>m"],
"win.new_feature_topology": ["<Control><Shift>p"],
"win.new_function_topology": ["<Control><Shift>f"],
"win.new_monolithic_topology": ["<Control>n"],
"win.open_file": ["<Control>o"],
"win.open_dir": ["<Control><Shift>o"],
"win.save": ["<Control>s"],
"win.save_as": ["<Control><Shift>s"],
"win.export_pdf": ["<Control>e"],
"win.close_tab": ["<Control>w"],
"win.toggle_text_mode": ["<Control>t"],
"win.zoom_in": ["<Control>plus", "<Control>equal"],
"win.zoom_out": ["<Control>minus"],
"win.reset_zoom": ["<Control>0"],
"win.toggle_fullscreen": ["F11"],
}
for act_name, keys in accels.items():
app.set_accels_for_action(act_name, keys)
menubar_model = Gio.Menu.new()
# 1. File Menu
file_menu = Gio.Menu.new()
new_submenu = Gio.Menu.new()
new_submenu.append("Module (Class.Widget)", "win.new_module")
new_submenu.append("Feature Topology (Class.Pipeline)", "win.new_feature_topology")
new_submenu.append("Function Topology (Multi-Pipeline)", "win.new_function_topology")
new_submenu.append("Monolithic Topology (sof-*.conf)", "win.new_monolithic_topology")
file_new_sec = Gio.Menu.new()
file_new_sec.append_submenu("New", new_submenu)
file_new_sec.append("Open Topology File…", "win.open_file")
file_new_sec.append("Open Topology2 Directory…", "win.open_dir")
file_menu.append_section(None, file_new_sec)
file_save_sec = Gio.Menu.new()
file_save_sec.append("Save", "win.save")
file_save_sec.append("Save As…", "win.save_as")
file_save_sec.append("Export Compilable .conf", "win.export_conf")
file_save_sec.append("Export to PDF…", "win.export_pdf")
file_menu.append_section(None, file_save_sec)
file_close_sec = Gio.Menu.new()
file_close_sec.append("Close Tab", "win.close_tab")
file_menu.append_section(None, file_close_sec)
menubar_model.append_submenu("File", file_menu)
# 2. Edit Menu (Undo, Redo, Select All, Cut, Copy, Paste, Delete)
edit_menu = Gio.Menu.new()
edit_hist_sec = Gio.Menu.new()
edit_hist_sec.append("Undo", "win.undo")
edit_hist_sec.append("Redo", "win.redo")
edit_menu.append_section(None, edit_hist_sec)
edit_clip_sec = Gio.Menu.new()
edit_clip_sec.append("Select All", "win.select_all")
edit_clip_sec.append("Cut", "win.cut")
edit_clip_sec.append("Copy", "win.copy")
edit_clip_sec.append("Paste", "win.paste")
edit_menu.append_section(None, edit_clip_sec)
edit_del_sec = Gio.Menu.new()
edit_del_sec.append("Delete", "win.delete_selected")
edit_menu.append_section(None, edit_del_sec)
menubar_model.append_submenu("Edit", edit_menu)
# 3. View Menu (Fit Graph, Auto-Layout, Toggle Text/Graph, Zoom In/Out/Reset, Fullscreen)
view_menu = Gio.Menu.new()
view_layout_sec = Gio.Menu.new()
view_layout_sec.append("Fit Graph", "win.fit_graph")
view_layout_sec.append("Auto-Layout", "win.auto_layout")
view_layout_sec.append("Toggle Text / Graph View", "win.toggle_text_mode")
view_menu.append_section(None, view_layout_sec)
view_zoom_sec = Gio.Menu.new()
view_zoom_sec.append("Zoom In", "win.zoom_in")
view_zoom_sec.append("Zoom Out", "win.zoom_out")
view_zoom_sec.append("Reset Zoom (1:1)", "win.reset_zoom")
view_menu.append_section(None, view_zoom_sec)
view_win_sec = Gio.Menu.new()
view_win_sec.append("Toggle Fullscreen", "win.toggle_fullscreen")
view_menu.append_section(None, view_win_sec)
menubar_model.append_submenu("View", view_menu)
# 4. Target Menu (Platform Architecture)
self.target_menu = Gio.Menu.new()
self._populate_target_menu()
menubar_model.append_submenu("Target", self.target_menu)
# 5. Help Menu (About)
help_menu = Gio.Menu.new()
help_sec = Gio.Menu.new()
help_sec.append("About…", "win.about")
help_menu.append_section(None, help_sec)
menubar_model.append_submenu("Help", help_menu)
self.menubar_model = menubar_model
menubar = Gtk.PopoverMenuBar.new_from_model(menubar_model)
return menubar
def _collect_version_info(self) -> Dict[str, str]:
"""Collect versions of the Tool, SOF firmware/testbench, ALSA library/driver, and alsa-utils."""
gtk_ver = f"{Gtk.get_major_version()}.{Gtk.get_minor_version()}.{Gtk.get_micro_version()}"
py_ver = f"{sys.version_info.major}.{sys.version_info.minor}.{sys.version_info.micro}"
tool_ver = f"SOF Builder v{TOOL_VERSION} (GTK {gtk_ver}, Python {py_ver})"
# Resolve SOF root directory
tplg2_root = (
self.workspace.root_dir
if (self.workspace and self.workspace.root_dir)
else self._discover_default_topology2_dir()
)
sof_root = (
os.environ.get("SOF_ROOT", "").strip()
or (os.path.abspath(os.path.join(tplg2_root, "..", "..", "..")) if tplg2_root else "")
)
# 1. SOF Version
sof_ver_parts: List[str] = []
sof_ver_h_candidates = [
os.path.join(sof_root, "tools", "testbench", "build_testbench", "sof_ep", "build", "generated", "include", "sof_versions.h"),
os.path.join(sof_root, "build_testbench", "sof_ep", "build", "generated", "include", "sof_versions.h"),
]
for vh_path in sof_ver_h_candidates:
if os.path.isfile(vh_path):
try:
with open(vh_path, "r", encoding="utf-8", errors="ignore") as fh:
vh_txt = fh.read()
maj = re.search(r"#define\s+SOF_MAJOR\s+(\d+)", vh_txt)
mnr = re.search(r"#define\s+SOF_MINOR\s+(\d+)", vh_txt)
mic = re.search(r"#define\s+SOF_MICRO\s+(\d+)", vh_txt)
gtag = re.search(r'#define\s+SOF_GIT_TAG\s+"([^"]+)"', vh_txt)
if maj and mnr and mic:
sof_ver_parts.append(f"v{maj.group(1)}.{mnr.group(1)}.{mic.group(1)}")
if gtag:
sof_ver_parts.append(f"({gtag.group(1)})")
break
except Exception:
pass
if not sof_ver_parts:
cmake_p = os.path.join(sof_root, "CMakeLists.txt")
if os.path.isfile(cmake_p):
try:
with open(cmake_p, "r", encoding="utf-8", errors="ignore") as fh:
cm_txt = fh.read()
maj = re.search(r"set\(VERSION_MAJOR\s+(\d+)\)", cm_txt)
mnr = re.search(r"set\(VERSION_MINOR\s+(\d+)\)", cm_txt)
mic = re.search(r"set\(VERSION_MICRO\s+(\d+)\)", cm_txt)
if maj and mnr and mic:
sof_ver_parts.append(f"v{maj.group(1)}.{mnr.group(1)}.{mic.group(1)}")
except Exception:
pass
try:
git_out = subprocess.check_output(
["git", "-C", sof_root, "describe", "--tags", "--always"],
stderr=subprocess.DEVNULL,
text=True,
timeout=1.5,
).strip()
if git_out:
sof_ver_parts.append(f"({git_out})")
except Exception:
pass
if self.last_telemetry and self.last_telemetry.fw_version and self.last_telemetry.fw_version != "0.0.0.0":
sof_ver_parts.append(f"[Live FW: v{self.last_telemetry.fw_version}]")
sof_ver = " ".join(sof_ver_parts) if sof_ver_parts else "Unknown"
# 2. ALSA & alsa-utils versions
alsatplg_bin = (
self.compiler.alsatplg_bin
if (self.compiler and getattr(self.compiler, "alsatplg_bin", None))
else (shutil.which("alsatplg") or "alsatplg")
)
alsatplg_ver = ""
libasound_ver = ""
libatopology_ver = ""
try:
out = subprocess.check_output(
[alsatplg_bin, "--version"],
stderr=subprocess.STDOUT,
text=True,
timeout=1.5,
)
for ln in out.splitlines():
m_t = re.search(r"alsatplg\s+version\s+(\S+)", ln, re.IGNORECASE)
if m_t:
alsatplg_ver = m_t.group(1)
m_a = re.search(r"libasound\s+version\s+(\S+)", ln, re.IGNORECASE)
if m_a:
libasound_ver = m_a.group(1)
m_top = re.search(r"libatopology\s+version\s+(\S+)", ln, re.IGNORECASE)
if m_top:
libatopology_ver = m_top.group(1)
except Exception:
pass
if not libasound_ver:
try:
libasound_ver = subprocess.check_output(
["pkg-config", "--modversion", "alsa"],
stderr=subprocess.DEVNULL,
text=True,
timeout=1.5,
).strip()
except Exception:
pass
aplay_ver = ""
aplay_bin = shutil.which("aplay")
if aplay_bin:
try:
out = subprocess.check_output(
[aplay_bin, "--version"],
stderr=subprocess.STDOUT,
text=True,
timeout=1.5,
)
m_ap = re.search(r"version\s+([0-9][0-9A-Za-z._-]*)", out)
if m_ap:
aplay_ver = m_ap.group(1)
except Exception:
pass
kernel_alsa = ""
if os.path.isfile("/proc/asound/version"):
try:
with open("/proc/asound/version", "r", encoding="utf-8", errors="ignore") as fh:
k_line = fh.readline().strip().rstrip(".")
m_k = re.search(r"Version\s+(\S+)", k_line)
kernel_alsa = m_k.group(1) if m_k else k_line
except Exception:
pass
alsa_parts: List[str] = []
if libasound_ver:
alsa_parts.append(f"libasound {libasound_ver}")
if libatopology_ver:
alsa_parts.append(f"libatopology {libatopology_ver}")
if kernel_alsa:
alsa_parts.append(f"Kernel ALSA {kernel_alsa}")
alsa_ver = " | ".join(alsa_parts) if alsa_parts else "Unknown"
utils_parts: List[str] = []
if alsatplg_ver:
utils_parts.append(f"alsatplg {alsatplg_ver}")
if aplay_ver and aplay_ver != alsatplg_ver:
utils_parts.append(f"aplay {aplay_ver}")
elif aplay_ver and not alsatplg_ver:
utils_parts.append(f"alsa-utils {aplay_ver}")
if alsatplg_bin:
utils_parts.append(f"({alsatplg_bin})")
alsautils_ver = " ".join(utils_parts) if utils_parts else "Unknown"
return {
"tool": tool_ver,
"sof": sof_ver,
"alsa": alsa_ver,
"alsautils": alsautils_ver,
}
def action_show_about(self) -> None:
"""Display the Help -> About dialog showing Tool, SOF, ALSA, and alsa-utils versions."""
debug_log_action("HELP-ABOUT", "Open About dialog")
vinfo = self._collect_version_info()
dlg = Gtk.Window(
title="About SOF Builder",
transient_for=self,
modal=True,
default_width=560,
default_height=310,
resizable=False,
)
self._about_dialog = dlg
outer = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=12)
outer.set_margin_top(18)
outer.set_margin_bottom(18)
outer.set_margin_start(22)
outer.set_margin_end(22)
title_lbl = Gtk.Label(label="SOF Builder")
title_lbl.add_css_class("heading")
title_lbl.set_xalign(0.0)
outer.append(title_lbl)
sub_lbl = Gtk.Label(
label="Visual Graph Editor, IPC4 Topology Compiler & Real-Time SOF Testbench"
)
sub_lbl.set_xalign(0.0)
outer.append(sub_lbl)
sep = Gtk.Separator(orientation=Gtk.Orientation.HORIZONTAL)
outer.append(sep)
grid = Gtk.Grid(column_spacing=16, row_spacing=10)
rows = [
("Tool Version:", vinfo["tool"]),
("SOF Version:", vinfo["sof"]),
("ALSA Version:", vinfo["alsa"]),
("alsa-utils Version:", vinfo["alsautils"]),
]
for r_idx, (k_txt, val_txt) in enumerate(rows):
k_lbl = Gtk.Label(label=k_txt)
k_lbl.set_xalign(0.0)
k_lbl.add_css_class("heading")
v_lbl = Gtk.Label(label=val_txt)
v_lbl.set_xalign(0.0)
v_lbl.set_selectable(True)
v_lbl.set_wrap(True)
v_lbl.set_hexpand(True)
grid.attach(k_lbl, 0, r_idx, 1, 1)
grid.attach(v_lbl, 1, r_idx, 1, 1)
outer.append(grid)
btn_row = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=8)
btn_row.set_halign(Gtk.Align.END)
btn_row.set_margin_top(10)
close_btn = Gtk.Button(label="Close")
close_btn.add_css_class("suggested-action")
close_btn.connect("clicked", lambda _b: dlg.close())
btn_row.append(close_btn)
outer.append(btn_row)
dlg.set_child(outer)
dlg.present()
def _populate_target_menu(self) -> None:
"""Populate the Target menu with Platform Architecture choices."""
if not hasattr(self, "target_menu") or self.target_menu is None:
return
self.target_menu.remove_all()
plat_sec = Gio.Menu.new()
plat_choices = [
("mtl", "MTL / ARL — ACE 1.x (platform/intel/mtl.conf)"),
("lnl", "LNL — ACE 2.0 (platform/intel/lnl.conf)"),
("ptl", "PTL — ACE 3.0 (platform/intel/ptl.conf)"),
("nvl", "NVL — ACE 4.0 (platform/intel/ptl.conf)"),
("tgl", "TGL — CAVS 2.5 (platform/intel/tgl.conf)"),
("adl", "ADL / RPL — CAVS 2.5 (platform/intel/tgl.conf)"),
]
for pid, plabel in plat_choices:
self._append_str_action_item(plat_sec, plabel, "win.select_target_platform", pid)
self.target_menu.append_section(None, plat_sec)
def action_select_target_platform(self, platform_id: str) -> None:
"""Select the target SoC platform definition (tgl, adl, mtl, lnl, ptl, nvl) for testbench compilation."""
plat = platform_id.strip().lower()
debug_log_action("TARGET-PLATFORM", f"Select target platform '{plat}'")
self.target_platform = plat
plat_conf_map = {
"tgl": "platform/intel/tgl.conf",
"adl": "platform/intel/tgl.conf",
"mtl": "platform/intel/mtl.conf",
"lnl": "platform/intel/lnl.conf",
"ptl": "platform/intel/ptl.conf",
"nvl": "platform/intel/ptl.conf",
}
if plat in plat_conf_map:
self.target_platform_def_path = plat_conf_map[plat]
if hasattr(self, "target_platform_def_action"):
self.target_platform_def_action.set_state(
GLib.Variant.new_string(self.target_platform_def_path)
)
if self.compiler:
self.compiler.target_platform = plat
self.compiler.extra_platform_conf = self.target_platform_def_path
if self.tb_runner:
self.tb_runner.platform_preset = plat
if self.tb_runner.live_client:
tb_preset = TestbenchRunner.map_platform_to_tb_preset(plat)
st, out = self.tb_runner.live_client.exec_shell(f"platform-cfg preset {tb_preset}")
self.append_log(f"[SOFR] $ platform-cfg preset {tb_preset} (status={st})\n{out.strip()}")
self._on_refresh_telemetry_clicked(None)
# Update PLATFORM variable in the active tab's GraphViewModel if present
active = self.get_active_tab()
if active is not None and active.canvas.vm is not None:
vm = active.canvas.vm
vm.defines["PLATFORM"] = plat
def_node = vm.root_config.get_child("Define (Active Variables)")
if def_node is not None:
def_node.set_scalar("PLATFORM", plat, category_info="Define", origin="instance")
# Merge SoC platform defines (e.g. DMIC_DRIVER_VERSION, SSP_BLOB_VERSION) into vm.defines
if self.workspace:
for pdef in self.workspace.platform_definitions:
if pdef.get("rel_path") == self.target_platform_def_path:
p_defs = pdef.get("defines", {})
if isinstance(p_defs, dict):
for k, v in p_defs.items():
vm.defines[k] = str(v)
if def_node is not None:
def_node.set_scalar(k, str(v), category_info="Platform Define", origin="define")
break
self._sync_ui_to_tab(active)
msg = (
f"Target Platform set to PLATFORM={plat.upper()} "
f"({self.target_platform_def_path})"
)
self.append_log(msg)
self.status_lbl.set_text(msg)
def action_select_target_harness(self, harness_id: str) -> None:
"""Select the testbench harness configuration used when wrapping standalone modules/pipelines."""
self.target_harness_kind = harness_id
if self.compiler:
self.compiler.target_harness = harness_id
harness_names = {
"hda_analog": "HDA Analog Duplex",
"hda_generic": "HDA Generic + DMIC / HDMI",
"sdw_alh": "SoundWire ALH Jack Duplex",
"ssp_nocodec": "NoCodec SSP0 I2S Duplex",
"dmic_capture": "PDM DMIC Capture",
"hdmi_playback": "HDMI Display Audio",
"bt_ssp": "Bluetooth Sideband SSP",
"deep_buffer": "Deep Buffer Playback",
}
h_label = harness_names.get(harness_id, harness_id)
msg = f"Testbench Harness Config set to: {h_label} [{harness_id}] (PLATFORM={self.target_platform})"
self.append_log(msg)
self.status_lbl.set_text(msg)
def action_select_platform_def(self, rel_path: str) -> None:
"""Select a platform definition file from platform/intel/*.conf and apply its target config."""
self.target_platform_def_path = rel_path
if self.compiler:
self.compiler.extra_platform_conf = rel_path
stem = os.path.splitext(os.path.basename(rel_path))[0]
if stem in ("tgl", "mtl", "lnl", "ptl"):
self.target_platform = stem
if self.compiler:
self.compiler.target_platform = stem
if hasattr(self, "target_platform_action"):
self.target_platform_action.set_state(GLib.Variant.new_string(stem))
applied_defs: List[str] = []
has_objs = False
abs_p = ""
if self.workspace:
abs_p = os.path.join(self.workspace.root_dir, rel_path)
for pdef in self.workspace.platform_definitions:
if pdef.get("rel_path") == rel_path:
has_objs = bool(pdef.get("has_objects", False))
p_defs = pdef.get("defines", {})
active = self.get_active_tab()
if isinstance(p_defs, dict) and p_defs:
for k, v in p_defs.items():
applied_defs.append(f"{k}={v}")
if active and active.canvas.vm:
active.canvas.vm.defines[k] = str(v)
def_node = active.canvas.vm.root_config.get_child("Define (Active Variables)")
if def_node is not None:
def_node.set_scalar(
k,
str(v),
category_info=f"From {rel_path}",
origin="instance",
)
break
active = self.get_active_tab()
if active is not None:
self._sync_ui_to_tab(active)
defs_preview = f" ({', '.join(applied_defs[:4])}{'…' if len(applied_defs) > 4 else ''})" if applied_defs else ""
msg = f"Selected Platform Definition: {rel_path}{defs_preview}"
self.append_log(msg)
self.status_lbl.set_text(msg)
def action_open_active_platform_def(self) -> Optional[GraphTabPage]:
"""Open the currently selected platform/intel/*.conf definition file in a Main View tab."""
if not self.workspace or not self.target_platform_def_path:
return None
abs_p = os.path.join(self.workspace.root_dir, self.target_platform_def_path)
if os.path.isfile(abs_p):
tab = self.open_conf_file_in_tab(abs_p)
# If the platform file is a pure Define file (0 nodes), switch it to Text Editor view automatically
if tab is not None and tab.canvas.vm is not None and len(tab.canvas.vm.nodes) == 0:
tab.mode_switch_btn.set_active(True)
return tab
return None
def action_select_target_variant(self, output_name: str) -> None:
"""Select a platform topology target configuration (CMakeTargetVariant) and open/configure it for testbench."""
if not self.workspace:
return
self.target_variant_name = output_name
for entry in self.workspace.machine_topologies:
for var in entry.variants:
if var.output_name == output_name:
plat = var.defines.get("PLATFORM", "")
if plat:
self.target_platform = plat
if self.compiler:
self.compiler.target_platform = plat
if hasattr(self, "target_platform_action"):
self.target_platform_action.set_state(GLib.Variant.new_string(plat))
self._on_left_pane_item_selected("topology", entry.conf_path, var.output_name)
msg = (
f"Selected Target Config: {var.output_name} "
f"({entry.name}.conf [{var.defines_str or 'default'}])"
)
self.append_log(msg)
self.status_lbl.set_text(msg)
return
def _build_header_bar(self) -> None:
header = Gtk.HeaderBar()
header.set_show_title_buttons(True)
self.set_titlebar(header)
# Left side: Unified Menubar (File, Edit, View, Target, Help)
self.menubar = self._build_menubar()
header.pack_start(self.menubar)
# Right header controls: Compile + Run in Testbench
self.run_tb_btn = Gtk.Button(label="▶ Run in Testbench")
self.run_tb_btn.add_css_class("suggested-action")
self.run_tb_btn.set_tooltip_text(
"Compile topology and run sof-testbench4 configured & monitored via SOFR network protocol"
)
self.run_tb_btn.connect("clicked", self._on_run_testbench_clicked)
header.pack_end(self.run_tb_btn)
self.compile_btn = Gtk.Button(label="⚙ Compile (.tplg)")
self.compile_btn.set_tooltip_text("Compile current topology/pipeline with alsatplg -p")
self.compile_btn.connect("clicked", self._on_compile_clicked)
header.pack_end(self.compile_btn)
def _build_main_3panel_layout(self) -> None:
# Outer horizontal paned: [Left Panel (25%)] | [Center (50%) + Right (25%) Paned]
self.hpaned_outer = Gtk.Paned.new(Gtk.Orientation.HORIZONTAL)
self.hpaned_outer.set_wide_handle(True)
self.hpaned_outer.set_resize_start_child(False)
self.hpaned_outer.set_resize_end_child(True)
self.hpaned_outer.set_position(
self._saved_hpaned_outer_pos if self._saved_hpaned_outer_pos is not None else 390
)
# Inner horizontal paned: [Middle Graph + Waveforms Panel (50%)] | [Right Notebook (25%)]
self.hpaned_inner = Gtk.Paned.new(Gtk.Orientation.HORIZONTAL)
self.hpaned_inner.set_wide_handle(True)
self.hpaned_inner.set_resize_start_child(False)
self.hpaned_inner.set_resize_end_child(True)
self.hpaned_inner.set_position(
self._saved_hpaned_inner_pos if self._saved_hpaned_inner_pos is not None else 780
)
# 1. Left Hand Panel (Object View, File View & Compile notebook) wrapped in high-level panel border
self.left_panel = LeftNavigationPanel(
on_item_selected=self._on_left_pane_item_selected,
on_add_module_requested=self._on_add_module_requested,
on_add_pipeline_requested=self._on_add_pipeline_requested,
on_view_source_requested=self._on_view_source_requested,
)
self.left_panel.vpaned_main.set_position(self._saved_left_vpaned_main_pos)
self.left_panel.vpaned_top.set_position(self._saved_left_vpaned_top_pos)
self.left_panel.vpaned_bot.set_position(self._saved_left_vpaned_bot_pos)
left_panel_frame = Gtk.Frame()
left_panel_frame.add_css_class("high-level-panel")