Repository navigation
Expand file tree
/
Copy pathmodel.py
More file actions
537 lines (470 loc) · 17.9 KB
/
Copy pathmodel.py
File metadata and controls
537 lines (470 loc) · 17.9 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
# SPDX-License-Identifier: BSD-3-Clause
"""Data models for SOF Topology2 AST, Classes, Graph Nodes/Edges, and Attributes."""
from __future__ import annotations
from dataclasses import dataclass, field
import datetime
import os
import sys
import threading
import traceback
from typing import Any, Callable, Dict, IO, List, Optional, Set, Tuple
_DEBUG_LOCK = threading.Lock()
_DEBUG_ENABLED: bool = False
_DEBUG_LOG_PATH: str = ""
_DEBUG_FH: Optional[IO[str]] = None
_ORIG_EXCEPTHOOK = sys.excepthook
_ORIG_THREAD_EXCEPTHOOK = getattr(threading, "excepthook", None)
def _now_ts() -> str:
return datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f")[:-3]
def enable_debug_logging(log_path: str = "sof-builder-debug.log") -> str:
"""Enable GUI debug logging of all user actions and command outputs to `log_path`."""
global _DEBUG_ENABLED, _DEBUG_LOG_PATH, _DEBUG_FH
abs_path = os.path.abspath(log_path)
parent = os.path.dirname(abs_path)
if parent:
os.makedirs(parent, exist_ok=True)
with _DEBUG_LOCK:
if _DEBUG_FH is not None:
try:
_DEBUG_FH.close()
except Exception:
pass
_DEBUG_FH = open(abs_path, "w", encoding="utf-8", buffering=1)
_DEBUG_LOG_PATH = abs_path
_DEBUG_ENABLED = True
_DEBUG_FH.write(
f"================================================================================\n"
f"SOF Builder — Debug Session Log\n"
f"Started : {_now_ts()}\n"
f"PID : {os.getpid()}\n"
f"CWD : {os.getcwd()}\n"
f"Argv : {' '.join(sys.argv)}\n"
f"LogFile : {abs_path}\n"
f"================================================================================\n"
)
_DEBUG_FH.flush()
def _custom_excepthook(exc_type: Any, exc_value: Any, exc_tb: Any) -> None:
tb_str = "".join(traceback.format_exception(exc_type, exc_value, exc_tb))
debug_log_line("EXCEPTION", f"Uncaught exception:\n{tb_str.rstrip()}")
_ORIG_EXCEPTHOOK(exc_type, exc_value, exc_tb)
def _custom_thread_excepthook(args: Any) -> None:
tb_str = "".join(
traceback.format_exception(args.exc_type, args.exc_value, args.exc_traceback)
)
tname = getattr(args.thread, "name", "thread")
debug_log_line("THREAD-EXCEPTION", f"Uncaught exception in {tname}:\n{tb_str.rstrip()}")
if _ORIG_THREAD_EXCEPTHOOK is not None:
_ORIG_THREAD_EXCEPTHOOK(args)
sys.excepthook = _custom_excepthook
if hasattr(threading, "excepthook"):
threading.excepthook = _custom_thread_excepthook
return abs_path
def is_debug_enabled() -> bool:
return _DEBUG_ENABLED
def get_debug_log_path() -> str:
return _DEBUG_LOG_PATH
def debug_log_line(tag: str, message: str) -> None:
"""Write a timestamped line or multi-line entry to the debug log file if enabled."""
if not _DEBUG_ENABLED or _DEBUG_FH is None:
return
ts = _now_ts()
with _DEBUG_LOCK:
try:
lines = str(message).splitlines() or [""]
_DEBUG_FH.write(f"[{ts}] [{tag}] {lines[0]}\n")
for extra_line in lines[1:]:
_DEBUG_FH.write(f" {extra_line}\n")
_DEBUG_FH.flush()
except Exception:
pass
def debug_log_action(category: str, action: str, details: str = "") -> None:
"""Log an interactive user action (menu, button, canvas drag/click, kcontrol, attribute edit, etc.)."""
if not _DEBUG_ENABLED or _DEBUG_FH is None:
return
suffix = f" | {details}" if details else ""
debug_log_line(f"USER:{category}", f"{action}{suffix}")
def debug_log_command(
subsystem: str,
command: str,
returncode: Optional[int] = None,
stdout: str = "",
stderr: str = "",
extra: str = "",
) -> None:
"""Log an external command or SOFR protocol operation alongside its full output."""
if not _DEBUG_ENABLED or _DEBUG_FH is None:
return
ts = _now_ts()
with _DEBUG_LOCK:
try:
rc_part = f" (rc={returncode})" if returncode is not None else ""
ex_part = f" [{extra}]" if extra else ""
_DEBUG_FH.write(f"[{ts}] [CMD:{subsystem}] $ {command}{rc_part}{ex_part}\n")
if stdout and stdout.strip():
_DEBUG_FH.write(" --- stdout ---\n")
for l in stdout.rstrip().splitlines():
_DEBUG_FH.write(f" {l}\n")
if stderr and stderr.strip():
_DEBUG_FH.write(" --- stderr ---\n")
for l in stderr.rstrip().splitlines():
_DEBUG_FH.write(f" {l}\n")
_DEBUG_FH.flush()
except Exception:
pass
@dataclass
class AttrConstraint:
"""Value constraints for a Class DefineAttribute."""
valid_values: List[str] = field(default_factory=list)
tuple_values: List[str] = field(default_factory=list)
@dataclass
class AttrDef:
"""Definition of a Class attribute from DefineAttribute and attributes {} block."""
name: str
attr_type: str = "string"
token_ref: str = ""
constraints: Optional[AttrConstraint] = None
is_constructor: bool = False
is_mandatory: bool = False
is_immutable: bool = False
is_deprecated: bool = False
is_unique: bool = False
description: str = ""
@property
def flags_summary(self) -> str:
flags = []
if self.is_constructor:
flags.append("constructor")
if self.is_mandatory:
flags.append("mandatory")
if self.is_immutable:
flags.append("immutable")
if self.is_unique:
flags.append("unique")
if self.is_deprecated:
flags.append("deprecated")
if self.constraints and self.constraints.valid_values:
vals = ", ".join(self.constraints.valid_values[:4])
if len(self.constraints.valid_values) > 4:
vals += ", ..."
flags.append(f"[{vals}]")
return " | ".join(flags)
@dataclass
class ConfigNode:
"""Hierarchical configuration tree node representing attributes and sub-objects."""
key: str
value: Any = None
node_type: str = "scalar" # "scalar", "object", "array", "section", "define"
category_info: str = ""
is_immutable: bool = False
is_mandatory: bool = False
is_constructor: bool = False
valid_values: List[str] = field(default_factory=list)
origin: str = "" # "default", "pipeline", "instance", "define"
children: List["ConfigNode"] = field(default_factory=list)
def get_child(self, key: str) -> Optional["ConfigNode"]:
for ch in self.children:
if ch.key == key:
return ch
return None
def get_scalar(self, key: str, default: Any = None) -> Any:
ch = self.get_child(key)
if ch is not None and ch.node_type == "scalar":
return ch.value
return default
def set_scalar(
self,
key: str,
value: Any,
category_info: str = "",
origin: str = "instance",
is_immutable: bool = False,
is_mandatory: bool = False,
is_constructor: bool = False,
valid_values: Optional[List[str]] = None,
) -> "ConfigNode":
ch = self.get_child(key)
if ch is None:
ch = ConfigNode(
key=key,
value=str(value),
node_type="scalar",
category_info=category_info,
origin=origin,
is_immutable=is_immutable,
is_mandatory=is_mandatory,
is_constructor=is_constructor,
valid_values=list(valid_values) if valid_values else [],
)
self.children.append(ch)
else:
ch.value = str(value)
if category_info:
ch.category_info = category_info
if origin:
ch.origin = origin
if valid_values:
ch.valid_values = list(valid_values)
return ch
def clone(self) -> "ConfigNode":
return ConfigNode(
key=self.key,
value=self.value,
node_type=self.node_type,
category_info=self.category_info,
is_immutable=self.is_immutable,
is_mandatory=self.is_mandatory,
is_constructor=self.is_constructor,
valid_values=list(self.valid_values),
origin=self.origin,
children=[c.clone() for c in self.children],
)
@dataclass
class TplgClassDef:
"""Represents a Topology2 Class.<category>.<name> definition."""
category: str # "Base", "Widget", "Pipeline", "Dai", "PCM", "Control", etc.
name: str
source_file: str
rel_path: str
description: str = ""
attributes: Dict[str, AttrDef] = field(default_factory=dict)
defaults: Dict[str, Any] = field(default_factory=dict)
constructor_attrs: List[str] = field(default_factory=list)
unique_attr: str = "instance"
extends_class: Optional[str] = None
widgets: List[Dict[str, Any]] = field(default_factory=list)
routes: List[Dict[str, str]] = field(default_factory=list)
controls: List[Dict[str, Any]] = field(default_factory=list)
sub_objects: List[ConfigNode] = field(default_factory=list)
config_tree: ConfigNode = field(default_factory=lambda: ConfigNode("root", node_type="object"))
@property
def full_name(self) -> str:
return f"Class.{self.category}.{self.name}"
@dataclass
class GraphPort:
"""Input or output connection pin on a GraphNode."""
id: str
name: str
direction: str # "in" or "out"
port_type: str = "audio" # "audio", "control", "host", "dai"
rel_x: float = 0.0
rel_y: float = 0.0
def clone(self) -> "GraphPort":
return GraphPort(
id=self.id,
name=self.name,
direction=self.direction,
port_type=self.port_type,
rel_x=self.rel_x,
rel_y=self.rel_y,
)
@dataclass
class GraphNode:
"""Visual and logical node in the Topology2 graph."""
id: str
title: str
subtitle: str
category: str # "host", "widget", "mix", "dai", "pcm", "control", "base", "pipeline"
class_category: str = "Widget"
class_name: str = ""
instance_id: str = "1"
pipeline_id: Optional[int] = None
pipeline_class: Optional[str] = None
parent_node_id: Optional[str] = None
x: float = 0.0
y: float = 0.0
width: float = 190.0
height: float = 86.0
in_ports: List[GraphPort] = field(default_factory=list)
out_ports: List[GraphPort] = field(default_factory=list)
in_fmt_badge: str = ""
out_fmt_badge: str = ""
badges: List[str] = field(default_factory=list)
config: ConfigNode = field(default_factory=lambda: ConfigNode("attributes", node_type="object"))
class_def: Optional[TplgClassDef] = None
source_file: str = ""
def clone(self) -> "GraphNode":
return GraphNode(
id=self.id,
title=self.title,
subtitle=self.subtitle,
category=self.category,
class_category=self.class_category,
class_name=self.class_name,
instance_id=self.instance_id,
pipeline_id=self.pipeline_id,
pipeline_class=self.pipeline_class,
parent_node_id=self.parent_node_id,
x=self.x,
y=self.y,
width=self.width,
height=self.height,
in_ports=[p.clone() for p in self.in_ports],
out_ports=[p.clone() for p in self.out_ports],
in_fmt_badge=self.in_fmt_badge,
out_fmt_badge=self.out_fmt_badge,
badges=list(self.badges),
config=self.config.clone(),
class_def=self.class_def,
source_file=self.source_file,
)
@dataclass
class GraphEdge:
"""Directed route connecting source_node -> sink_node."""
id: str
source_node: str
sink_node: str
source_port: str = "out0"
sink_port: str = "in0"
control: str = ""
pipeline_id: Optional[int] = None
is_inter_pipeline: bool = False
config: ConfigNode = field(default_factory=lambda: ConfigNode("route", node_type="object"))
def clone(self) -> "GraphEdge":
return GraphEdge(
id=self.id,
source_node=self.source_node,
sink_node=self.sink_node,
source_port=self.source_port,
sink_port=self.sink_port,
control=self.control,
pipeline_id=self.pipeline_id,
is_inter_pipeline=self.is_inter_pipeline,
config=self.config.clone(),
)
@dataclass
class PipelineContainer:
"""Visual container grouping nodes that belong to the same pipeline index."""
pipeline_id: int
class_name: str
direction: str = "playback"
x: float = 0.0
y: float = 0.0
width: float = 300.0
height: float = 160.0
enabled_by: str = ""
warning_text: str = ""
config: ConfigNode = field(default_factory=lambda: ConfigNode("pipeline", node_type="object"))
def clone(self) -> "PipelineContainer":
return PipelineContainer(
pipeline_id=self.pipeline_id,
class_name=self.class_name,
direction=self.direction,
x=self.x,
y=self.y,
width=self.width,
height=self.height,
enabled_by=self.enabled_by,
warning_text=self.warning_text,
config=self.config.clone(),
)
@dataclass
class CMakeTargetVariant:
"""A concrete topology build target from production/ or development/ CMake files."""
input_conf: str
output_name: str
defines_str: str
defines: Dict[str, str] = field(default_factory=dict)
cmake_file: str = ""
category: str = "production" # "production" or "development"
@dataclass
class MachineTopologyEntry:
"""Represents a top-level .conf topology file and its CMake target variants."""
name: str
conf_path: str
rel_path: str
variants: List[CMakeTargetVariant] = field(default_factory=list)
@dataclass
class GraphViewModel:
"""Complete graph model currently displayed in the center canvas."""
title: str
subtitle: str = ""
view_kind: str = "topology" # "base_class", "module", "pipeline", "topology"
source_file: str = ""
defines: Dict[str, str] = field(default_factory=dict)
nodes: Dict[str, GraphNode] = field(default_factory=dict)
edges: List[GraphEdge] = field(default_factory=list)
containers: Dict[int, PipelineContainer] = field(default_factory=dict)
root_config: ConfigNode = field(default_factory=lambda: ConfigNode("root", node_type="object"))
dirty: bool = False
graph_structure_modified: bool = False
target_variant: Optional[CMakeTargetVariant] = None
def clone(self) -> "GraphViewModel":
return GraphViewModel(
title=self.title,
subtitle=self.subtitle,
view_kind=self.view_kind,
source_file=self.source_file,
defines=dict(self.defines),
nodes={nid: n.clone() for nid, n in self.nodes.items()},
edges=[e.clone() for e in self.edges],
containers={pid: c.clone() for pid, c in self.containers.items()},
root_config=self.root_config.clone(),
dirty=self.dirty,
graph_structure_modified=self.graph_structure_modified,
target_variant=self.target_variant,
)
@dataclass
class GraphHistoryEntry:
"""Snapshot of a GraphViewModel and selection state for Undo/Redo."""
description: str
vm_snapshot: GraphViewModel
selected_node_id: Optional[str] = None
selected_node_ids: Set[str] = field(default_factory=set)
selected_edge_id: Optional[str] = None
selected_container_id: Optional[int] = None
selected_container_ids: Set[int] = field(default_factory=set)
class UndoRedoManager:
"""Bounded Undo/Redo stack managing GraphHistoryEntry snapshots."""
def __init__(
self,
max_depth: int = 100,
on_history_changed: Optional[Callable[[], None]] = None,
) -> None:
self.max_depth = max_depth
self.on_history_changed = on_history_changed
self.undo_stack: List[GraphHistoryEntry] = []
self.redo_stack: List[GraphHistoryEntry] = []
def clear(self) -> None:
self.undo_stack.clear()
self.redo_stack.clear()
if self.on_history_changed:
self.on_history_changed()
@property
def can_undo(self) -> bool:
return bool(self.undo_stack)
@property
def can_redo(self) -> bool:
return bool(self.redo_stack)
@property
def undo_description(self) -> Optional[str]:
return self.undo_stack[-1].description if self.undo_stack else None
@property
def redo_description(self) -> Optional[str]:
return self.redo_stack[-1].description if self.redo_stack else None
def push_undo_entry(self, entry: GraphHistoryEntry) -> None:
self.undo_stack.append(entry)
if len(self.undo_stack) > self.max_depth:
self.undo_stack.pop(0)
self.redo_stack.clear()
if self.on_history_changed:
self.on_history_changed()
def undo(self, current_entry: GraphHistoryEntry) -> Optional[Tuple[GraphHistoryEntry, str]]:
if not self.undo_stack:
return None
prev_entry = self.undo_stack.pop()
action_desc = prev_entry.description
current_entry.description = action_desc
self.redo_stack.append(current_entry)
if self.on_history_changed:
self.on_history_changed()
return (prev_entry, action_desc)
def redo(self, current_entry: GraphHistoryEntry) -> Optional[Tuple[GraphHistoryEntry, str]]:
if not self.redo_stack:
return None
next_entry = self.redo_stack.pop()
action_desc = next_entry.description
current_entry.description = action_desc
self.undo_stack.append(current_entry)
if self.on_history_changed:
self.on_history_changed()
return (next_entry, action_desc)