diff --git a/sof-builder/sof_builder/compiler.py b/sof-builder/sof_builder/compiler.py index 0cd74ab..7cf2fa3 100644 --- a/sof-builder/sof_builder/compiler.py +++ b/sof-builder/sof_builder/compiler.py @@ -426,7 +426,32 @@ def _find_alsatplg(self) -> str: return c return "alsatplg" - def _ensure_abi_conf(self) -> str: + @staticmethod + def _format_abi_conf_from_bytes_str(bytes_str: str) -> str: + cleaned = ",".join(part.strip() for part in (bytes_str or "").split(",") if part.strip()) + return ( + "Object.Base.manifest.1 {\n" + "\tname \"sof_manifest\"\n" + "\tObject.Base.data.1 {\n" + "\t\tname \"SOF ABI\"\n" + f"\t\tbytes\t\"{cleaned}\"\n" + "\t}\n" + "}\n" + ) + + def _ensure_abi_conf(self, vm: Optional[GraphViewModel] = None) -> str: + # Preserve binary SOF ABI bytes when recompiling a decoded or versioned GraphViewModel + if vm is not None and vm.root_config is not None: + manifest_node = vm.root_config.get_child("Object.Base.manifest") + if manifest_node is not None: + bytes_str = str(manifest_node.get_scalar("sof_abi_bytes", "") or "").strip() + if bytes_str: + os.makedirs(self.build_dir, exist_ok=True) + bin_abi_path = os.path.join(self.build_dir, "abi_binary.conf") + with open(bin_abi_path, "w", encoding="utf-8") as f: + f.write(self._format_abi_conf_from_bytes_str(bytes_str)) + return bin_abi_path + abi_path = os.path.join(self.build_dir, "abi.conf") if os.path.isfile(abi_path): return abi_path @@ -435,10 +460,10 @@ def _ensure_abi_conf(self) -> str: sof_root, _ = resolve_sof_and_workspace_roots(self.topology2_root) tplg_repo_root = os.path.abspath(os.path.join(self.topology2_root, "..")) abi_source = "" - if sof_root and os.path.isdir(os.path.join(sof_root, "src")): - abi_source = sof_root - elif os.path.isfile(os.path.join(tplg_repo_root, "include", "kernel", "abi.h")): + if os.path.isfile(os.path.join(tplg_repo_root, "include", "kernel", "abi.h")): abi_source = tplg_repo_root + elif sof_root and os.path.isdir(os.path.join(sof_root, "src")): + abi_source = sof_root if os.path.isfile(get_abi) and abi_source: try: @@ -464,10 +489,12 @@ def compile_graph( self, vm: GraphViewModel, extra_defines: str = "", + prefer_full_topology: bool = False, + output_tplg_path: Optional[str] = None, ) -> CompileResult: """Serialize vm to .conf, prepend abi.conf, and compile to .tplg with alsatplg -p.""" os.makedirs(self.build_dir, exist_ok=True) - abi_path = self._ensure_abi_conf() + abi_path = self._ensure_abi_conf(vm) with open(abi_path, "r", encoding="utf-8") as f: abi_text = f.read() @@ -477,13 +504,14 @@ def compile_graph( target_platform=self.target_platform, target_harness=self.target_harness, extra_platform_conf=self.extra_platform_conf, + prefer_full_topology=prefer_full_topology, ) if extra_defines.strip(): defines_str = f"{defines_str},{extra_defines.strip()}" if defines_str else extra_defines.strip() safe_name = re.sub(r"[^A-Za-z0-9_\-]", "_", vm.title) or "custom_topology" conf_path = os.path.join(self.build_dir, f"{safe_name}.conf") - tplg_path = os.path.join(self.build_dir, f"{safe_name}.tplg") + tplg_path = os.path.abspath(output_tplg_path) if output_tplg_path else os.path.join(self.build_dir, f"{safe_name}.tplg") with open(conf_path, "w", encoding="utf-8") as f: f.write(abi_text + "\n" + body_text) diff --git a/sof-builder/sof_builder/model.py b/sof-builder/sof_builder/model.py index 79fb048..c540cdc 100644 --- a/sof-builder/sof_builder/model.py +++ b/sof-builder/sof_builder/model.py @@ -5,6 +5,7 @@ from dataclasses import dataclass, field import datetime import os +import re import subprocess import sys import threading @@ -442,6 +443,8 @@ class GraphViewModel: dirty: bool = False graph_structure_modified: bool = False target_variant: Optional[CMakeTargetVariant] = None + source_tplg: str = "" + binary_match_summary: str = "" def clone(self) -> "GraphViewModel": return GraphViewModel( @@ -457,6 +460,8 @@ def clone(self) -> "GraphViewModel": dirty=self.dirty, graph_structure_modified=self.graph_structure_modified, target_variant=self.target_variant, + source_tplg=self.source_tplg, + binary_match_summary=self.binary_match_summary, ) @@ -578,8 +583,8 @@ def resolve_sof_and_workspace_roots(topology2_root: str = "") -> Tuple[str, str] break query_cwd = topology2_root if (topology2_root and os.path.isdir(topology2_root)) else sof_utils_root - if not sof_root: - sof_root = west_project_path("sof", cwd=query_cwd) or west_project_path("sof", cwd=sof_utils_root) + if not sof_root and topology2_root: + sof_root = west_project_path("sof", cwd=query_cwd) workspace_root = west_topdir(cwd=query_cwd) or west_topdir(cwd=sof_utils_root) @@ -598,6 +603,9 @@ def resolve_sof_and_workspace_roots(topology2_root: str = "") -> Tuple[str, str] if not workspace_root: workspace_root = tplg_repo_parent + if not sof_root: + sof_root = west_project_path("sof", cwd=sof_utils_root) + if not sof_root: sib_sof = os.path.abspath(os.path.join(sof_utils_root, "..", "sof")) if os.path.isdir(os.path.join(sib_sof, "src")): @@ -612,14 +620,56 @@ def resolve_sof_and_workspace_roots(topology2_root: str = "") -> Tuple[str, str] return (sof_root, workspace_root) -def discover_topology2_dir(initial_dir: Optional[str] = None, saved_dir: str = "") -> str: - """Locate a topology2 directory across CLI arg, env vars, west workspace, and sibling repos.""" - if initial_dir: - abs_init = os.path.abspath(initial_dir) - if os.path.isdir(abs_init): - return abs_init +_ABI_MACRO_RE = re.compile(r"^\s*#\s*define\s+(SOF_ABI_(?:MAJOR|MINOR|PATCH))\s+(\d+)", re.MULTILINE) + +def parse_abi_header_text(text: str) -> Optional[Tuple[int, int, int]]: + """Parse (SOF_ABI_MAJOR, SOF_ABI_MINOR, SOF_ABI_PATCH) from kernel/abi.h text.""" + vals: Dict[str, int] = {} + for m in _ABI_MACRO_RE.finditer(text or ""): + vals[m.group(1)] = int(m.group(2)) + if "SOF_ABI_MAJOR" in vals and "SOF_ABI_MINOR" in vals and "SOF_ABI_PATCH" in vals: + return (vals["SOF_ABI_MAJOR"], vals["SOF_ABI_MINOR"], vals["SOF_ABI_PATCH"]) + return None + + +def read_workspace_sof_abi(topology2_root: str) -> Optional[Tuple[int, int, int]]: + """Read (major, minor, patch) SOF ABI version for a topology2 directory.""" + if not topology2_root: + return None + norm = os.path.abspath(topology2_root) + legacy_sof = os.path.abspath(os.path.join(norm, "..", "..", "..")) + tplg_repo_root = os.path.abspath(os.path.join(norm, "..")) + sof_root, _ = resolve_sof_and_workspace_roots(norm) + candidates = [ + os.path.join(tplg_repo_root, "include", "kernel", "abi.h"), + os.path.join(legacy_sof, "src", "include", "kernel", "abi.h"), + os.path.join(norm, "include", "kernel", "abi.h"), + os.path.join(norm, "abi.h"), + ] + if sof_root: + candidates.extend([ + os.path.join(sof_root, "src", "include", "kernel", "abi.h"), + os.path.join(sof_root, "include", "kernel", "abi.h"), + ]) + for cpath in candidates: + if cpath and os.path.isfile(cpath): + try: + with open(cpath, "r", encoding="utf-8", errors="replace") as fh: + parsed = parse_abi_header_text(fh.read()) + if parsed is not None: + return parsed + except Exception: + pass + return None + + +def discover_all_topology2_dirs(preferred_dir: str = "") -> List[str]: + """Return unique existing topology2 source directories ordered by discovery priority.""" candidates: List[str] = [] + if preferred_dir: + candidates.append(os.path.abspath(preferred_dir)) + env_tplg2 = os.environ.get("SOF_TOPOLOGY2_DIR", "").strip() if env_tplg2: candidates.append(os.path.abspath(env_tplg2)) @@ -629,8 +679,6 @@ def discover_topology2_dir(initial_dir: Optional[str] = None, saved_dir: str = " 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 saved_dir: - candidates.append(saved_dir) sof_utils_root = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "..")) for cwd_probe in (os.getcwd(), sof_utils_root): @@ -641,7 +689,6 @@ def discover_topology2_dir(initial_dir: Optional[str] = None, saved_dir: str = " if west_sof: candidates.append(os.path.join(west_sof, "tools", "topology", "topology2")) - # Check current working directory and ancestors cur = os.path.abspath(os.getcwd()) for _ in range(5): candidates.append(os.path.join(cur, "topology2")) @@ -653,16 +700,60 @@ def discover_topology2_dir(initial_dir: Optional[str] = None, saved_dir: str = " break cur = parent - # Check sibling checkouts relative to sof-utils root pkg_root = os.path.abspath(os.path.join(sof_utils_root, "..")) for sib in ("sof-topologies", "sof-topology"): candidates.append(os.path.join(pkg_root, sib, "topology2")) candidates.append(os.path.join(pkg_root, "sof", "tools", "topology", "topology2")) + # Bounded 1-level sibling checkout scan in pkg_root to discover versioned local checkouts + if os.path.isdir(pkg_root): + try: + for name in sorted(os.listdir(pkg_root)): + sub = os.path.join(pkg_root, name) + if not os.path.isdir(sub): + continue + for rel in ("topology2", os.path.join("tools", "topology", "topology2")): + cand = os.path.join(sub, rel) + if os.path.isdir(os.path.join(cand, "include")): + candidates.append(cand) + except Exception: + pass + + out: List[str] = [] + seen: Set[str] = set() + for c in candidates: + if not c: + continue + ap = os.path.abspath(c) + if ap not in seen and os.path.isdir(ap) and os.path.isdir(os.path.join(ap, "include")): + seen.add(ap) + out.append(ap) + return out + + +def discover_topology2_dir(initial_dir: Optional[str] = None, saved_dir: str = "") -> str: + """Locate a topology2 directory across CLI arg, env vars, west workspace, and sibling repos.""" + if initial_dir: + abs_init = os.path.abspath(initial_dir) + if os.path.isdir(abs_init): + return abs_init + if os.path.isfile(abs_init) and not abs_init.lower().endswith(".tplg"): + cur = os.path.dirname(abs_init) + for _ in range(6): + if os.path.isdir(os.path.join(cur, "include")) and ( + os.path.basename(cur) == "topology2" or os.path.isdir(os.path.join(cur, "platform")) + ): + return cur + parent = os.path.dirname(cur) + if parent == cur: + break + cur = parent + + candidates: List[str] = [] + if saved_dir: + candidates.append(saved_dir) + candidates.extend(discover_all_topology2_dirs()) 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 "" diff --git a/sof-builder/sof_builder/parser.py b/sof-builder/sof_builder/parser.py index 1bd71d1..a0c79ce 100644 --- a/sof-builder/sof_builder/parser.py +++ b/sof-builder/sof_builder/parser.py @@ -2,6 +2,8 @@ """Recursive parser and graph builder for ALSA Topology2 (.conf) and CMake targets.""" from __future__ import annotations +import ast +import operator import os import re from pathlib import Path @@ -1033,6 +1035,23 @@ def resolve_one(pname: str) -> None: for pname in list(self.pipeline_classes.keys()): resolve_one(pname) + def _expand_ast_children_inline( + self, + children: List[AstStmt], + defines: Dict[str, str], + ) -> List[AstStmt]: + """Recursively expand IncludeByKey.* blocks inside compound AST bodies (e.g., input_audio_format).""" + expanded: List[AstStmt] = [] + for ch in children: + if ch.stmt_type == "block" and ch.key.startswith("IncludeByKey."): + _vn, _vv, matched, _skipped = self._match_include_by_key(ch, defines) + for _pat, mch in matched: + if mch.stmt_type == "block": + expanded.extend(self._expand_ast_children_inline(mch.children, defines)) + else: + expanded.append(ch) + return expanded + def _ast_to_config_node( self, stmt: AstStmt, @@ -1056,7 +1075,8 @@ def _ast_to_config_node( category_info=stmt.stmt_type, origin=origin, ) - for idx, ch in enumerate(stmt.children): + flat_children = self._expand_ast_children_inline(stmt.children, defs) + for idx, ch in enumerate(flat_children): if ch.stmt_type == "block" and ch.key == "{}": elem = self._ast_to_config_node(ch, defs, origin=origin) elem.key = f"[{idx}]" @@ -1065,6 +1085,36 @@ def _ast_to_config_node( node.children.append(self._ast_to_config_node(ch, defs, origin=origin)) return node + @staticmethod + def _eval_int_arith(expr: str) -> Optional[int]: + """Safely evaluate integer arithmetic expressions from alsaconf $[ ... ] syntax.""" + ops = { + ast.Add: operator.add, + ast.Sub: operator.sub, + ast.Mult: operator.mul, + ast.Div: operator.floordiv, + ast.FloorDiv: operator.floordiv, + ast.Mod: operator.mod, + } + uops = {ast.UAdd: operator.pos, ast.USub: operator.neg} + + def eval_node(n: ast.AST) -> int: + if isinstance(n, ast.Expression): + return eval_node(n.body) + if isinstance(n, ast.Constant) and isinstance(n.value, (int, float)) and not isinstance(n.value, bool): + return int(n.value) + if isinstance(n, ast.BinOp) and type(n.op) in ops: + return int(ops[type(n.op)](eval_node(n.left), eval_node(n.right))) + if isinstance(n, ast.UnaryOp) and type(n.op) in uops: + return int(uops[type(n.op)](eval_node(n.operand))) + raise ValueError("Unsupported arithmetic node") + + try: + tree = ast.parse(expr.strip(), mode="eval") + return eval_node(tree) + except Exception: + return None + def _substitute_vars(self, text: str, defines: Dict[str, str]) -> str: if "$" not in text: return text @@ -1077,7 +1127,13 @@ def repl(m: re.Match) -> str: return str(self.global_defines[vname]) return m.group(0) - return re.sub(r"\$([A-Za-z0-9_]+)", repl, text) + substituted = re.sub(r"\$([A-Za-z0-9_]+)", repl, text) + if "$[" in substituted: + def arith_repl(m: re.Match) -> str: + val = self._eval_int_arith(m.group(1)) + return str(val) if val is not None else m.group(0) + substituted = re.sub(r"\$\[([^\[\]]+)\]", arith_repl, substituted) + return substituted def _parse_cmake_targets(self) -> Dict[str, List[CMakeTargetVariant]]: """Parse production/tplg-targets-*.cmake and development/tplg-targets*.cmake.""" @@ -1495,26 +1551,70 @@ def build_graph_for_topology( raw_routes: List[Tuple[Dict[str, str], Optional[int]]] = [] top_widgets: List[Tuple[str, str, List[AstStmt]]] = [] - # Process top-level Object.Pipeline, Object.Dai, Object.PCM, Object.Widget, Object.Base.route + # Temporarily apply inline Class.* definitions from expanded_stmts so file-local + # pipeline/widget classes (e.g., Class.Pipeline."custom-capture") override global scans. + saved_pipelines = dict(self.pipeline_classes) + saved_modules = dict(self.processing_modules) + saved_bases = dict(self.base_classes) + inline_pipelines: List[str] = [] for st in expanded_stmts: - if not st.key.startswith("Object."): - continue - parts = split_dotted_key(st.key) - if len(parts) < 2: - continue - obj_cat = parts[1] + if st.stmt_type == "block" and st.key.startswith("Class."): + cparts = split_dotted_key(st.key) + if len(cparts) >= 3: + cat, cname = cparts[1], cparts[2] + cdef = self._build_class_def(cat, cname, st, conf_path, rel_path) + if cat == "Pipeline": + self.pipeline_classes[cname] = cdef + inline_pipelines.append(cname) + elif cat == "Widget": + self.processing_modules[cname] = cdef + else: + self.base_classes[f"{cat}.{cname}"] = cdef + if inline_pipelines: + self._resolve_pipeline_inheritance() - if obj_cat == "Pipeline": - self._process_topology_pipeline_stmt(st, parts, vm, defines, raw_routes, conf_path) - elif obj_cat == "Widget": - self._collect_topology_widget_stmt(st, parts, top_widgets) - elif obj_cat == "Base": - self._collect_topology_route_stmt(st, parts, defines, raw_routes) - elif obj_cat == "Dai": - self._process_topology_dai_stmt(st, parts, vm, defines, conf_path) - elif obj_cat == "PCM": - self._process_topology_pcm_stmt(st, parts, vm, defines, conf_path) + try: + # Process top-level Object.Pipeline, Object.Dai, Object.PCM, Object.Widget, Object.Base.route + for st in expanded_stmts: + if not st.key.startswith("Object."): + continue + parts = split_dotted_key(st.key) + if len(parts) < 2: + continue + obj_cat = parts[1] + + if obj_cat == "Pipeline": + self._process_topology_pipeline_stmt(st, parts, vm, defines, raw_routes, conf_path) + elif obj_cat == "Widget": + self._collect_topology_widget_stmt(st, parts, top_widgets) + elif obj_cat == "Base": + self._collect_topology_route_stmt(st, parts, defines, raw_routes) + elif obj_cat == "Dai": + self._process_topology_dai_stmt(st, parts, vm, defines, conf_path) + elif obj_cat == "PCM": + self._process_topology_pcm_stmt(st, parts, vm, defines, conf_path) + + self._finalize_topology_widgets_and_routes( + vm, top_widgets, raw_routes, defines, search_dirs, conf_path, rel_path + ) + self._analyze_unconnected_pipelines(vm, conf_path, defines, search_dirs, skipped_branches) + self.attach_host_copier_io_nodes(vm) + return vm + finally: + self.pipeline_classes = saved_pipelines + self.processing_modules = saved_modules + self.base_classes = saved_bases + def _finalize_topology_widgets_and_routes( + self, + vm: GraphViewModel, + top_widgets: List[Tuple[str, str, List[AstStmt]]], + raw_routes: List[Tuple[Dict[str, str], Optional[int]]], + defines: Dict[str, str], + search_dirs: List[str], + conf_path: str, + rel_path: str, + ) -> None: # First pass over top-level Object.Widget: create/update PipelineContainers from Object.Widget.pipeline custom_pipe_ids: Set[int] = set() nested_pipe_widgets: List[Tuple[str, str, List[AstStmt]]] = [] @@ -1650,10 +1750,6 @@ def build_graph_for_topology( ) ) - self._analyze_unconnected_pipelines(vm, conf_path, defines, search_dirs, skipped_branches) - self.attach_host_copier_io_nodes(vm) - return vm - def _evaluate_topology_file( self, fpath: str, @@ -1725,21 +1821,13 @@ def _evaluate_stmt_list( else: defines.setdefault(ch.key, self._substitute_vars(str(ch.value), defines)) elif st.stmt_type == "block" and st.key.startswith("IncludeByKey."): - parts = split_dotted_key(st.key) - var_name = parts[1] if len(parts) > 1 else "" - var_val = str(defines.get(var_name, "")) - matched_ch: Optional[AstStmt] = None - matched_pattern: str = "" - for ch in st.children: - pattern = strip_quotes(ch.key) - if matched_ch is None and self._key_matches(pattern, var_val): - matched_ch = ch - matched_pattern = pattern - elif skipped_branches is not None: + var_name, var_val, matched, skipped = self._match_include_by_key(st, defines) + if skipped_branches is not None: + for pattern, ch in skipped: skipped_branches.append((var_name, var_val, pattern, ch, current_file)) - if matched_ch is not None: - if matched_ch.stmt_type == "kv" and matched_ch.value: - inc_file = self._substitute_vars(str(matched_ch.value), defines) + for pattern, ch in matched: + if ch.stmt_type == "kv" and ch.value: + inc_file = self._substitute_vars(str(ch.value), defines) inc_path = self.resolve_include(inc_file, search_dirs, current_file) if inc_path: cond = f'{var_name} = "{var_val}" → {inc_file}' @@ -1754,11 +1842,11 @@ def _evaluate_stmt_list( skipped_branches=skipped_branches, ) ) - elif matched_ch.stmt_type == "block": - cond = f'{var_name} = "{var_val}" (matches "{matched_pattern}")' + elif ch.stmt_type == "block": + cond = f'{var_name} = "{var_val}" (matches "{pattern}")' out.extend( self._evaluate_stmt_list( - matched_ch.children, + ch.children, defines, search_dirs, current_file, @@ -1777,6 +1865,46 @@ def _evaluate_stmt_list( def _is_target_override(key: str, defines: Dict[str, str], cli_keys: Set[str]) -> bool: return key in cli_keys and defines.get(key, "") not in ("", "none") + def _match_include_by_key( + self, + st: AstStmt, + defines: Dict[str, str], + ) -> Tuple[str, str, List[Tuple[str, AstStmt]], List[Tuple[str, AstStmt]]]: + """Evaluate both 2-part (IncludeByKey.VAR { pat {...} }) and 3-part (IncludeByKey.VAR.\"pat\" {...}) forms.""" + parts = split_dotted_key(st.key) + var_name = parts[1] if len(parts) > 1 else "" + var_val = self._substitute_vars(str(defines.get(var_name, "")), defines) + matched: List[Tuple[str, AstStmt]] = [] + skipped: List[Tuple[str, AstStmt]] = [] + + if len(parts) >= 3: + pattern = strip_quotes(parts[2]) + synth = AstStmt("block", key=pattern, children=st.children, source_file=st.source_file) + if self._key_matches(pattern, var_val): + matched.append((pattern, synth)) + else: + skipped.append((pattern, synth)) + return var_name, var_val, matched, skipped + + for ch in st.children: + pattern = strip_quotes(ch.key) + if self._key_matches(pattern, var_val): + matched.append((pattern, ch)) + else: + skipped.append((pattern, ch)) + return var_name, var_val, matched, skipped + + @staticmethod + def _has_topology_objects(stmts: List[AstStmt]) -> bool: + """Return True when statements instantiate topology Objects (Pipeline/Dai/PCM/Base/Widget) vs pure Class defs.""" + for st in stmts: + if st.key.startswith("Object."): + return True + if st.stmt_type == "block" and (st.key == "{}" or st.key.startswith("IncludeByKey.")): + if Topology2Workspace._has_topology_objects(st.children): + return True + return False + @staticmethod def _key_matches(pattern: str, val: str) -> bool: if pattern == val: @@ -1948,19 +2076,15 @@ def _expand_inner_include_by_key( out: List[AstStmt] = [] for st in stmts: if st.stmt_type == "block" and st.key.startswith("IncludeByKey."): - parts = split_dotted_key(st.key) - var_name = parts[1] if len(parts) > 1 else "" - var_val = str(defines.get(var_name, "")) - for ch in st.children: - if self._key_matches(strip_quotes(ch.key), var_val): - if ch.stmt_type == "kv" and ch.value: - inc_file = self._substitute_vars(str(ch.value), defines) - inc_path = self.resolve_include(inc_file, search_dirs, current_file) - if inc_path: - out.extend(self._expand_inner_include_by_key(self.get_ast(inc_path), defines, search_dirs, inc_path)) - elif ch.stmt_type == "block": - out.extend(self._expand_inner_include_by_key(ch.children, defines, search_dirs, current_file)) - break + _vn, _vv, matched, _skipped = self._match_include_by_key(st, defines) + for _pat, ch in matched: + if ch.stmt_type == "kv" and ch.value: + inc_file = self._substitute_vars(str(ch.value), defines) + inc_path = self.resolve_include(inc_file, search_dirs, current_file) + if inc_path: + out.extend(self._expand_inner_include_by_key(self.get_ast(inc_path), defines, search_dirs, inc_path)) + elif ch.stmt_type == "block": + out.extend(self._expand_inner_include_by_key(ch.children, defines, search_dirs, current_file)) elif st.stmt_type == "include": inc_path = self.resolve_include(st.key, search_dirs, current_file) if inc_path: @@ -2309,20 +2433,16 @@ def _apply_override_stmts_to_config( val = self._substitute_vars(str(st.value), defines) cfg.set_scalar(st.key, val, origin="instance") elif st.stmt_type == "block" and st.key.startswith("IncludeByKey."): - parts = split_dotted_key(st.key) - var_name = parts[1] if len(parts) > 1 else "" - var_val = str(defines.get(var_name, "")) - for ch in st.children: - if self._key_matches(strip_quotes(ch.key), var_val): - if ch.stmt_type == "kv" and ch.value: - inc_str = self._substitute_vars(str(ch.value), defines) - cfg.set_scalar("included_param_file", inc_str, origin="instance") - inc_path = self.resolve_include(inc_str, search_dirs) - if inc_path: - self._apply_override_stmts_to_config(cfg, self.get_ast(inc_path), defines) - elif ch.stmt_type == "block": - self._apply_override_stmts_to_config(cfg, ch.children, defines) - break + _vn, _vv, matched, _skipped = self._match_include_by_key(st, defines) + for _pat, ch in matched: + if ch.stmt_type == "kv" and ch.value: + inc_str = self._substitute_vars(str(ch.value), defines) + cfg.set_scalar("included_param_file", inc_str, origin="instance") + inc_path = self.resolve_include(inc_str, search_dirs) + if inc_path: + self._apply_override_stmts_to_config(cfg, self.get_ast(inc_path), defines) + elif ch.stmt_type == "block": + self._apply_override_stmts_to_config(cfg, ch.children, defines) elif st.stmt_type == "include": inc_path = self.resolve_include(st.key, search_dirs) if inc_path: @@ -3793,6 +3913,13 @@ def create_new_monolithic_topology_graph(self, name: str = "sof-custom-generic") def build_graph_for_arbitrary_conf_file(self, conf_path: str) -> GraphViewModel: """Open any .conf file and build the appropriate GraphViewModel.""" abs_path = os.path.abspath(conf_path) + for entry in self.machine_topologies: + if os.path.abspath(entry.conf_path) == abs_path: + variant = entry.variants[0] if entry.variants else None + return self.build_graph_for_topology(abs_path, variant) + stmts = self.get_ast(abs_path) + if self._has_topology_objects(stmts): + return self.build_graph_for_topology(abs_path, None) for mname, mdef in self.processing_modules.items(): if os.path.abspath(mdef.source_file) == abs_path: return self.build_graph_for_module(mname) @@ -3802,10 +3929,6 @@ def build_graph_for_arbitrary_conf_file(self, conf_path: str) -> GraphViewModel: for bkey, bdef in self.base_classes.items(): if os.path.abspath(bdef.source_file) == abs_path: return self.build_graph_for_base_class(bkey) - for entry in self.machine_topologies: - if os.path.abspath(entry.conf_path) == abs_path: - variant = entry.variants[0] if entry.variants else None - return self.build_graph_for_topology(abs_path, variant) return self.build_graph_for_topology(abs_path, None) def build_graph_from_conf_text( @@ -3824,36 +3947,39 @@ def build_graph_from_conf_text( ) stmts = parse_conf_text(text, source_file=eval_file) rel_path = os.path.relpath(eval_file, self.root_dir) if source_file else "(Edited Buffer)" - - # Check if the buffer defines a Class.. - for stmt in stmts: - if stmt.stmt_type == "block" and stmt.key.startswith("Class."): - parts = split_dotted_key(stmt.key) - if len(parts) >= 3: - cat = parts[1] - cname = parts[2] - cdef = self._build_class_def(cat, cname, stmt, eval_file, rel_path) - self.all_classes[f"{cat}.{cname}"] = cdef - if cat == "Widget": - self.processing_modules[cname] = cdef - vm = self.build_graph_for_module(cname) - vm.source_file = source_file - vm.dirty = True - return vm - if cat == "Pipeline": - self.pipeline_classes[cname] = cdef - self._resolve_pipeline_inheritance() - vm = self.build_graph_for_pipeline(cname) + has_topo = self._has_topology_objects(stmts) + + # Register Class.. blocks; only short-circuit to a single-class view + # when the buffer does not also instantiate topology Objects (e.g., platform feature files). + if not has_topo: + for stmt in stmts: + if stmt.stmt_type == "block" and stmt.key.startswith("Class."): + parts = split_dotted_key(stmt.key) + if len(parts) >= 3: + cat = parts[1] + cname = parts[2] + cdef = self._build_class_def(cat, cname, stmt, eval_file, rel_path) + self.all_classes[f"{cat}.{cname}"] = cdef + if cat == "Widget": + self.processing_modules[cname] = cdef + vm = self.build_graph_for_module(cname) + vm.source_file = source_file + vm.dirty = True + return vm + if cat == "Pipeline": + self.pipeline_classes[cname] = cdef + self._resolve_pipeline_inheritance() + vm = self.build_graph_for_pipeline(cname) + vm.source_file = source_file + vm.dirty = True + return vm + self.base_classes[f"{cat}.{cname}"] = cdef + vm = self.build_graph_for_base_class(f"{cat}.{cname}") vm.source_file = source_file vm.dirty = True return vm - self.base_classes[f"{cat}.{cname}"] = cdef - vm = self.build_graph_for_base_class(f"{cat}.{cname}") - vm.source_file = source_file - vm.dirty = True - return vm - # Otherwise evaluate as a multi-pipeline Function Topology or Monolithic Machine Topology + # Evaluate as a multi-pipeline Function Topology or Monolithic Machine Topology self._ast_cache[eval_file] = stmts vm = self.build_graph_for_topology(eval_file, target_variant) vm.source_file = source_file diff --git a/sof-builder/sof_builder/serializer.py b/sof-builder/sof_builder/serializer.py index bb7a715..cd23ffe 100644 --- a/sof-builder/sof_builder/serializer.py +++ b/sof-builder/sof_builder/serializer.py @@ -256,6 +256,7 @@ def generate_compilable_conf( target_platform: str = "mtl", target_harness: str = "hda_analog", extra_platform_conf: str = "", + prefer_full_topology: bool = False, ) -> Tuple[str, str, List[int]]: """Generate a compilable Topology2 .conf string for the current GraphViewModel. @@ -274,6 +275,12 @@ def generate_compilable_conf( target_platform=target_platform, extra_platform_conf=extra_platform_conf, ) + if prefer_full_topology and vm.view_kind == "topology": + return _generate_full_topology_conf( + vm, + topology2_root, + target_platform=target_platform, + ) return _generate_standalone_harness_conf( vm, topology2_root, @@ -867,5 +874,432 @@ def serialize_graph_for_save(vm: GraphViewModel, topology2_root: str) -> str: ] """ - conf_text, _, _ = generate_compilable_conf(vm, topology2_root) + conf_text, _, _ = generate_compilable_conf( + vm, topology2_root, prefer_full_topology=(vm.view_kind == "topology") + ) return conf_text + + +def _fmt_conf_scalar(val: str) -> str: + v = str(val).strip() + if v.startswith('"') or v.startswith("'") or v.startswith("$") or v.lstrip("-").isdigit() or v.startswith("0x"): + return v + if v.lower() in ("true", "false"): + return v.lower() + return f'"{v}"' + + +def _infer_node_type_macro(wclass: str, copier_type: str, direction: str) -> str: + is_cap = direction.lower() == "capture" + if wclass == "host-copier": + return "$HDA_HOST_INPUT_CLASS" if is_cap else "$HDA_HOST_OUTPUT_CLASS" + ct = copier_type.upper() + if ct == "DMIC": + return "$DMIC_LINK_INPUT_CLASS" + if ct in ("SSP", "I2S"): + return "$I2S_LINK_INPUT_CLASS" if is_cap else "$I2S_LINK_OUTPUT_CLASS" + if ct == "ALH": + return "$ALH_UAOL_STREAM_LINK_INPUT_CLASS" if is_cap else "$ALH_UAOL_STREAM_LINK_OUTPUT_CLASS" + return "$HDA_LINK_INPUT_CLASS" if is_cap else "$HDA_LINK_OUTPUT_CLASS" + + +def _serialize_audio_format_block(node: GraphNode, cfg_key: str, indent: int = 1) -> str: + fmt_node = node.config.get_child(cfg_key) + if fmt_node is None or not fmt_node.children: + return "" + pad = "\t" * indent + lines = [f"{pad}{cfg_key} [\n"] + for item in fmt_node.children: + if item.node_type != "object": + continue + lines.append(f"{pad}\t{{\n") + for sc in item.children: + if sc.node_type == "scalar" and str(sc.value) != "": + lines.append(f"{pad}\t\t{sc.key}\t{_fmt_conf_scalar(str(sc.value))}\n") + lines.append(f"{pad}\t}}\n") + lines.append(f"{pad}]\n") + return "".join(lines) + + +def _serialize_widget_controls(node: GraphNode, vm: GraphViewModel, topology2_root: str, indent: int = 1) -> str: + pad = "\t" * indent + blocks: List[str] = [] + # Prefer attached Control GraphNodes (which reflect live edits), falling back to node.config Object.Control + ctl_nodes = [ + c for c in vm.nodes.values() + if c.parent_node_id == node.id and c.class_category == "Control" + ] + if not ctl_nodes: + ctrl_grp = node.config.get_child("Object.Control") + if ctrl_grp is None: + return "" + for ch in ctrl_grp.children: + ctype = ch.key.split(".", 1)[0] + cinst = ch.key.split(".", 1)[1] if "." in ch.key else "1" + blocks.append(_serialize_single_ctrl_cfg(ctype, cinst, ch, node.class_name, topology2_root, indent)) + return "".join(blocks) + + for cnode in ctl_nodes: + blocks.append( + _serialize_single_ctrl_cfg( + cnode.class_name, cnode.instance_id, cnode.config, node.class_name, topology2_root, indent + ) + ) + return "".join(blocks) + + +def _serialize_single_ctrl_cfg( + ctype: str, + cinst: str, + ctrl_cfg: ConfigNode, + parent_wclass: str, + topology2_root: str, + indent: int, +) -> str: + pad = "\t" * indent + lines = [f'{pad}Object.Control.{ctype}."{cinst}" {{\n'] + cname = str(ctrl_cfg.get_scalar("name", "")).strip() + if cname: + lines.append(f"{pad}\tname\t'{cname}'\n") + pfile = _resolve_bytes_param_include(str(ctrl_cfg.get_scalar("included_param_file", "")), parent_wclass, topology2_root) + if ctype == "bytes": + max_v = str(ctrl_cfg.get_scalar("max", "")).strip() + if max_v.isdigit(): + lines.append(f"{pad}\tmax\t{max_v}\n") + if pfile: + lines.append(f"{pad}\t<{pfile}>\n") + else: + bhex = str(ctrl_cfg.get_scalar("bytes_hex", "")).strip() + if bhex: + lines.append(f'{pad}\tObject.Base.data."1" {{\n{pad}\t\tbytes\t"{bhex}"\n{pad}\t}}\n') + elif ctype == "mixer": + min_v = str(ctrl_cfg.get_scalar("min", "")).strip() + max_v = str(ctrl_cfg.get_scalar("max", "")).strip() + inv_v = str(ctrl_cfg.get_scalar("invert", "")).strip().lower() + if min_v.lstrip("-").isdigit(): + lines.append(f"{pad}\tmin\t{min_v}\n") + if max_v.lstrip("-").isdigit(): + lines.append(f"{pad}\tmax\t{max_v}\n") + if inv_v in ("true", "1"): + lines.append(f"{pad}\tinvert\ttrue\n") + tlv = ctrl_cfg.get_child("Object.Base.tlv.scale") + if tlv is not None: + lines.append(f'{pad}\tObject.Base.tlv.scale {{\n') + for tk in ("min", "step", "mute"): + tv = str(tlv.get_scalar(tk, "")).strip() + if tv: + lines.append(f"{pad}\t\t{tk}\t{tv}\n") + lines.append(f"{pad}\t}}\n") + elif ctype == "enum": + opts_raw = str(ctrl_cfg.get_scalar("enum_options", "")).strip() + opts = [o.strip() for o in opts_raw.split(",") if o.strip()] + vals_s = "\n".join(f'{pad}\t\t\t"{o}"' for o in opts) + if opts: + lines.append( + f'{pad}\tObject.Base.text."1" {{\n' + f'{pad}\t\tname\t"enum_{cinst}"\n' + f'{pad}\t\t!values [\n{vals_s}\n{pad}\t\t]\n' + f'{pad}\t}}\n' + ) + lines.append(f"{pad}}}\n") + return "".join(lines) + + +def _generate_full_topology_conf( + vm: GraphViewModel, + topology2_root: str, + target_platform: str = "mtl", +) -> Tuple[str, str, List[int]]: + """Serialize a multi-pipeline GraphViewModel (e.g. from a .tplg binary) to compilable Topology2 .conf.""" + base_includes = [ + "include/common/vendor-token.conf", + "include/common/tokens.conf", + "include/common/virtual.conf", + "include/common/data.conf", + "include/common/pcm.conf", + "include/common/pcm_caps.conf", + "include/common/fe_dai.conf", + "include/common/route.conf", + "include/common/manifest.conf", + "include/common/common_definitions.conf", + "platform/intel/common_definitions.conf", + "include/common/input_audio_format.conf", + "include/common/output_audio_format.conf", + "include/common/input_pin_binding.conf", + "include/common/output_pin_binding.conf", + "include/common/text.conf", + "include/controls/mixer.conf", + "include/controls/bytes.conf", + "include/controls/enum.conf", + "include/components/pipeline.conf", + "include/components/host-copier.conf", + "include/components/dai-copier.conf", + "include/dais/hw_config_simple.conf", + "include/dais/hda.conf", + "include/dais/dmic.conf", + "include/dais/pdm_config.conf", + "include/dais/ssp.conf", + "include/dais/alh.conf", + ] + inc_set: List[str] = [] + seen_inc: Set[str] = set() + for rel in base_includes: + if os.path.isfile(os.path.join(topology2_root, rel)) and rel not in seen_inc: + seen_inc.add(rel) + inc_set.append(rel) + + custom_classes: Dict[str, GraphNode] = {} + for n in vm.nodes.values(): + if n.class_category != "Widget" or n.class_name in ("pipeline", "virtual"): + continue + found = False + for sub_dir in ("include/components", "include/components/cavs"): + cand = f"{sub_dir}/{n.class_name}.conf" + if os.path.isfile(os.path.join(topology2_root, cand)): + if cand not in seen_inc: + seen_inc.add(cand) + inc_set.append(cand) + found = True + break + if not found and n.class_name not in custom_classes: + custom_classes[n.class_name] = n + + inc_lines = "\n".join(f"<{rel}>" for rel in inc_set) + + plat_key = (target_platform or vm.defines.get("PLATFORM", "mtl") or "mtl").strip().lower() + if plat_key not in ("tgl", "adl", "mtl", "lnl", "ptl", "nvl"): + plat_key = "mtl" + + inline_class_blocks: List[str] = [] + for cname, sample_node in sorted(custom_classes.items()): + uuid_v = str(sample_node.config.get_scalar("uuid", "00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00")) + wtype_v = str(sample_node.config.get_scalar("type", "effect")) + inline_class_blocks.append( + f"""Class.Widget."{cname}" {{ +\tDefineAttribute."index" {{}} +\tDefineAttribute."instance" {{}} +\t +\tattributes {{ +\t\t!constructor [ +\t\t\t"index" +\t\t\t"instance" +\t\t] +\t\tunique "instance" +\t}} +\ttype "{wtype_v}" +\tuuid "{uuid_v}" +}}""" + ) + inline_cls_txt = ("\n\n" + "\n\n".join(inline_class_blocks)) if inline_class_blocks else "" + + pipe_container_cls = "" + if os.path.isfile(os.path.join(topology2_root, "include/pipelines/pipeline-common.conf")): + pipe_container_cls = """ +Class.Pipeline."tplg-container" { +\t +\tattributes { +\t\t!constructor [ +\t\t\t"index" +\t\t] +\t\tunique "instance" +\t} +\tdirection "playback" +}""" + + # Group pipeline scheduler + widgets inside Object.Pipeline."tplg-container" per pipeline_id + # so identical widget instance numbers (e.g. gain.1 vs gain.2) stay namespaced per pipeline. + widgets_by_pid: Dict[int, List[GraphNode]] = {} + for nid, n in sorted(vm.nodes.items(), key=lambda kv: (kv[1].pipeline_id or 0, kv[0])): + if n.class_category != "Widget" or n.class_name in ("pipeline", "virtual"): + continue + pid = n.pipeline_id if n.pipeline_id is not None else 0 + widgets_by_pid.setdefault(pid, []).append(n) + + all_pids = sorted(set(vm.containers.keys()) | set(widgets_by_pid.keys())) + pipeline_entries: List[str] = [] + for pid in all_pids: + cont = vm.containers.get(pid) + pdir_c = cont.direction if cont else "playback" + p_entry_lines = [ + "\t{", + f"\t\tindex\t{pid}", + f'\t\tdirection\t"{pdir_c}"', + ] + sched_lines = ['\t\tObject.Widget.pipeline."1" {', f"\t\t\tindex\t{pid}"] + if cont is not None: + for pk in ("priority", "lp_mode", "core_id", "period", "time_domain", "dynamic_pipeline"): + pv = str(cont.config.get_scalar(pk, "")).strip() + if pv != "": + sched_lines.append(f"\t\t\t{pk}\t{_fmt_conf_scalar(pv)}") + sched_lines.append("\t\t}") + p_entry_lines.append("\n".join(sched_lines)) + + for n in widgets_by_pid.get(pid, []): + wclass = n.class_name + inst_hdr = n.instance_id + if wclass in ("host-copier", "dai-copier", "alh-dai-copier", "alh-copier"): + inst_hdr = n.id + wlines = [f'\t\tObject.Widget.{wclass}."{inst_hdr}" {{', f"\t\t\tindex\t{pid}"] + + cdef = n.class_def + skip_keys = { + "index", + "instance", + "direction", + "included_param_file", + "included_conf", + "enum_options", + "value", + "bytes_hex", + "num_input_pins", + "num_output_pins", + "num_input_audio_formats", + "num_output_audio_formats", + } + if cdef is not None: + for aname, adef in cdef.attributes.items(): + if adef.is_immutable: + skip_keys.add(aname) + # Emit uuid when mandatory or not marked immutable and missing a class default + if "uuid" in skip_keys or ( + not (cdef.attributes.get("uuid") and cdef.attributes["uuid"].is_mandatory) + and cdef.defaults.get("uuid") + ): + skip_keys.add("uuid") + if "type" in skip_keys or cdef.defaults.get("type"): + skip_keys.add("type") + else: + skip_keys.update({"uuid", "type"}) + + wdir = str(n.config.get_scalar("direction", pdir_c)) + ctype_dai = str(n.config.get_scalar("copier_type", n.config.get_scalar("dai_type", "HDA"))) + if wclass in ("host-copier", "dai-copier", "alh-dai-copier", "alh-copier"): + if str(n.config.get_scalar("node_type", "")).strip() == "": + n.config.set_scalar("node_type", _infer_node_type_macro(wclass, ctype_dai, wdir), origin="instance") + if wclass == "host-copier": + pcm_id_v = str(n.config.get_scalar("pcm_id", "")).strip() or (n.instance_id if n.instance_id.isdigit() else "0") + wlines.append(f"\t\t\tpcm_id\t{pcm_id_v}") + wlines.append(f"\t\t\tdirection\t{_fmt_conf_scalar(wdir)}") + skip_keys.update({"pcm_id", "direction"}) + elif wclass in ("dai-copier", "alh-dai-copier", "alh-copier"): + sname_v = str(n.config.get_scalar("stream_name", "")).strip() or n.instance_id + wlines.append(f"\t\t\tcopier_type\t{_fmt_conf_scalar(ctype_dai)}") + wlines.append(f"\t\t\tstream_name\t{_fmt_conf_scalar(sname_v)}") + wlines.append(f"\t\t\tdirection\t{_fmt_conf_scalar(wdir)}") + skip_keys.update({"copier_type", "stream_name", "direction"}) + + for pk in ("num_input_pins", "num_output_pins", "num_input_audio_formats", "num_output_audio_formats"): + pv = str(n.config.get_scalar(pk, "")).strip() + if pv != "": + wlines.append(f"\t\t\t{pk}\t{pv}") + + for sc in n.config.children: + if sc.node_type != "scalar" or sc.origin != "instance": + continue + if sc.key in skip_keys or str(sc.value) == "": + continue + if sc.key in ("index", "instance"): + continue + wlines.append(f"\t\t\t{sc.key}\t{_fmt_conf_scalar(str(sc.value))}") + + for ch in n.config.children: + if ch.key.startswith("Object.Base.input_pin_binding.") or ch.key.startswith("Object.Base.output_pin_binding."): + wlines.append(serialize_config_node(ch, indent=3).rstrip("\n")) + + in_fmt_txt = _serialize_audio_format_block(n, "Object.Base.input_audio_format", indent=3) + if in_fmt_txt: + wlines.append(in_fmt_txt.rstrip("\n")) + out_fmt_txt = _serialize_audio_format_block(n, "Object.Base.output_audio_format", indent=3) + if out_fmt_txt: + wlines.append(out_fmt_txt.rstrip("\n")) + + ctl_txt = _serialize_widget_controls(n, vm, topology2_root, indent=3) + if ctl_txt: + wlines.append(ctl_txt.rstrip("\n")) + + wlines.append("\t\t}") + p_entry_lines.append("\n".join(wlines)) + + p_entry_lines.append("\t}") + pipeline_entries.append("\n".join(p_entry_lines)) + + pipelines_section = 'Object.Pipeline."tplg-container" [\n' + "\n".join(pipeline_entries) + "\n]" + + # Routes + route_lines: List[str] = [] + for e in vm.edges: + u = vm.nodes.get(e.source_node) + v = vm.nodes.get(e.sink_node) + if not u or not v or u.class_category in ("Control", "TestbenchIO") or v.class_category in ("Control", "TestbenchIO"): + continue + route_lines.append(f'\t{{\n\t\tsource\t"{u.id}"\n\t\tsink\t"{v.id}"\n\t}}') + + # PCMs + pcm_blocks: List[str] = [] + for ch in vm.root_config.children: + if ch.key.startswith("Object.PCM.pcm."): + pid_s = str(ch.get_scalar("id", "0")) + pname_s = str(ch.get_scalar("name", f"PCM {pid_s}")) + pdir_s = str(ch.get_scalar("direction", "playback")) + plines = [ + f'\t{{', + f'\t\tid\t{pid_s}', + f'\t\tname\t{_fmt_conf_scalar(pname_s)}', + f'\t\tdirection\t{_fmt_conf_scalar(pdir_s)}', + f'\t\tObject.Base.fe_dai."1" {{\n\t\t\tname\t{_fmt_conf_scalar(pname_s)}\n\t\t}}', + ] + d0i3 = str(ch.get_scalar("capture_compatible_d0i3", "")).strip().lower() + if d0i3 in ("true", "1"): + plines.append("\t\tcapture_compatible_d0i3\ttrue") + for sub in ch.children: + if sub.key.startswith("Object.PCM.pcm_caps."): + cap_s = str(sub.get_scalar("name", pname_s)) + fmts_s = str(sub.get_scalar("formats", "S16_LE,S32_LE")) + rates_s = str(sub.get_scalar("rates", "48000")) + cmin_s = str(sub.get_scalar("channels_min", "2")) + cmax_s = str(sub.get_scalar("channels_max", "2")) + cdir = "capture" if "capture" in sub.key else "playback" + plines.append( + f'\t\tObject.PCM.pcm_caps."{cdir}" {{\n' + f'\t\t\tdirection\t"{cdir}"\n' + f'\t\t\tname\t"{cap_s}"\n' + f'\t\t\tformats\t"{fmts_s}"\n' + f'\t\t\trates\t"{rates_s}"\n' + f'\t\t\tchannels_min\t{cmin_s}\n' + f'\t\t\tchannels_max\t{cmax_s}\n' + f'\t\t}}' + ) + plines.append("\t}") + pcm_blocks.append("\n".join(plines)) + + pcm_section = f"\nObject.PCM.pcm [\n" + "\n".join(pcm_blocks) + "\n]\n" if pcm_blocks else "" + route_section = f"\nObject.Base.route [\n" + "\n".join(route_lines) + "\n]\n" if route_lines else "" + + conf_text = f""" + + + + + + + + + +{inc_lines} + +Define {{ +\tPLATFORM\t"{plat_key}" +}} + +IncludeByKey.PLATFORM {{ +\t"tgl"\t"platform/intel/tgl.conf" +\t"adl"\t"platform/intel/tgl.conf" +\t"mtl"\t"platform/intel/mtl.conf" +\t"lnl"\t"platform/intel/lnl.conf" +\t"ptl"\t"platform/intel/ptl.conf" +\t"nvl"\t"platform/intel/ptl.conf" +}}{pipe_container_cls}{inline_cls_txt} + +""" + pipelines_section + route_section + pcm_section + + return (conf_text, f"PLATFORM={plat_key}", _extract_active_pipeline_ids(vm)) diff --git a/sof-builder/sof_builder/text_editor.py b/sof-builder/sof_builder/text_editor.py index 3a6c4aa..6aba6ca 100644 --- a/sof-builder/sof_builder/text_editor.py +++ b/sof-builder/sof_builder/text_editor.py @@ -3,11 +3,12 @@ from __future__ import annotations import re -from typing import Callable, Optional, Tuple +from typing import Callable, List, Optional, Tuple import gi gi.require_version("Gtk", "4.0") -from gi.repository import Gdk, GLib, Gtk, Pango +gi.require_version("PangoCairo", "1.0") +from gi.repository import Gdk, GLib, Gtk, Pango, PangoCairo # Pre-compiled regex patterns for ALSA Topology2 (.conf) syntax colorization @@ -34,6 +35,48 @@ RE_COMMENT = re.compile(r"/\*[\s\S]*?\*/|#[^\n]*") RE_DOXY = re.compile(r"##[^\n]*") +SYNTAX_TAG_NAMES = ( + "syn_brace", + "syn_number", + "syn_keyword", + "syn_category", + "syn_directive", + "syn_variable", + "syn_include", + "syn_string", + "syn_comment", + "syn_doxy", +) + +MIN_FONT_SIZE_PT = 8 +MAX_FONT_SIZE_PT = 36 +DEFAULT_FONT_FAMILY = "Monospace" +DEFAULT_FONT_SIZE_PT = 11 + +_OPEN_TO_CLOSE = {"{": "}", "[": "]", '"': '"', "'": "'"} +_CLOSE_CHARS = {"}", "]", '"', "'"} +_BRACKET_OPEN_TO_CLOSE = {"{": "}", "[": "]"} +_BRACKET_CLOSE_TO_OPEN = {"}": "{", "]": "["} + + +def list_monospace_font_families() -> List[str]: + """Return sorted usable monospace font families available on the system.""" + families = ["Monospace"] + excluded = {"Noto Color Emoji", "Noto Sans SignWriting"} + try: + font_map = PangoCairo.font_map_get_default() + found = sorted( + { + fam.get_name() + for fam in font_map.list_families() + if fam.is_monospace() and fam.get_name() not in excluded and fam.get_name() != "Monospace" + } + ) + families.extend(found) + except Exception: + pass + return families + def check_alsaconf_syntax_balance(text: str) -> Tuple[bool, Optional[int], str]: """Quick structural syntax check for balanced braces/brackets and quotes. @@ -107,26 +150,113 @@ def check_alsaconf_syntax_balance(text: str) -> Tuple[bool, Optional[int], str]: return (True, None, "Valid Topology2 (.conf) syntax") +def _find_matching_bracket_offset(text: str, pos: int) -> Optional[Tuple[int, Optional[int]]]: + """If cursor is adjacent to '{', '}', '[', or ']', return `(brace_pos, match_pos_or_None)`.""" + n = len(text) + if n == 0: + return None + target_idx = -1 + if 0 <= pos < n and (text[pos] in _BRACKET_OPEN_TO_CLOSE or text[pos] in _BRACKET_CLOSE_TO_OPEN): + target_idx = pos + elif pos - 1 >= 0 and ( + text[pos - 1] in _BRACKET_OPEN_TO_CLOSE or text[pos - 1] in _BRACKET_CLOSE_TO_OPEN + ): + target_idx = pos - 1 + if target_idx < 0: + return None + + ch = text[target_idx] + if ch in _BRACKET_OPEN_TO_CLOSE: + expected = _BRACKET_OPEN_TO_CLOSE[ch] + depth = 0 + in_sq = False + in_dq = False + for i in range(target_idx, n): + c = text[i] + if c == "\n": + in_sq = False + in_dq = False + elif c == "'" and not in_dq: + in_sq = not in_sq + elif c == '"' and not in_sq: + in_dq = not in_dq + elif not in_sq and not in_dq: + if c == ch: + depth += 1 + elif c == expected: + depth -= 1 + if depth == 0: + return (target_idx, i) + return (target_idx, None) + + expected = _BRACKET_CLOSE_TO_OPEN[ch] + depth = 0 + for i in range(target_idx, -1, -1): + c = text[i] + if c == ch: + depth += 1 + elif c == expected: + depth -= 1 + if depth == 0: + return (target_idx, i) + return (target_idx, None) + + class TopologyTextEditor(Gtk.Box): """Colorized ALSA Topology2 (.conf) source editor widget with live Diagram synchronization.""" def __init__( self, on_text_committed: Optional[Callable[[str], Tuple[bool, str]]] = None, + on_edit_state_changed: Optional[Callable[[], None]] = None, + on_font_changed: Optional[Callable[[str, int], None]] = None, + font_family: str = DEFAULT_FONT_FAMILY, + font_size_pt: int = DEFAULT_FONT_SIZE_PT, ): super().__init__(orientation=Gtk.Orientation.VERTICAL, spacing=0) self.set_vexpand(True) self.set_hexpand(True) self.on_text_committed = on_text_committed + self.on_edit_state_changed = on_edit_state_changed + self.on_font_changed = on_font_changed + self._suppress_change_signal: bool = False + self._suppress_font_signal: bool = False self._highlight_timer_id: Optional[int] = None self._sync_timer_id: Optional[int] = None self.is_modified_in_text: bool = False self._last_synced_text: str = "" + self._error_line: Optional[int] = None + self._font_families: List[str] = list_monospace_font_families() + self.font_family: str = ( + font_family if font_family in self._font_families else DEFAULT_FONT_FAMILY + ) + self.font_size_pt: int = max(MIN_FONT_SIZE_PT, min(MAX_FONT_SIZE_PT, int(font_size_pt))) + self._search_matches: List[Tuple[int, int]] = [] + self._current_match_idx: int = -1 + self._css_class_name = f"sof-code-editor-{id(self)}" + self._font_css_provider = Gtk.CssProvider() + self._gutter_digits: int = 2 + + self._build_toolbar() + self.append(Gtk.Separator(orientation=Gtk.Orientation.HORIZONTAL)) + self._build_find_bar() + self._build_goto_bar() + self._build_editor_area() - # 1. Top Editor Toolbar - toolbar = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=8) + display = Gdk.Display.get_default() + if display is not None: + Gtk.StyleContext.add_provider_for_display( + display, + self._font_css_provider, + Gtk.STYLE_PROVIDER_PRIORITY_USER, + ) + self.connect("destroy", self._on_destroy) + self._apply_font_css() + + def _build_toolbar(self) -> None: + toolbar = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=6) toolbar.set_margin_start(8) toolbar.set_margin_end(8) toolbar.set_margin_top(4) @@ -138,6 +268,37 @@ def __init__( self.file_lbl.set_hexpand(True) toolbar.append(self.file_lbl) + # Font family + size selectors + self.font_dropdown = Gtk.DropDown.new_from_strings(self._font_families) + self.font_dropdown.set_size_request(135, -1) + self.font_dropdown.set_tooltip_text("Editor font family") + if self.font_family in self._font_families: + self.font_dropdown.set_selected(self._font_families.index(self.font_family)) + self.font_dropdown.connect("notify::selected", self._on_font_dropdown_changed) + toolbar.append(self.font_dropdown) + + self.font_size_spin = Gtk.SpinButton.new_with_range( + MIN_FONT_SIZE_PT, MAX_FONT_SIZE_PT, 1 + ) + self.font_size_spin.set_digits(0) + self.font_size_spin.set_value(self.font_size_pt) + self.font_size_spin.set_width_chars(3) + self.font_size_spin.set_tooltip_text("Font size in pt (Ctrl++ / Ctrl+- / Ctrl+0)") + self.font_size_spin.connect("value-changed", self._on_font_size_spin_changed) + toolbar.append(self.font_size_spin) + + self.wrap_btn = Gtk.ToggleButton(label="Wrap") + self.wrap_btn.add_css_class("flat") + self.wrap_btn.set_tooltip_text("Toggle word wrap") + self.wrap_btn.connect("toggled", self._on_wrap_toggled) + toolbar.append(self.wrap_btn) + + self.find_btn = Gtk.ToggleButton(label="Find") + self.find_btn.add_css_class("flat") + self.find_btn.set_tooltip_text("Find & Replace (Ctrl+F / Ctrl+H)") + self.find_btn.connect("toggled", self._on_find_btn_toggled) + toolbar.append(self.find_btn) + self.status_lbl = Gtk.Label(label="✔ Synced with Diagram", xalign=1.0) self.status_lbl.add_css_class("monospace") toolbar.append(self.status_lbl) @@ -155,13 +316,139 @@ def __init__( toolbar.append(self.apply_btn) self.append(toolbar) - self.append(Gtk.Separator(orientation=Gtk.Orientation.HORIZONTAL)) - # 2. Main Scrolled Editor Area (Line-number gutter + Monospace TextView) - editor_hbox = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=0) - editor_hbox.set_vexpand(True) - editor_hbox.set_hexpand(True) + def _build_find_bar(self) -> None: + self.find_revealer = Gtk.Revealer() + self.find_revealer.set_transition_type(Gtk.RevealerTransitionType.SLIDE_DOWN) + self.find_revealer.set_transition_duration(120) + self.find_revealer.set_reveal_child(False) + + outer = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=4) + outer.set_margin_start(8) + outer.set_margin_end(8) + outer.set_margin_top(4) + outer.set_margin_bottom(4) + + row1 = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=6) + self.find_entry = Gtk.SearchEntry() + self.find_entry.set_placeholder_text("Find… (Enter: Next, Shift+Enter: Prev, Esc: Close)") + self.find_entry.set_hexpand(True) + self.find_entry.connect("search-changed", self._on_find_criteria_changed) + self.find_entry.connect("activate", lambda _e: self.find_next()) + f_key = Gtk.EventControllerKey.new() + f_key.connect("key-pressed", self._on_find_entry_key_pressed) + self.find_entry.add_controller(f_key) + row1.append(self.find_entry) + + self.match_count_lbl = Gtk.Label(label="0 / 0") + self.match_count_lbl.add_css_class("monospace") + self.match_count_lbl.add_css_class("dim-label") + self.match_count_lbl.set_width_chars(9) + row1.append(self.match_count_lbl) + + prev_btn = Gtk.Button(label="↑") + prev_btn.set_tooltip_text("Previous match (Shift+F3)") + prev_btn.connect("clicked", lambda _b: self.find_prev()) + row1.append(prev_btn) + + next_btn = Gtk.Button(label="↓") + next_btn.set_tooltip_text("Next match (F3)") + next_btn.connect("clicked", lambda _b: self.find_next()) + row1.append(next_btn) + + self.case_btn = Gtk.ToggleButton(label="Aa") + self.case_btn.add_css_class("flat") + self.case_btn.set_tooltip_text("Match Case") + self.case_btn.connect("toggled", self._on_find_criteria_changed) + row1.append(self.case_btn) + + self.regex_btn = Gtk.ToggleButton(label=".*") + self.regex_btn.add_css_class("flat") + self.regex_btn.set_tooltip_text("Regular Expression") + self.regex_btn.connect("toggled", self._on_find_criteria_changed) + row1.append(self.regex_btn) + + self.replace_toggle_btn = Gtk.ToggleButton(label="Replace") + self.replace_toggle_btn.add_css_class("flat") + self.replace_toggle_btn.set_tooltip_text("Show/hide Replace controls (Ctrl+H)") + self.replace_toggle_btn.connect( + "toggled", lambda b: self.replace_row.set_visible(b.get_active()) + ) + row1.append(self.replace_toggle_btn) + + close_btn = Gtk.Button(label="✕") + close_btn.add_css_class("flat") + close_btn.set_tooltip_text("Close Find bar (Esc)") + close_btn.connect("clicked", lambda _b: self.close_bars()) + row1.append(close_btn) + outer.append(row1) + self.replace_row = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=6) + self.replace_row.set_visible(False) + self.replace_entry = Gtk.Entry() + self.replace_entry.set_placeholder_text("Replace with…") + self.replace_entry.set_hexpand(True) + self.replace_entry.connect("activate", lambda _e: self.replace_current()) + r_key = Gtk.EventControllerKey.new() + r_key.connect("key-pressed", self._on_find_entry_key_pressed) + self.replace_entry.add_controller(r_key) + self.replace_row.append(self.replace_entry) + + rep_btn = Gtk.Button(label="Replace") + rep_btn.connect("clicked", lambda _b: self.replace_current()) + self.replace_row.append(rep_btn) + + rep_all_btn = Gtk.Button(label="Replace All") + rep_all_btn.connect("clicked", lambda _b: self.replace_all()) + self.replace_row.append(rep_all_btn) + + outer.append(self.replace_row) + outer.append(Gtk.Separator(orientation=Gtk.Orientation.HORIZONTAL)) + self.find_revealer.set_child(outer) + self.append(self.find_revealer) + + def _build_goto_bar(self) -> None: + self.goto_revealer = Gtk.Revealer() + self.goto_revealer.set_transition_type(Gtk.RevealerTransitionType.SLIDE_DOWN) + self.goto_revealer.set_transition_duration(120) + self.goto_revealer.set_reveal_child(False) + + outer = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=2) + row = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=6) + row.set_margin_start(8) + row.set_margin_end(8) + row.set_margin_top(4) + row.set_margin_bottom(4) + + row.append(Gtk.Label(label="Go to Line[:Col]:")) + self.goto_entry = Gtk.Entry() + self.goto_entry.set_placeholder_text("e.g. 42 or 42:10") + self.goto_entry.set_width_chars(18) + self.goto_entry.connect("activate", lambda _e: self._submit_goto_line()) + g_key = Gtk.EventControllerKey.new() + g_key.connect("key-pressed", self._on_goto_entry_key_pressed) + self.goto_entry.add_controller(g_key) + row.append(self.goto_entry) + + go_btn = Gtk.Button(label="Go") + go_btn.connect("clicked", lambda _b: self._submit_goto_line()) + row.append(go_btn) + + spacer = Gtk.Box() + spacer.set_hexpand(True) + row.append(spacer) + + close_btn = Gtk.Button(label="✕") + close_btn.add_css_class("flat") + close_btn.connect("clicked", lambda _b: self.close_bars()) + row.append(close_btn) + + outer.append(row) + outer.append(Gtk.Separator(orientation=Gtk.Orientation.HORIZONTAL)) + self.goto_revealer.set_child(outer) + self.append(self.goto_revealer) + + def _build_editor_area(self) -> None: self.scroll = Gtk.ScrolledWindow() self.scroll.set_vexpand(True) self.scroll.set_hexpand(True) @@ -171,30 +458,60 @@ def __init__( self.text_view.set_monospace(True) self.text_view.set_editable(True) self.text_view.set_wrap_mode(Gtk.WrapMode.NONE) - self.text_view.set_left_margin(12) + self.text_view.set_left_margin(10) self.text_view.set_right_margin(12) - self.text_view.set_top_margin(8) + self.text_view.set_top_margin(6) self.text_view.set_bottom_margin(12) + self.text_view.add_css_class(self._css_class_name) self.buffer = self.text_view.get_buffer() + self.buffer.set_enable_undo(True) self._init_syntax_tags() + # Left line-number gutter attached cleanly inside TextView + self.gutter_area = Gtk.DrawingArea() + self.gutter_area.set_content_width(44) + self.gutter_area.set_draw_func(self._draw_gutter) + self.text_view.set_gutter(Gtk.TextWindowType.LEFT, self.gutter_area) + + vadj = self.scroll.get_vadjustment() + if vadj is not None: + vadj.connect("value-changed", lambda *_: self.gutter_area.queue_draw()) + self.buffer.connect("changed", self._on_buffer_changed) self.buffer.connect("notify::cursor-position", self._on_cursor_moved) + self.buffer.connect("notify::can-undo", lambda *_: self._notify_edit_state()) + self.buffer.connect("notify::can-redo", lambda *_: self._notify_edit_state()) + self.buffer.connect("mark-set", self._on_mark_set) key_ctrl = Gtk.EventControllerKey.new() key_ctrl.connect("key-pressed", self._on_key_pressed) self.text_view.add_controller(key_ctrl) + scroll_ctrl = Gtk.EventControllerScroll.new(Gtk.EventControllerScrollFlags.VERTICAL) + scroll_ctrl.connect("scroll", self._on_ctrl_scroll_zoom) + self.text_view.add_controller(scroll_ctrl) + self.scroll.set_child(self.text_view) - editor_hbox.append(self.scroll) - self.append(editor_hbox) + self.append(self.scroll) + + def _on_destroy(self, *_args: object) -> None: + self._cancel_timers() + display = Gdk.Display.get_default() + if display is not None: + try: + Gtk.StyleContext.remove_provider_for_display(display, self._font_css_provider) + except Exception: + pass def _init_syntax_tags(self) -> None: table = self.buffer.get_tag_table() if table.lookup("syn_keyword") is not None: return + t_cur = self.buffer.create_tag("syn_cur_line", background="#182030") + t_cur.set_priority(0) + self.buffer.create_tag("syn_brace", foreground="#ffd166", weight=Pango.Weight.BOLD) self.buffer.create_tag("syn_number", foreground="#b5cea8") self.buffer.create_tag("syn_keyword", foreground="#569cd6", weight=Pango.Weight.BOLD) @@ -205,26 +522,292 @@ def _init_syntax_tags(self) -> None: self.buffer.create_tag("syn_string", foreground="#e6db74") self.buffer.create_tag("syn_comment", foreground="#6a9955", style=Pango.Style.ITALIC) self.buffer.create_tag("syn_doxy", foreground="#4ec9b0", style=Pango.Style.ITALIC) + + self.buffer.create_tag("syn_search_match", background="#4a3d14") + self.buffer.create_tag("syn_search_current", background="#85580f", foreground="#fef08a") + self.buffer.create_tag( + "syn_brace_match", + background="#1e3a5f", + foreground="#7dd3fc", + weight=Pango.Weight.BOLD, + ) + self.buffer.create_tag( + "syn_brace_mismatch", + background="#5c1d24", + foreground="#fca5a5", + weight=Pango.Weight.BOLD, + ) self.buffer.create_tag( "syn_error_line", background="#421c22", underline=Pango.Underline.ERROR, ) + # ------------------------------------------------------------------ + # Font & View Settings + # ------------------------------------------------------------------ + def _apply_font_css(self) -> None: + escaped_fam = self.font_family.replace("\\", "\\\\").replace('"', '\\"') + css = ( + f"textview.{self._css_class_name}, textview.{self._css_class_name} text {{\n" + f" font-family: \"{escaped_fam}\", monospace;\n" + f" font-size: {self.font_size_pt}pt;\n" + f"}}\n" + ) + self._font_css_provider.load_from_string(css) + self._update_gutter_width() + self.gutter_area.queue_draw() + + def set_font(self, font_family: Optional[str] = None, font_size_pt: Optional[int] = None, notify: bool = True) -> None: + """Update editor font family and/or point size, refreshing CSS and gutter.""" + changed = False + self._suppress_font_signal = True + try: + if font_family is not None: + cand = font_family if font_family in self._font_families else DEFAULT_FONT_FAMILY + if cand != self.font_family: + self.font_family = cand + changed = True + if cand in self._font_families: + idx = self._font_families.index(cand) + if self.font_dropdown.get_selected() != idx: + self.font_dropdown.set_selected(idx) + if font_size_pt is not None: + clamped = max(MIN_FONT_SIZE_PT, min(MAX_FONT_SIZE_PT, int(font_size_pt))) + if clamped != self.font_size_pt: + self.font_size_pt = clamped + changed = True + if int(round(self.font_size_spin.get_value())) != clamped: + self.font_size_spin.set_value(clamped) + finally: + self._suppress_font_signal = False + + if changed: + self._apply_font_css() + if notify and self.on_font_changed is not None: + self.on_font_changed(self.font_family, self.font_size_pt) + + def zoom_in(self, step: int = 1) -> int: + self.set_font(font_size_pt=self.font_size_pt + step, notify=True) + return self.font_size_pt + + def zoom_out(self, step: int = 1) -> int: + self.set_font(font_size_pt=self.font_size_pt - step, notify=True) + return self.font_size_pt + + def reset_zoom(self) -> int: + self.set_font(font_size_pt=DEFAULT_FONT_SIZE_PT, notify=True) + return self.font_size_pt + + def _on_font_dropdown_changed(self, dropdown: Gtk.DropDown, _pspec: object) -> None: + if self._suppress_font_signal: + return + idx = int(dropdown.get_selected()) + if 0 <= idx < len(self._font_families): + self.set_font(font_family=self._font_families[idx], notify=True) + + def _on_font_size_spin_changed(self, spin: Gtk.SpinButton) -> None: + if self._suppress_font_signal: + return + self.set_font(font_size_pt=int(round(spin.get_value())), notify=True) + + def _on_ctrl_scroll_zoom( + self, + ctrl: Gtk.EventControllerScroll, + _dx: float, + dy: float, + ) -> bool: + state = ctrl.get_current_event_state() + if state & Gdk.ModifierType.CONTROL_MASK: + if dy < 0: + self.zoom_in() + elif dy > 0: + self.zoom_out() + return True + return False + + def _on_wrap_toggled(self, btn: Gtk.ToggleButton) -> None: + self.text_view.set_wrap_mode( + Gtk.WrapMode.WORD_CHAR if btn.get_active() else Gtk.WrapMode.NONE + ) + self.gutter_area.queue_draw() + + # ------------------------------------------------------------------ + # Gutter Drawing & Overlay Highlights + # ------------------------------------------------------------------ + def _update_gutter_width(self) -> None: + digits = max(2, len(str(max(1, self.buffer.get_line_count())))) + char_w = max(7.0, self.font_size_pt * 0.72) + target_w = int(digits * char_w + 20) + if digits != self._gutter_digits or self.gutter_area.get_content_width() != target_w: + self._gutter_digits = digits + self.gutter_area.set_content_width(target_w) + + def _draw_gutter( + self, + _area: Gtk.DrawingArea, + cr: object, + width: int, + height: int, + ) -> None: + cr.set_source_rgb(0.078, 0.098, 0.137) + cr.rectangle(0, 0, width, height) + cr.fill() + + cr.set_source_rgb(0.18, 0.22, 0.30) + cr.set_line_width(1.0) + cr.move_to(width - 0.5, 0) + cr.line_to(width - 0.5, height) + cr.stroke() + + vrect = self.text_view.get_visible_rect() + ok_s, top_it = self.text_view.get_iter_at_location(vrect.x, vrect.y) + top_it.set_line_offset(0) + ok_e, bot_it = self.text_view.get_iter_at_location(vrect.x, vrect.y + vrect.height) + cur_line_0 = self.buffer.get_iter_at_mark(self.buffer.get_insert()).get_line() + + layout = PangoCairo.create_layout(cr) + desc = Pango.FontDescription.from_string( + f"{self.font_family}, monospace {max(8, self.font_size_pt - 1)}" + ) + layout.set_font_description(desc) + + it = top_it.copy() + end_line_0 = bot_it.get_line() if ok_e else self.buffer.get_line_count() - 1 + while True: + ln0 = it.get_line() + ln1 = ln0 + 1 + buf_y, line_h = self.text_view.get_line_yrange(it) + win_x, win_y = self.text_view.buffer_to_window_coords( + Gtk.TextWindowType.LEFT, 0, buf_y + ) + if win_y + line_h >= 0 and win_y <= height: + if self._error_line == ln1: + cr.set_source_rgba(0.75, 0.18, 0.22, 0.35) + cr.rectangle(0, win_y, width - 1, line_h) + cr.fill() + elif ln0 == cur_line_0: + cr.set_source_rgba(0.24, 0.35, 0.52, 0.28) + cr.rectangle(0, win_y, width - 1, line_h) + cr.fill() + + layout.set_text(str(ln1), -1) + _ink, logical = layout.get_pixel_extents() + text_x = max(4, width - 8 - logical.width) + text_y = win_y + max(0, (line_h - logical.height) / 2.0) + if self._error_line == ln1: + cr.set_source_rgb(0.98, 0.55, 0.55) + elif ln0 == cur_line_0: + cr.set_source_rgb(0.85, 0.92, 1.0) + else: + cr.set_source_rgb(0.45, 0.53, 0.65) + cr.move_to(text_x, text_y) + PangoCairo.show_layout(cr, layout) + + if ln0 >= end_line_0 or not it.forward_line(): + break + + def _update_cursor_overlays(self) -> None: + """Refresh active-line background and matching/mismatched brace highlight.""" + start_it = self.buffer.get_start_iter() + end_it = self.buffer.get_end_iter() + self.buffer.remove_tag_by_name("syn_cur_line", start_it, end_it) + self.buffer.remove_tag_by_name("syn_brace_match", start_it, end_it) + self.buffer.remove_tag_by_name("syn_brace_mismatch", start_it, end_it) + + cur_it = self.buffer.get_iter_at_mark(self.buffer.get_insert()) + line_start = cur_it.copy() + line_start.set_line_offset(0) + line_end = line_start.copy() + line_end.forward_line() + self.buffer.apply_tag_by_name("syn_cur_line", line_start, line_end) + + text = self.get_text() + match = _find_matching_bracket_offset(text, cur_it.get_offset()) + if match is not None: + b_idx, m_idx = match + tag = "syn_brace_match" if m_idx is not None else "syn_brace_mismatch" + for idx in ([b_idx, m_idx] if m_idx is not None else [b_idx]): + s_i = self.buffer.get_iter_at_offset(idx) + e_i = self.buffer.get_iter_at_offset(idx + 1) + self.buffer.apply_tag_by_name(tag, s_i, e_i) + + # ------------------------------------------------------------------ + # Buffer State, Undo/Redo, Clipboard + # ------------------------------------------------------------------ + @property + def can_undo(self) -> bool: + return bool(self.buffer.get_can_undo()) + + @property + def can_redo(self) -> bool: + return bool(self.buffer.get_can_redo()) + + def undo(self) -> bool: + if not self.buffer.get_can_undo(): + return False + self.buffer.undo() + self._notify_edit_state() + return True + + def redo(self) -> bool: + if not self.buffer.get_can_redo(): + return False + self.buffer.redo() + self._notify_edit_state() + return True + + def select_all(self) -> None: + self.buffer.select_range(self.buffer.get_start_iter(), self.buffer.get_end_iter()) + + def copy_clipboard(self) -> None: + clip = self.text_view.get_clipboard() + self.buffer.copy_clipboard(clip) + + def cut_clipboard(self) -> None: + clip = self.text_view.get_clipboard() + self.buffer.cut_clipboard(clip, True) + + def paste_clipboard(self) -> None: + clip = self.text_view.get_clipboard() + self.buffer.paste_clipboard(clip, None, True) + + def delete_selection(self) -> bool: + if self.buffer.get_has_selection(): + self.buffer.delete_selection(True, True) + return True + return False + + def _notify_edit_state(self) -> None: + if self.on_edit_state_changed is not None: + self.on_edit_state_changed() + def set_text(self, text: str, header_title: str = "") -> None: - """Populate the text editor without triggering a feedback loop to the diagram.""" + """Populate the text editor without recording an initial undo step or sync loop.""" self._cancel_timers() self._suppress_change_signal = True + self._error_line = None try: + self.buffer.set_enable_undo(False) self.buffer.set_text(text) + self.buffer.set_enable_undo(True) + self.buffer.place_cursor(self.buffer.get_start_iter()) self._last_synced_text = text self.is_modified_in_text = False if header_title: self.file_lbl.set_text(header_title) + self._clear_error_highlight() self.apply_syntax_highlighting() + self._update_cursor_overlays() + if self.find_revealer.get_reveal_child(): + self._refresh_search_matches(scroll_to_current=False) + self._update_gutter_width() + self.gutter_area.queue_draw() self.status_lbl.set_text("✔ Synced with Diagram") + self._on_cursor_moved() finally: self._suppress_change_signal = False + self._notify_edit_state() def get_text(self) -> str: start_it = self.buffer.get_start_iter() @@ -240,7 +823,6 @@ def scroll_to_hint(self, hint: Optional[str]) -> bool: return False idx = text.find(hint) if idx < 0: - # Try unquoted fallback if hint had quotes unquoted = hint.replace('"', "").replace("'", "") if unquoted: idx = text.find(unquoted) @@ -259,6 +841,505 @@ def _cancel_timers(self) -> None: GLib.source_remove(self._sync_timer_id) self._sync_timer_id = None + # ------------------------------------------------------------------ + # Find / Replace / Go to Line + # ------------------------------------------------------------------ + def open_find_bar(self, with_replace: bool = False) -> None: + self.goto_revealer.set_reveal_child(False) + self.find_revealer.set_reveal_child(True) + self.find_btn.set_active(True) + self.replace_toggle_btn.set_active(with_replace) + self.replace_row.set_visible(with_replace) + bounds = self.buffer.get_selection_bounds() + if len(bounds) >= 2: + s_it, e_it = bounds[-2], bounds[-1] + sel = self.buffer.get_text(s_it, e_it, False) + if sel and "\n" not in sel and len(sel) <= 120: + self.find_entry.set_text(sel) + self._refresh_search_matches(scroll_to_current=False) + self.find_entry.grab_focus() + self.find_entry.select_region(0, -1) + + def open_goto_line_bar(self) -> None: + self.find_revealer.set_reveal_child(False) + self.find_btn.set_active(False) + self.goto_revealer.set_reveal_child(True) + ln = self.buffer.get_iter_at_mark(self.buffer.get_insert()).get_line() + 1 + self.goto_entry.set_text(str(ln)) + self.goto_entry.grab_focus() + self.goto_entry.select_region(0, -1) + + def close_bars(self) -> None: + self.find_revealer.set_reveal_child(False) + self.goto_revealer.set_reveal_child(False) + self.find_btn.set_active(False) + self._clear_search_highlights() + self.text_view.grab_focus() + + def _on_find_btn_toggled(self, btn: Gtk.ToggleButton) -> None: + if btn.get_active(): + if not self.find_revealer.get_reveal_child(): + self.open_find_bar(with_replace=False) + else: + if self.find_revealer.get_reveal_child(): + self.close_bars() + + def _on_find_criteria_changed(self, *_args: object) -> None: + self._refresh_search_matches(scroll_to_current=True) + + def _clear_search_highlights(self) -> None: + self._search_matches.clear() + self._current_match_idx = -1 + start_it = self.buffer.get_start_iter() + end_it = self.buffer.get_end_iter() + self.buffer.remove_tag_by_name("syn_search_match", start_it, end_it) + self.buffer.remove_tag_by_name("syn_search_current", start_it, end_it) + self.match_count_lbl.set_text("0 / 0") + + def _compile_search_pattern(self) -> Optional[re.Pattern]: + query = self.find_entry.get_text() + if not query: + return None + flags = 0 if self.case_btn.get_active() else re.IGNORECASE + try: + if self.regex_btn.get_active(): + return re.compile(query, flags) + return re.compile(re.escape(query), flags) + except re.error: + return None + + def _refresh_search_matches(self, scroll_to_current: bool = False) -> None: + start_it = self.buffer.get_start_iter() + end_it = self.buffer.get_end_iter() + self.buffer.remove_tag_by_name("syn_search_match", start_it, end_it) + self.buffer.remove_tag_by_name("syn_search_current", start_it, end_it) + self._search_matches.clear() + + pat = self._compile_search_pattern() + if pat is None: + self._current_match_idx = -1 + self.match_count_lbl.set_text( + "Invalid" if (self.find_entry.get_text() and self.regex_btn.get_active()) else "0 / 0" + ) + return + + text = self.get_text() + for m in pat.finditer(text): + if m.end() > m.start(): + self._search_matches.append((m.start(), m.end())) + s_i = self.buffer.get_iter_at_offset(m.start()) + e_i = self.buffer.get_iter_at_offset(m.end()) + self.buffer.apply_tag_by_name("syn_search_match", s_i, e_i) + + if not self._search_matches: + self._current_match_idx = -1 + self.match_count_lbl.set_text("0 / 0") + return + + cur_off = self.buffer.get_iter_at_mark(self.buffer.get_insert()).get_offset() + idx = next((i for i, (s, _e) in enumerate(self._search_matches) if s >= cur_off), 0) + self._set_active_search_match(idx, scroll_to_view=scroll_to_current, select_match=False) + + def _set_active_search_match(self, idx: int, scroll_to_view: bool = True, select_match: bool = True) -> None: + if not self._search_matches: + self._current_match_idx = -1 + self.match_count_lbl.set_text("0 / 0") + return + idx %= len(self._search_matches) + self._current_match_idx = idx + + start_it = self.buffer.get_start_iter() + end_it = self.buffer.get_end_iter() + self.buffer.remove_tag_by_name("syn_search_current", start_it, end_it) + + s_off, e_off = self._search_matches[idx] + s_i = self.buffer.get_iter_at_offset(s_off) + e_i = self.buffer.get_iter_at_offset(e_off) + self.buffer.apply_tag_by_name("syn_search_current", s_i, e_i) + if select_match: + self.buffer.select_range(s_i, e_i) + if scroll_to_view: + self.text_view.scroll_to_iter(s_i, 0.15, True, 0.0, 0.35) + self.match_count_lbl.set_text(f"{idx + 1} / {len(self._search_matches)}") + + def find_next(self) -> bool: + if not self.find_revealer.get_reveal_child(): + self.open_find_bar(with_replace=False) + return False + if not self._search_matches: + self._refresh_search_matches(scroll_to_current=False) + if not self._search_matches: + return False + cur_off = self.buffer.get_iter_at_mark(self.buffer.get_insert()).get_offset() + next_idx = ( + (self._current_match_idx + 1) % len(self._search_matches) + if self._current_match_idx >= 0 + else next((i for i, (s, _e) in enumerate(self._search_matches) if s >= cur_off), 0) + ) + self._set_active_search_match(next_idx, scroll_to_view=True, select_match=True) + return True + + def find_prev(self) -> bool: + if not self.find_revealer.get_reveal_child(): + self.open_find_bar(with_replace=False) + return False + if not self._search_matches: + self._refresh_search_matches(scroll_to_current=False) + if not self._search_matches: + return False + prev_idx = ( + (self._current_match_idx - 1) % len(self._search_matches) + if self._current_match_idx >= 0 + else len(self._search_matches) - 1 + ) + self._set_active_search_match(prev_idx, scroll_to_view=True, select_match=True) + return True + + def replace_current(self) -> bool: + if not self._search_matches: + self._refresh_search_matches(scroll_to_current=False) + if not self._search_matches or self._current_match_idx < 0: + return False + + pat = self._compile_search_pattern() + if pat is None: + return False + s_off, e_off = self._search_matches[self._current_match_idx] + rep_raw = self.replace_entry.get_text() + cur_slice = self.get_text()[s_off:e_off] + if self.regex_btn.get_active(): + try: + replacement = pat.sub(rep_raw, cur_slice, count=1) + except re.error: + return False + else: + replacement = rep_raw + + self.buffer.begin_user_action() + try: + s_i = self.buffer.get_iter_at_offset(s_off) + e_i = self.buffer.get_iter_at_offset(e_off) + self.buffer.delete(s_i, e_i) + ins_i = self.buffer.get_iter_at_offset(s_off) + self.buffer.insert(ins_i, replacement) + finally: + self.buffer.end_user_action() + self._refresh_search_matches(scroll_to_current=True) + return True + + def replace_all(self) -> int: + pat = self._compile_search_pattern() + if pat is None: + return 0 + text = self.get_text() + rep_raw = self.replace_entry.get_text() + try: + if self.regex_btn.get_active(): + new_text, count = pat.subn(rep_raw, text) + else: + new_text, count = pat.subn(lambda _m: rep_raw, text) + except re.error: + return 0 + if count <= 0: + return 0 + + cur_off = min( + len(new_text), + self.buffer.get_iter_at_mark(self.buffer.get_insert()).get_offset(), + ) + self.buffer.begin_user_action() + try: + self.buffer.delete(self.buffer.get_start_iter(), self.buffer.get_end_iter()) + self.buffer.insert(self.buffer.get_start_iter(), new_text) + finally: + self.buffer.end_user_action() + self.buffer.place_cursor(self.buffer.get_iter_at_offset(cur_off)) + self._refresh_search_matches(scroll_to_current=False) + self.status_lbl.set_text(f"Replaced {count} match(es)") + return count + + def goto_line(self, line_1based: int, col_1based: int = 1) -> bool: + total = max(1, self.buffer.get_line_count()) + target_ln = max(1, min(total, int(line_1based))) - 1 + ok, it = self.buffer.get_iter_at_line(target_ln) + if not ok: + return False + line_chars = it.get_chars_in_line() + # Exclude trailing newline if present when clamping column + max_col = max(0, line_chars - (1 if target_ln < total - 1 else 0)) + it.set_line_offset(max(0, min(max_col, int(col_1based) - 1))) + self.buffer.place_cursor(it) + self.text_view.scroll_to_iter(it, 0.15, True, 0.0, 0.35) + return True + + def _submit_goto_line(self) -> None: + raw = self.goto_entry.get_text().strip() + m = re.match(r"^(\d+)(?:[:.,](\d+))?$", raw) + if not m: + return + ln = int(m.group(1)) + col = int(m.group(2)) if m.group(2) else 1 + self.goto_line(ln, col) + self.close_bars() + + def _on_find_entry_key_pressed( + self, + _ctrl: Gtk.EventControllerKey, + keyval: int, + _keycode: int, + state: Gdk.ModifierType, + ) -> bool: + shift_held = bool(state & Gdk.ModifierType.SHIFT_MASK) + if keyval == Gdk.KEY_Escape: + self.close_bars() + return True + if keyval in (Gdk.KEY_F3, Gdk.KEY_Return, Gdk.KEY_KP_Enter) and shift_held: + self.find_prev() + return True + if keyval == Gdk.KEY_F3: + self.find_next() + return True + return False + + def _on_goto_entry_key_pressed( + self, + _ctrl: Gtk.EventControllerKey, + keyval: int, + _keycode: int, + _state: Gdk.ModifierType, + ) -> bool: + if keyval == Gdk.KEY_Escape: + self.close_bars() + return True + return False + + # ------------------------------------------------------------------ + # Line-Oriented Editing Helpers (Indent, Comments, Duplicate, Home) + # ------------------------------------------------------------------ + def _selected_line_range(self) -> Tuple[int, int]: + bounds = self.buffer.get_selection_bounds() + if len(bounds) >= 2: + s_it, e_it = bounds[-2], bounds[-1] + start_ln = s_it.get_line() + end_ln = e_it.get_line() + if end_ln > start_ln and e_it.get_line_offset() == 0: + end_ln -= 1 + return (start_ln, end_ln) + ln = self.buffer.get_iter_at_mark(self.buffer.get_insert()).get_line() + return (ln, ln) + + def _select_line_span(self, start_ln: int, end_ln: int) -> None: + _, s_it = self.buffer.get_iter_at_line(start_ln) + _, e_it = self.buffer.get_iter_at_line(end_ln) + if not e_it.ends_line(): + e_it.forward_to_line_end() + self.buffer.select_range(s_it, e_it) + + def _indent_selected_lines(self, outdent: bool = False) -> None: + start_ln, end_ln = self._selected_line_range() + had_sel = self.buffer.get_has_selection() + self.buffer.begin_user_action() + try: + for ln in range(start_ln, end_ln + 1): + ok, ls = self.buffer.get_iter_at_line(ln) + if not ok: + continue + if outdent: + le = ls.copy() + if not le.ends_line(): + le.forward_to_line_end() + line_txt = self.buffer.get_text(ls, le, False) + rm_len = 0 + if line_txt.startswith("\t"): + rm_len = 1 + else: + rm_len = min(4, len(line_txt) - len(line_txt.lstrip(" "))) + if rm_len > 0: + del_end = self.buffer.get_iter_at_line_offset(ln, rm_len)[1] + self.buffer.delete(ls, del_end) + else: + self.buffer.insert(ls, "\t") + finally: + self.buffer.end_user_action() + if had_sel: + self._select_line_span(start_ln, end_ln) + + def toggle_comment_lines(self) -> None: + """Toggle leading '#' comment marker across current line or selected lines.""" + start_ln, end_ln = self._selected_line_range() + had_sel = self.buffer.get_has_selection() + lines_text: List[str] = [] + for ln in range(start_ln, end_ln + 1): + _, ls = self.buffer.get_iter_at_line(ln) + le = ls.copy() + if not le.ends_line(): + le.forward_to_line_end() + lines_text.append(self.buffer.get_text(ls, le, False)) + + non_empty = [t for t in lines_text if t.strip()] + all_commented = bool(non_empty) and all(t.lstrip(" \t").startswith("#") for t in non_empty) + + self.buffer.begin_user_action() + try: + for offset_idx, txt in enumerate(lines_text): + ln = start_ln + offset_idx + if not txt.strip(): + continue + indent_len = len(txt) - len(txt.lstrip(" \t")) + if all_commented: + rm_len = 2 if txt[indent_len:].startswith("# ") else 1 + _, s_del = self.buffer.get_iter_at_line_offset(ln, indent_len) + _, e_del = self.buffer.get_iter_at_line_offset(ln, indent_len + rm_len) + self.buffer.delete(s_del, e_del) + else: + _, ins_it = self.buffer.get_iter_at_line_offset(ln, indent_len) + self.buffer.insert(ins_it, "# ") + finally: + self.buffer.end_user_action() + + if had_sel: + self._select_line_span(start_ln, end_ln) + + def duplicate_lines(self) -> None: + """Duplicate current line or selected lines immediately below.""" + start_ln, end_ln = self._selected_line_range() + _, s_it = self.buffer.get_iter_at_line(start_ln) + _, e_it = self.buffer.get_iter_at_line(end_ln) + if not e_it.ends_line(): + e_it.forward_to_line_end() + block = self.buffer.get_text(s_it, e_it, False) + self.buffer.begin_user_action() + try: + self.buffer.insert(e_it, "\n" + block) + finally: + self.buffer.end_user_action() + + def delete_lines(self) -> None: + """Delete current line or selected lines atomically.""" + start_ln, end_ln = self._selected_line_range() + _, s_it = self.buffer.get_iter_at_line(start_ln) + if end_ln + 1 < self.buffer.get_line_count(): + _, e_it = self.buffer.get_iter_at_line(end_ln + 1) + else: + _, e_it = self.buffer.get_iter_at_line(end_ln) + if not e_it.ends_line(): + e_it.forward_to_line_end() + if s_it.get_offset() > 0: + s_it.backward_char() + self.buffer.begin_user_action() + try: + self.buffer.delete(s_it, e_it) + finally: + self.buffer.end_user_action() + + def _handle_auto_indent_return(self) -> bool: + if self.buffer.get_has_selection(): + self.buffer.delete_selection(True, True) + cur_it = self.buffer.get_iter_at_mark(self.buffer.get_insert()) + ln = cur_it.get_line() + col = cur_it.get_line_offset() + _, ls = self.buffer.get_iter_at_line(ln) + le = ls.copy() + if not le.ends_line(): + le.forward_to_line_end() + line_txt = self.buffer.get_text(ls, le, False) + indent = line_txt[: len(line_txt) - len(line_txt.lstrip(" \t"))] + before_cursor = line_txt[:col].rstrip() + after_cursor = line_txt[col:].lstrip() + + opens_block = bool(before_cursor) and before_cursor[-1] in ("{", "[") + closes_immediately = opens_block and bool(after_cursor) and ( + (before_cursor[-1] == "{" and after_cursor[0] == "}") + or (before_cursor[-1] == "[" and after_cursor[0] == "]") + ) + + self.buffer.begin_user_action() + try: + if closes_immediately: + self.buffer.insert(cur_it, f"\n{indent}\t\n{indent}") + _, inner_it = self.buffer.get_iter_at_line(ln + 1) + if not inner_it.ends_line(): + inner_it.forward_to_line_end() + self.buffer.place_cursor(inner_it) + elif opens_block: + self.buffer.insert(cur_it, f"\n{indent}\t") + else: + self.buffer.insert(cur_it, f"\n{indent}") + finally: + self.buffer.end_user_action() + self.text_view.scroll_mark_onscreen(self.buffer.get_insert()) + return True + + def _handle_smart_home(self, extend_selection: bool = False) -> bool: + cur_it = self.buffer.get_iter_at_mark(self.buffer.get_insert()) + ln = cur_it.get_line() + col = cur_it.get_line_offset() + _, ls = self.buffer.get_iter_at_line(ln) + le = ls.copy() + if not le.ends_line(): + le.forward_to_line_end() + line_txt = self.buffer.get_text(ls, le, False) + first_non_ws = len(line_txt) - len(line_txt.lstrip(" \t")) + target_col = 0 if (col == first_non_ws or first_non_ws == len(line_txt)) else first_non_ws + _, dest_it = self.buffer.get_iter_at_line_offset(ln, target_col) + if extend_selection: + self.buffer.move_mark(self.buffer.get_insert(), dest_it) + else: + self.buffer.place_cursor(dest_it) + return True + + def _handle_pair_or_close_char(self, ch: str) -> bool: + if self.buffer.get_has_selection(): + return False + cur_it = self.buffer.get_iter_at_mark(self.buffer.get_insert()) + nxt_it = cur_it.copy() + next_ch = nxt_it.get_char() if nxt_it.forward_char() else "" + # Above: check char AT cur_it cleanly + cur_char = cur_it.get_char() if not cur_it.is_end() else "" + + if ch in _CLOSE_CHARS and cur_char == ch: + adv_it = cur_it.copy() + adv_it.forward_char() + self.buffer.place_cursor(adv_it) + return True + + if ch in _OPEN_TO_CLOSE and (cur_char == "" or cur_char in " \t\n\r}])"): + closer = _OPEN_TO_CLOSE[ch] + self.buffer.begin_user_action() + try: + self.buffer.insert(cur_it, ch + closer) + finally: + self.buffer.end_user_action() + mid = self.buffer.get_iter_at_mark(self.buffer.get_insert()) + mid.backward_char() + self.buffer.place_cursor(mid) + return True + return False + + def _handle_pair_backspace(self) -> bool: + if self.buffer.get_has_selection(): + return False + cur_it = self.buffer.get_iter_at_mark(self.buffer.get_insert()) + if cur_it.is_start() or cur_it.is_end(): + return False + prev_it = cur_it.copy() + prev_it.backward_char() + prev_ch = prev_it.get_char() + next_ch = cur_it.get_char() + if prev_ch in _OPEN_TO_CLOSE and _OPEN_TO_CLOSE[prev_ch] == next_ch: + nxt_it = cur_it.copy() + nxt_it.forward_char() + self.buffer.begin_user_action() + try: + self.buffer.delete(prev_it, nxt_it) + finally: + self.buffer.end_user_action() + return True + return False + + # ------------------------------------------------------------------ + # Keyboard & Signal Handlers + # ------------------------------------------------------------------ def _on_key_pressed( self, _ctrl: Gtk.EventControllerKey, @@ -267,39 +1348,151 @@ def _on_key_pressed( state: Gdk.ModifierType, ) -> bool: ctrl_held = bool(state & Gdk.ModifierType.CONTROL_MASK) - if ctrl_held and keyval in (Gdk.KEY_Return, Gdk.KEY_KP_Enter): - self.commit_to_diagram() + shift_held = bool(state & Gdk.ModifierType.SHIFT_MASK) + + if keyval == Gdk.KEY_Escape and ( + self.find_revealer.get_reveal_child() or self.goto_revealer.get_reveal_child() + ): + self.close_bars() + return True + + if ctrl_held: + if keyval in (Gdk.KEY_Return, Gdk.KEY_KP_Enter): + self.commit_to_diagram() + return True + if keyval in (Gdk.KEY_f, Gdk.KEY_F) and not shift_held: + self.open_find_bar(with_replace=False) + return True + if keyval in (Gdk.KEY_h, Gdk.KEY_H) and not shift_held: + self.open_find_bar(with_replace=True) + return True + if keyval in (Gdk.KEY_g, Gdk.KEY_G) and not shift_held: + self.open_goto_line_bar() + return True + if keyval in (Gdk.KEY_slash, Gdk.KEY_KP_Divide) and not shift_held: + self.toggle_comment_lines() + return True + if keyval in (Gdk.KEY_d, Gdk.KEY_D) and not shift_held: + self.duplicate_lines() + return True + if keyval in (Gdk.KEY_k, Gdk.KEY_K) and shift_held: + self.delete_lines() + return True + if keyval in (Gdk.KEY_plus, Gdk.KEY_equal, Gdk.KEY_KP_Add): + self.zoom_in() + return True + if keyval in (Gdk.KEY_minus, Gdk.KEY_KP_Subtract): + self.zoom_out() + return True + if keyval in (Gdk.KEY_0, Gdk.KEY_KP_0): + self.reset_zoom() + return True + if keyval in (Gdk.KEY_z, Gdk.KEY_Z): + return self.redo() if shift_held else self.undo() + if keyval in (Gdk.KEY_y, Gdk.KEY_Y): + return self.redo() + return False + + if keyval == Gdk.KEY_F3: + return self.find_prev() if shift_held else self.find_next() + + if keyval in (Gdk.KEY_ISO_Left_Tab,) or (keyval == Gdk.KEY_Tab and shift_held): + self._indent_selected_lines(outdent=True) return True + + if keyval == Gdk.KEY_Tab: + start_ln, end_ln = self._selected_line_range() + if self.buffer.get_has_selection() and end_ln > start_ln: + self._indent_selected_lines(outdent=False) + return True + return False + + if keyval in (Gdk.KEY_Return, Gdk.KEY_KP_Enter) and not shift_held: + return self._handle_auto_indent_return() + + if keyval == Gdk.KEY_Home: + return self._handle_smart_home(extend_selection=shift_held) + + if keyval == Gdk.KEY_BackSpace and not shift_held: + if self._handle_pair_backspace(): + return True + + pair_map = { + Gdk.KEY_braceleft: "{", + Gdk.KEY_braceright: "}", + Gdk.KEY_bracketleft: "[", + Gdk.KEY_bracketright: "]", + Gdk.KEY_quotedbl: '"', + Gdk.KEY_apostrophe: "'", + } + if keyval in pair_map: + return self._handle_pair_or_close_char(pair_map[keyval]) + return False + def _on_mark_set(self, _buf: Gtk.TextBuffer, _it: Gtk.TextIter, mark: Gtk.TextMark) -> None: + mname = mark.get_name() + if mname in ("insert", "selection_bound"): + self._on_cursor_moved() + def _on_cursor_moved(self, *_args: object) -> None: mark = self.buffer.get_insert() it = self.buffer.get_iter_at_mark(mark) ln = it.get_line() + 1 col = it.get_line_offset() + 1 - self.cursor_lbl.set_text(f"Ln {ln}, Col {col}") + sel_suffix = "" + bounds = self.buffer.get_selection_bounds() + if len(bounds) >= 2: + s_i, e_i = bounds[-2], bounds[-1] + sel_len = abs(e_i.get_offset() - s_i.get_offset()) + if sel_len > 0: + sel_suffix = f" ({sel_len} sel)" + self.cursor_lbl.set_text(f"Ln {ln}, Col {col}{sel_suffix}") + if not self._suppress_change_signal: + self._update_cursor_overlays() + self.gutter_area.queue_draw() def _on_buffer_changed(self, _buf: Gtk.TextBuffer) -> None: if self._suppress_change_signal: return - self.is_modified_in_text = True - self.status_lbl.set_text("✎ Editing text…") + self._error_line = None + self._clear_error_highlight() + self._update_gutter_width() + self.gutter_area.queue_draw() + + cur_text = self.get_text() + if cur_text == self._last_synced_text: + self.is_modified_in_text = False + self.status_lbl.set_text("✔ Synced with Diagram") + if self._sync_timer_id is not None: + GLib.source_remove(self._sync_timer_id) + self._sync_timer_id = None + else: + self.is_modified_in_text = True + self.status_lbl.set_text("✎ Editing text…") + if self._sync_timer_id is not None: + GLib.source_remove(self._sync_timer_id) + self._sync_timer_id = GLib.timeout_add(550, self._on_debounced_sync) if self._highlight_timer_id is not None: GLib.source_remove(self._highlight_timer_id) self._highlight_timer_id = GLib.timeout_add(90, self._on_debounced_highlight) - - if self._sync_timer_id is not None: - GLib.source_remove(self._sync_timer_id) - self._sync_timer_id = GLib.timeout_add(480, self._on_debounced_sync) + self._notify_edit_state() def _on_debounced_highlight(self) -> bool: self._highlight_timer_id = None self.apply_syntax_highlighting() + self._update_cursor_overlays() + if self.find_revealer.get_reveal_child(): + self._refresh_search_matches(scroll_to_current=False) return False def _on_debounced_sync(self) -> bool: self._sync_timer_id = None + ok_syn, _err_line, _syn_msg = check_alsaconf_syntax_balance(self.get_text()) + if not ok_syn: + # Wait for balanced braces during continuous typing; explicit Ctrl+Enter/Save still reports errors + return False self.commit_to_diagram() return False @@ -311,17 +1504,25 @@ def commit_to_diagram(self) -> bool: text = self.get_text() self.apply_syntax_highlighting() + self._update_cursor_overlays() ok_syn, err_line, syn_msg = check_alsaconf_syntax_balance(text) if not ok_syn: + self._error_line = err_line if err_line is not None: self._highlight_error_line(err_line) + self.gutter_area.queue_draw() self.status_lbl.set_text(f"⚠ {syn_msg}") return False + self._error_line = None + self._clear_error_highlight() + self.gutter_area.queue_draw() + if text == self._last_synced_text: self.is_modified_in_text = False self.status_lbl.set_text("✔ Synced with Diagram") + self._notify_edit_state() return True if self.on_text_committed is not None: @@ -330,13 +1531,22 @@ def commit_to_diagram(self) -> bool: self._last_synced_text = text self.is_modified_in_text = False self.status_lbl.set_text(f"✔ {msg}") + self._notify_edit_state() return True - else: - self.status_lbl.set_text(f"⚠ {msg}") - return False + self.status_lbl.set_text(f"⚠ {msg}") + self._notify_edit_state() + return False return True + def _clear_error_highlight(self) -> None: + self.buffer.remove_tag_by_name( + "syn_error_line", + self.buffer.get_start_iter(), + self.buffer.get_end_iter(), + ) + def _highlight_error_line(self, line_1based: int) -> None: + self._clear_error_highlight() ok, s_it = self.buffer.get_iter_at_line(max(0, line_1based - 1)) if not ok: return @@ -349,19 +1559,23 @@ def apply_syntax_highlighting(self) -> None: """Apply ALSA Topology2 (.conf) syntax colorization tags across the buffer.""" start_it = self.buffer.get_start_iter() end_it = self.buffer.get_end_iter() - self.buffer.remove_all_tags(start_it, end_it) + for tname in SYNTAX_TAG_NAMES: + self.buffer.remove_tag_by_name(tname, start_it, end_it) text = self.buffer.get_text(start_it, end_it, True) if not text: return - # Convert byte/char offsets using Gtk.TextBuffer iter_at_offset (char-based in Python) + def _clear_syntax_range(s_it: Gtk.TextIter, e_it: Gtk.TextIter) -> None: + for tname in SYNTAX_TAG_NAMES: + self.buffer.remove_tag_by_name(tname, s_it, e_it) + def _apply_pattern(regex: re.Pattern, tag_name: str, clear_under: bool = False) -> None: for m in regex.finditer(text): s_idx, e_idx = m.start(), m.end() s_it = self.buffer.get_iter_at_offset(s_idx) e_it = self.buffer.get_iter_at_offset(e_idx) if clear_under: - self.buffer.remove_all_tags(s_it, e_it) + _clear_syntax_range(s_it, e_it) self.buffer.apply_tag_by_name(tag_name, s_it, e_it) _apply_pattern(RE_BRACE, "syn_brace") diff --git a/sof-builder/sof_builder/tplg_binary.py b/sof-builder/sof_builder/tplg_binary.py new file mode 100644 index 0000000..894d0ad --- /dev/null +++ b/sof-builder/sof_builder/tplg_binary.py @@ -0,0 +1,1423 @@ +# SPDX-License-Identifier: BSD-3-Clause +"""Binary ALSA .tplg source identification and editable GraphViewModel reconstruction.""" + +from __future__ import annotations +from dataclasses import dataclass, field +import io +import os +import re +import shutil +import subprocess +import tarfile +from typing import Dict, List, Optional, Set, Tuple + +from .model import ( + CMakeTargetVariant, + ConfigNode, + GraphEdge, + GraphNode, + GraphPort, + GraphViewModel, + MachineTopologyEntry, + PipelineContainer, + TplgClassDef, + discover_all_topology2_dirs, + parse_abi_header_text, + read_workspace_sof_abi, + resolve_sof_and_workspace_roots, +) +from . import parser as _parser_mod +from . import tplg_ipc4 as _ipc4 + + +# Fallback UUID -> Widget class mapping when workspace include/components is unavailable or incomplete +_KNOWN_UUID_CLASS_HINTS: Dict[str, str] = { + "a8a9bc61d018184a8e7b2639219804b7": "gain", + "b26e6539713b49408d3ff92cd5c43c09": "mixin", + "5a50563cd7248f41bddcc1f5a3ac2ae0": "mixout", + "e6c05051f927c84e8351c705b642d12f": "eq-iir", + "e70ca943a5f3df41ac06ba98651ae6a3": "eq-fir", + "dae46eb36f00f947a06dfecbe2d8b6ce": "drc", + "491751ddfad95c45b3a713585693f1af": "tdfb", + "1e967a16e48aea1189f1000c29ce1635": "kpb", + "6c8a4f213a491e4b8b1e0d3b6f8a2c15": "ecns", + "7d6c5b4a9f8e1b4a2c3d4e5f60718293": "wov-arbiter", + "329ab5f7a5559f4c9004984c47678791": "mfcc", + "a771e67a1746094abf6d9d2975b68791": "mww", + "f9401882d5f24a4cb46842c24d262e12": "mww", + "4fc35fd90f37c74abc86bfdc83f169a1": "wov", + "6838be396ccb334694472379089c592f": "src", +} + +_DAPM_TYPE_CLASS_HINTS: Dict[int, str] = { + _ipc4.SND_SOC_TPLG_DAPM_AIF_IN: "host-copier", + _ipc4.SND_SOC_TPLG_DAPM_AIF_OUT: "host-copier", + _ipc4.SND_SOC_TPLG_DAPM_DAI_IN: "dai-copier", + _ipc4.SND_SOC_TPLG_DAPM_DAI_OUT: "dai-copier", + _ipc4.SND_SOC_TPLG_DAPM_BUFFER: "module-copier", + _ipc4.SND_SOC_TPLG_DAPM_PGA: "gain", + _ipc4.SND_SOC_TPLG_DAPM_MIXER: "mixin", + _ipc4.SND_SOC_TPLG_DAPM_SRC: "src", + _ipc4.SND_SOC_TPLG_DAPM_ASRC: "asrc", + _ipc4.SND_SOC_TPLG_DAPM_SIGGEN: "siggen", + _ipc4.SND_SOC_TPLG_DAPM_EFFECT: "process", +} + +_PREFIX_CLASS_HINTS: Tuple[Tuple[str, str], ...] = ( + ("host-copier", "host-copier"), + ("dai-copier", "dai-copier"), + ("alh-copier", "alh-dai-copier"), + ("alh-dai-copier", "alh-dai-copier"), + ("module-copier", "module-copier"), + ("copier.host", "host-copier"), + ("copier.dai", "dai-copier"), + ("copier.alh", "alh-dai-copier"), + ("wov-arbiter", "wov-arbiter"), + ("smart_amp", "smart_amp"), + ("eqiir", "eq-iir"), + ("eq-iir", "eq-iir"), + ("eqfir", "eq-fir"), + ("eq-fir", "eq-fir"), + ("dcblock", "dcblock"), + ("multiband_drc", "multiband_drc"), + ("crossover", "crossover"), + ("mixin", "mixin"), + ("mixout", "mixout"), + ("gain", "gain"), + ("siggen", "siggen"), + ("kpb", "kpb"), + ("mfcc", "mfcc"), + ("mww", "mww"), + ("ecns", "ecns"), + ("tdfb", "tdfb"), + ("drc", "drc"), + ("src", "src"), + ("asrc", "asrc"), + ("wov", "wov"), + ("aria", "aria"), +) + + +@dataclass +class TplgDiffReport: + """Structural & parameter comparison between a parsed .tplg binary and a source GraphViewModel.""" + + similarity_pct: float = 0.0 + is_exact: bool = False + missing_pipelines_in_source: List[int] = field(default_factory=list) + extra_pipelines_in_source: List[int] = field(default_factory=list) + missing_widgets_in_source: List[str] = field(default_factory=list) + extra_widgets_in_source: List[str] = field(default_factory=list) + missing_routes_in_source: List[Tuple[str, str]] = field(default_factory=list) + extra_routes_in_source: List[Tuple[str, str]] = field(default_factory=list) + param_diffs: List[str] = field(default_factory=list) + summary: str = "" + + +@dataclass +class TplgBinaryVersionInfo: + """Decoded ABI, protocol, and ALSA manifest version metadata extracted from a .tplg binary.""" + + ipc_protocol: str = "" # "IPC4", "IPC3", or "" + sof_abi_major: Optional[int] = None + sof_abi_minor: Optional[int] = None + sof_abi_patch: Optional[int] = None + sof_abi_str: str = "" + sof_abi_bytes: bytes = b"" + tplg_abi_version: int = 0 + tplg_version: int = 0 + + @property + def sof_abi_tuple(self) -> Optional[Tuple[int, int, int]]: + if ( + self.sof_abi_major is None + or self.sof_abi_minor is None + or self.sof_abi_patch is None + ): + return None + return (self.sof_abi_major, self.sof_abi_minor, self.sof_abi_patch) + + @property + def label(self) -> str: + parts: List[str] = [] + if self.ipc_protocol: + parts.append(self.ipc_protocol) + if self.sof_abi_str: + parts.append(f"SOF ABI {self.sof_abi_str}") + if self.tplg_abi_version: + parts.append(f"tplg ABI v{self.tplg_abi_version}") + return " • ".join(parts) if parts else "Unknown binary version" + + +@dataclass +class WorkspaceVersionMatch: + """Result of resolving a version-matched topology2 workspace for a compiled .tplg binary.""" + + workspace: Optional[object] = None + workspace_abi: Optional[Tuple[int, int, int]] = None + binary_abi: Optional[Tuple[int, int, int]] = None + status: str = "no_workspace" # exact, compatible, git_snapshot, ipc3_unsupported, mismatch, unknown_binary_abi, no_workspace + source_desc: str = "" + snapshot_commit: str = "" + + +def extract_tplg_version_info(tplg: _ipc4.TplgIpc4Topology) -> TplgBinaryVersionInfo: + """Extract protocol, SOF ABI version, and ALSA manifest version from a parsed .tplg.""" + return TplgBinaryVersionInfo( + ipc_protocol=str(getattr(tplg, "ipc_protocol", "") or ""), + sof_abi_major=getattr(tplg, "sof_abi_major", None), + sof_abi_minor=getattr(tplg, "sof_abi_minor", None), + sof_abi_patch=getattr(tplg, "sof_abi_patch", None), + sof_abi_str=str(getattr(tplg, "sof_abi_str", "") or ""), + sof_abi_bytes=bytes(getattr(tplg, "sof_abi_bytes", b"") or b""), + tplg_abi_version=int(getattr(tplg, "abi_version", 0) or 0), + tplg_version=int(getattr(tplg, "tplg_version", 0) or 0), + ) + + +@dataclass +class TplgSourceMatchResult: + """Candidate source .conf + CMake variant matched against a compiled .tplg binary.""" + + conf_path: str + rel_path: str + entry: Optional[MachineTopologyEntry] + variant: Optional[CMakeTargetVariant] + match_reason: str + diff: TplgDiffReport + source_vm: Optional[GraphViewModel] = None + version_info: Optional[TplgBinaryVersionInfo] = None + version_match: Optional[WorkspaceVersionMatch] = None + + +_VERSIONED_WORKSPACE_CACHE: Dict[str, object] = {} + + +def _load_or_reuse_workspace( + topology2_root: str, + current_ws: Optional[object] = None, +) -> Optional[object]: + """Return a scanned Topology2Workspace for topology2_root, reusing caches when available.""" + abs_root = os.path.abspath(topology2_root) + if current_ws is not None and os.path.abspath(getattr(current_ws, "root_dir", "")) == abs_root: + _VERSIONED_WORKSPACE_CACHE[abs_root] = current_ws + return current_ws + cached = _VERSIONED_WORKSPACE_CACHE.get(abs_root) + if cached is not None: + return cached + if not os.path.isdir(abs_root): + return None + ws = _parser_mod.Topology2Workspace(abs_root) + ws.scan_all() + _VERSIONED_WORKSPACE_CACHE[abs_root] = ws + return ws + + +def _git_top_level(path: str) -> str: + """Return the enclosing git repository root for path, or '' if not a git repo.""" + if not path or not os.path.isdir(path): + return "" + try: + res = subprocess.run( + ["git", "-C", path, "rev-parse", "--show-toplevel"], + capture_output=True, + text=True, + check=True, + timeout=3, + ) + top = res.stdout.strip() + return os.path.abspath(top) if top and os.path.isdir(top) else "" + except Exception: + return "" + + +def _git_show_abi(git_root: str, ref_spec: str, abi_rel: str) -> Optional[Tuple[int, int, int]]: + """Read and parse kernel/abi.h from a specific git revision without touching working tree.""" + try: + res = subprocess.run( + ["git", "-C", git_root, "show", f"{ref_spec}:{abi_rel}"], + capture_output=True, + text=True, + check=True, + timeout=3, + ) + return parse_abi_header_text(res.stdout) + except Exception: + return None + + +def _find_git_commit_for_abi( + topology2_dir: str, + target_abi: Tuple[int, int, int], +) -> Optional[Tuple[str, str, str, str]]: + """Search read-only git history for a commit whose abi.h matches target_abi. + + Returns `(git_root, commit_sha, tplg_rel_subpath, abi_rel_path)` or None. + """ + norm_t2 = os.path.abspath(topology2_dir) + sof_root, _ = resolve_sof_and_workspace_roots(norm_t2) + tplg_repo = _git_top_level(norm_t2) + sof_repo = _git_top_level(sof_root) if sof_root else "" + + # Candidate pairs of (git_repo_root, abi_rel_path, tplg_rel_subpath) + repo_specs: List[Tuple[str, str, str]] = [] + if sof_repo: + t2_rel = os.path.relpath(norm_t2, sof_repo) + if not t2_rel.startswith(".."): + repo_specs.append((sof_repo, "src/include/kernel/abi.h", t2_rel)) + if tplg_repo and tplg_repo != sof_repo: + t2_rel = os.path.relpath(norm_t2, tplg_repo) + if not t2_rel.startswith(".."): + for abi_cand in ("include/kernel/abi.h", "src/include/kernel/abi.h", "topology2/abi.h"): + repo_specs.append((tplg_repo, abi_cand, t2_rel)) + + for git_root, abi_rel, tplg_rel in repo_specs: + try: + log_res = subprocess.run( + ["git", "-C", git_root, "log", "-n", "120", "--format=%H", "--", abi_rel], + capture_output=True, + text=True, + check=True, + timeout=5, + ) + except Exception: + continue + commits = [c.strip() for c in log_res.stdout.splitlines() if c.strip()] + seen_revs: Set[str] = set() + revs_to_check: List[str] = [] + # Pass 1: direct commits touching abi.h (newest first, e.g. revert/bump target) + for sha in commits: + if sha not in seen_revs: + seen_revs.add(sha) + revs_to_check.append(sha) + # Pass 2: parents right before an ABI bump commit + for sha in commits: + try: + p_res = subprocess.run( + ["git", "-C", git_root, "rev-parse", "--verify", f"{sha}^"], + capture_output=True, + text=True, + check=True, + timeout=3, + ) + parent_sha = p_res.stdout.strip() + except Exception: + parent_sha = "" + if parent_sha and parent_sha not in seen_revs: + seen_revs.add(parent_sha) + revs_to_check.append(parent_sha) + + for rev in revs_to_check: + parsed = _git_show_abi(git_root, rev, abi_rel) + if parsed == target_abi: + chk = subprocess.run( + ["git", "-C", git_root, "cat-file", "-e", f"{rev}:{tplg_rel}"], + capture_output=True, + timeout=3, + ) + if chk.returncode == 0: + return (git_root, rev, tplg_rel, abi_rel) + return None + + +def _materialize_git_topology_snapshot( + git_root: str, + commit_sha: str, + tplg_rel: str, + abi_rel: str, + target_abi: Tuple[int, int, int], + cache_root: Optional[str] = None, +) -> Optional[str]: + """Extract historical topology2 + abi.h via `git archive` into a read-only cache dir.""" + base_cache = cache_root or os.path.join( + os.path.expanduser("~"), ".cache", "sof-builder", "versioned-sources" + ) + ver_tag = f"{target_abi[0]}.{target_abi[1]}.{target_abi[2]}" + snap_root = os.path.join(base_cache, f"{commit_sha[:12]}-abi-{ver_tag}") + snap_tplg_dir = os.path.join(snap_root, tplg_rel) + marker = os.path.join(snap_root, ".snapshot_ready") + + if os.path.isfile(marker) and os.path.isdir(snap_tplg_dir): + return snap_tplg_dir + + tmp_root = f"{snap_root}.tmp.{os.getpid()}" + try: + shutil.rmtree(tmp_root, ignore_errors=True) + os.makedirs(tmp_root, exist_ok=True) + proc = subprocess.run( + ["git", "-C", git_root, "archive", "--format=tar", commit_sha, tplg_rel, abi_rel], + capture_output=True, + check=True, + timeout=20, + ) + with tarfile.open(fileobj=io.BytesIO(proc.stdout), mode="r:") as tf: + # Safe extraction inside tmp_root (filter out any non-relative entries) + safe_members = [ + m for m in tf.getmembers() + if not m.name.startswith("/") and ".." not in m.name.split("/") + ] + try: + tf.extractall(tmp_root, members=safe_members, filter="data") + except TypeError: + tf.extractall(tmp_root, members=safe_members) + with open(os.path.join(tmp_root, ".snapshot_ready"), "w", encoding="utf-8") as mf: + mf.write(f"{commit_sha}\n{ver_tag}\n") + if os.path.isdir(snap_root): + shutil.rmtree(snap_root, ignore_errors=True) + os.makedirs(os.path.dirname(snap_root), exist_ok=True) + os.replace(tmp_root, snap_root) + return snap_tplg_dir if os.path.isdir(snap_tplg_dir) else None + except Exception: + shutil.rmtree(tmp_root, ignore_errors=True) + return None + + +def resolve_workspace_for_binary( + bin_ver: TplgBinaryVersionInfo, + current_ws: Optional[object] = None, + cache_root: Optional[str] = None, +) -> Tuple[Optional[object], WorkspaceVersionMatch]: + """Locate or materialize the Topology2Workspace whose ABI best matches a .tplg binary.""" + preferred_dir = str(getattr(current_ws, "root_dir", "") or "") + candidate_dirs = discover_all_topology2_dirs(preferred_dir=preferred_dir) + if current_ws is not None and os.path.isdir(preferred_dir): + abs_pref = os.path.abspath(preferred_dir) + if abs_pref not in candidate_dirs: + candidate_dirs.insert(0, abs_pref) + + if not candidate_dirs and current_ws is None: + return ( + None, + WorkspaceVersionMatch( + workspace=None, + binary_abi=bin_ver.sof_abi_tuple, + status="no_workspace", + source_desc="No topology2 source workspace found locally", + ), + ) + + fallback_dir = preferred_dir or (candidate_dirs[0] if candidate_dirs else "") + fallback_abi = read_workspace_sof_abi(fallback_dir) if fallback_dir else None + + if bin_ver.ipc_protocol == "IPC3": + ws_obj = current_ws if current_ws is not None else _load_or_reuse_workspace(fallback_dir, current_ws) + return ( + ws_obj, + WorkspaceVersionMatch( + workspace=ws_obj, + workspace_abi=fallback_abi, + binary_abi=bin_ver.sof_abi_tuple, + status="ipc3_unsupported", + source_desc=( + f"Binary uses {bin_ver.label}; topology2 sources only build IPC4 binaries " + "(opening decoded binary view)" + ), + ), + ) + + target_abi = bin_ver.sof_abi_tuple + if target_abi is None: + ws_obj = current_ws if current_ws is not None else _load_or_reuse_workspace(fallback_dir, current_ws) + return ( + ws_obj, + WorkspaceVersionMatch( + workspace=ws_obj, + workspace_abi=fallback_abi, + binary_abi=None, + status="unknown_binary_abi", + source_desc="Binary manifest has no SOF ABI version; using local workspace", + ), + ) + + # 1. Inspect local checkouts for exact SOF ABI match (major, minor, patch) + local_entries: List[Tuple[str, Optional[Tuple[int, int, int]]]] = [] + for cdir in candidate_dirs: + w_abi = read_workspace_sof_abi(cdir) + local_entries.append((cdir, w_abi)) + if w_abi == target_abi: + ws_obj = _load_or_reuse_workspace(cdir, current_ws) + ver_s = f"{w_abi[0]}.{w_abi[1]}.{w_abi[2]}" + return ( + ws_obj, + WorkspaceVersionMatch( + workspace=ws_obj, + workspace_abi=w_abi, + binary_abi=target_abi, + status="exact", + source_desc=f"Exact ABI {ver_s} match ({cdir})", + ), + ) + + # 2. Search read-only git history across known checkouts and cache a historical snapshot + for cdir, _ in local_entries: + found = _find_git_commit_for_abi(cdir, target_abi) + if found is not None: + git_root, sha, tplg_rel, abi_rel = found + snap_dir = _materialize_git_topology_snapshot( + git_root, sha, tplg_rel, abi_rel, target_abi, cache_root=cache_root + ) + if snap_dir: + ws_obj = _load_or_reuse_workspace(snap_dir, None) + if ws_obj is not None: + ver_s = f"{target_abi[0]}.{target_abi[1]}.{target_abi[2]}" + return ( + ws_obj, + WorkspaceVersionMatch( + workspace=ws_obj, + workspace_abi=target_abi, + binary_abi=target_abi, + status="git_snapshot", + snapshot_commit=sha, + source_desc=f"Git snapshot commit {sha[:10]} matching SOF ABI {ver_s}", + ), + ) + + # 3. Choose closest compatible local checkout (same major.minor preferred) + best_dir = fallback_dir + best_abi = fallback_abi + best_score = (99, 9999, 9999) + for idx, (cdir, w_abi) in enumerate(local_entries): + if w_abi is None: + score = (10, 9999, idx) + elif w_abi[0] == target_abi[0] and w_abi[1] == target_abi[1]: + score = (0, abs(w_abi[2] - target_abi[2]), idx) + elif w_abi[0] == target_abi[0]: + score = (1, abs(w_abi[1] - target_abi[1]) * 100 + abs(w_abi[2] - target_abi[2]), idx) + else: + score = (2, abs(w_abi[0] - target_abi[0]) * 1000, idx) + if score < best_score: + best_score = score + best_dir = cdir + best_abi = w_abi + + ws_obj = _load_or_reuse_workspace(best_dir, current_ws) + bin_s = f"{target_abi[0]}.{target_abi[1]}.{target_abi[2]}" + ws_s = f"{best_abi[0]}.{best_abi[1]}.{best_abi[2]}" if best_abi else "unknown" + if best_abi and best_abi[0] == target_abi[0] and best_abi[1] == target_abi[1]: + return ( + ws_obj, + WorkspaceVersionMatch( + workspace=ws_obj, + workspace_abi=best_abi, + binary_abi=target_abi, + status="compatible", + source_desc=f"Compatible local workspace ABI {ws_s} (binary is {bin_s})", + ), + ) + + return ( + ws_obj, + WorkspaceVersionMatch( + workspace=ws_obj, + workspace_abi=best_abi, + binary_abi=target_abi, + status="mismatch", + source_desc=f"ABI mismatch: binary is {bin_s}, local workspace is {ws_s}", + ), + ) + + +def _uuid_str_to_hex(uuid_str: str) -> str: + """Normalize colon-separated or dashed UUID strings to lowercase 32-hex chars.""" + cleaned = re.sub(r"[^0-9a-fA-F]", "", str(uuid_str or "")) + return cleaned.lower() if len(cleaned) == 32 else "" + + +def _uuid_bytes_to_colon(uuid_bytes: bytes) -> str: + return ":".join(f"{b:02X}" for b in uuid_bytes) + + +def _jaccard(a: set, b: set) -> float: + if not a and not b: + return 1.0 + if not a or not b: + return 0.0 + return len(a & b) / len(a | b) + + +def _extract_binary_fingerprint(tplg: _ipc4.TplgIpc4Topology) -> Tuple[Set[int], Set[str], Set[Tuple[str, str]], Set[int]]: + pipe_ids = set(tplg.pipelines.keys()) + widgets = { + w.name for w in tplg.widgets + if w.pipeline_id in pipe_ids and any(w.orig_uuid_bytes) + } + routes = { + (r.source_name, r.sink_name) for r in tplg.routes + if r.source_name in widgets and r.sink_name in widgets + } + pcms = {p.pcm_id for p in tplg.pcms} + return pipe_ids, widgets, routes, pcms + + +def _extract_vm_fingerprint(vm: GraphViewModel) -> Tuple[Set[int], Set[str], Set[Tuple[str, str]], Set[int]]: + pipe_ids = set(vm.containers.keys()) + widgets = { + nid for nid, n in vm.nodes.items() + if n.class_category == "Widget" and n.class_name not in ("pipeline", "virtual") + } + routes = { + (e.source_node, e.sink_node) for e in vm.edges + if e.source_node in widgets and e.sink_node in widgets + } + pcms: Set[int] = set() + for n in vm.nodes.values(): + if n.class_category == "Widget": + raw_pid = n.config.get_scalar("pcm_id") + if raw_pid is not None and str(raw_pid).lstrip("-").isdigit(): + pcms.add(int(str(raw_pid))) + return pipe_ids, widgets, routes, pcms + + +def diff_binary_vs_source(tplg: _ipc4.TplgIpc4Topology, vm: GraphViewModel) -> TplgDiffReport: + """Compute similarity score and structural differences between a .tplg binary and source VM.""" + b_pipes, b_widgets, b_routes, b_pcms = _extract_binary_fingerprint(tplg) + s_pipes, s_widgets, s_routes, s_pcms = _extract_vm_fingerprint(vm) + + pipe_sim = _jaccard(b_pipes, s_pipes) + wid_sim = _jaccard(b_widgets, s_widgets) + route_sim = _jaccard(b_routes, s_routes) + pcm_sim = _jaccard(b_pcms, s_pcms) + + score = 100.0 * (0.30 * pipe_sim + 0.40 * wid_sim + 0.15 * route_sim + 0.15 * pcm_sim) + + miss_p = sorted(b_pipes - s_pipes) + extra_p = sorted(s_pipes - b_pipes) + miss_w = sorted(b_widgets - s_widgets) + extra_w = sorted(s_widgets - b_widgets) + miss_r = sorted(b_routes - s_routes) + extra_r = sorted(s_routes - b_routes) + + param_diffs: List[str] = [] + for bw in tplg.widgets: + if bw.name not in vm.nodes: + continue + sn = vm.nodes[bw.name] + s_in = len(sn.in_ports) + s_out = len(sn.out_ports) + if bw.num_input_pins != s_in: + param_diffs.append(f"{bw.name}: input_pins bin={bw.num_input_pins} vs src={s_in}") + if bw.num_output_pins != s_out: + param_diffs.append(f"{bw.name}: output_pins bin={bw.num_output_pins} vs src={s_out}") + b_cpc = bw.word_tokens.get(_ipc4.SOF_TKN_COMP_CPC, 0) + s_cpc_raw = str(sn.config.get_scalar("cpc", "")).strip() + if b_cpc and s_cpc_raw.isdigit() and int(s_cpc_raw) != b_cpc: + param_diffs.append(f"{bw.name}: cpc bin={b_cpc} vs src={s_cpc_raw}") + # Compare pin audio format channels/rates (distinguishes 2ch vs 4ch variants) + if bw.input_pin_fmts: + b_chs = {pf.audio_fmt.channels_count for pf in bw.input_pin_fmts if pf.audio_fmt.channels_count > 0} + s_fmt_node = sn.config.get_child("Object.Base.input_audio_format") + if s_fmt_node and s_fmt_node.children: + s_chs = set() + for item in s_fmt_node.children: + cv = str(item.get_scalar("in_channels", "")).strip() + if cv.isdigit(): + s_chs.add(int(cv)) + if b_chs and s_chs and b_chs != s_chs: + param_diffs.append(f"{bw.name}: in_channels bin={sorted(b_chs)} vs src={sorted(s_chs)}") + + # Subtract a small tie-breaker penalty per parameter mismatch so exact 2ch/4ch variants outscore siblings + score = max(0.0, score - min(10.0, 0.5 * len(param_diffs))) + + is_exact = ( + score >= 99.5 + and not miss_p + and not extra_p + and not miss_w + and not extra_w + and not param_diffs + ) + + parts: List[str] = [] + if is_exact: + summary = "Exact structural match (0 differences)" + else: + if miss_p: + parts.append(f"+{len(miss_p)} bin-only pipelines {miss_p[:4]}") + if extra_p: + parts.append(f"-{len(extra_p)} src-only pipelines {extra_p[:4]}") + if miss_w: + parts.append(f"+{len(miss_w)} bin-only widgets") + if extra_w: + parts.append(f"-{len(extra_w)} src-only widgets") + if miss_r or extra_r: + parts.append(f"routes diff (+{len(miss_r)}/-{len(extra_r)})") + if param_diffs: + parts.append(f"{len(param_diffs)} param diffs") + summary = "; ".join(parts) if parts else f"{score:.1f}% match" + + return TplgDiffReport( + similarity_pct=score, + is_exact=is_exact, + missing_pipelines_in_source=miss_p, + extra_pipelines_in_source=extra_p, + missing_widgets_in_source=miss_w, + extra_widgets_in_source=extra_w, + missing_routes_in_source=miss_r, + extra_routes_in_source=extra_r, + param_diffs=param_diffs, + summary=summary, + ) + + +def _stem_aliases(stem: str) -> List[str]: + """Generate likely CMake target output_name aliases for vendor-bundled .tplg filenames.""" + aliases = [stem] + plat_swaps = ( + ("sof-ptl-", "sof-wcl-"), + ("sof-wcl-", "sof-ptl-"), + ("sof-arl-", "sof-mtl-"), + ("sof-mtl-", "sof-arl-"), + ("sof-rpl-", "sof-adl-"), + ("sof-adl-", "sof-tgl-"), + ) + for src_pfx, dst_pfx in plat_swaps: + if stem.startswith(src_pfx): + aliases.append(dst_pfx + stem[len(src_pfx):]) + # Also strip trailing -idN vendor bundle suffixes (e.g. sof-sdca-2amp-id2 -> sof-sdca-2amp) + stripped = re.sub(r"-id\d+$", "", stem) + if stripped != stem: + aliases.append(stripped) + for src_pfx, dst_pfx in plat_swaps: + if stripped.startswith(src_pfx): + aliases.append(dst_pfx + stripped[len(src_pfx):]) + return aliases + + +def _pre_score_entry_text(conf_path: str, stem: str, tplg: _ipc4.TplgIpc4Topology) -> float: + """Fast heuristic score on raw .conf text to prioritize candidates before full AST evaluation.""" + try: + with open(conf_path, "r", encoding="utf-8", errors="replace") as f: + txt = f.read().lower() + except Exception: + return 0.0 + score = 0.0 + base = os.path.splitext(os.path.basename(conf_path))[0].lower() + if base in stem.lower(): + score += 3.0 + # Match stream names, PCM names, and dai_types present in binary + for p in tplg.pcms: + if p.name and p.name.lower() in txt: + score += 2.0 + for l in tplg.links: + if l.name and l.name.lower() in txt: + score += 1.5 + tokens = [tok for tok in re.split(r"[-_]", stem.lower()) if tok and tok not in ("sof", "tplg", "4ch", "2ch")] + for tok in tokens: + if tok in txt: + score += 1.0 + return score + + +def identify_tplg_source( + ws: Optional[_parser_mod.Topology2Workspace], + tplg_path: str, + tplg: _ipc4.TplgIpc4Topology, +) -> Optional[TplgSourceMatchResult]: + """Identify the best matching source .conf and CMakeTargetVariant for a .tplg binary.""" + bin_ver = extract_tplg_version_info(tplg) + if bin_ver.ipc_protocol == "IPC3": + return None + if ws is None or not (ws.machine_topologies or ws.platform_definitions): + return None + + stem = os.path.splitext(os.path.basename(tplg_path))[0] + aliases = _stem_aliases(stem) + + # Tier 1: Exact / aliased CMakeTargetVariant output_name or standalone .conf stem match + tier1_candidates: List[Tuple[Optional[MachineTopologyEntry], str, Optional[CMakeTargetVariant], str]] = [] + seen_pairs: Set[Tuple[str, str]] = set() + + for entry in ws.machine_topologies: + for var in entry.variants: + if var.output_name in aliases: + key = (os.path.abspath(entry.conf_path), var.output_name) + if key not in seen_pairs: + seen_pairs.add(key) + reason = ( + f"CMake target '{var.output_name}'" + if var.output_name == stem + else f"CMake target alias '{var.output_name}' for '{stem}'" + ) + tier1_candidates.append((entry, entry.conf_path, var, reason)) + ebase = os.path.splitext(os.path.basename(entry.conf_path))[0] + if ebase in aliases and not entry.variants: + key = (os.path.abspath(entry.conf_path), ebase) + if key not in seen_pairs: + seen_pairs.add(key) + tier1_candidates.append((entry, entry.conf_path, None, f"Filename stem '{ebase}.conf'")) + + for pdef in ws.platform_definitions: + if pdef.get("has_objects") and pdef.get("stem") in aliases: + ap = str(pdef.get("abs_path", "")) + if ap and os.path.isfile(ap): + key = (os.path.abspath(ap), str(pdef.get("stem"))) + if key not in seen_pairs: + seen_pairs.add(key) + tier1_candidates.append((None, ap, None, f"Platform conf '{pdef.get('name')}'")) + + best_match: Optional[TplgSourceMatchResult] = None + + def evaluate_candidate( + entry: Optional[MachineTopologyEntry], + conf_path: str, + var: Optional[CMakeTargetVariant], + reason: str, + ) -> Optional[TplgSourceMatchResult]: + try: + vm = ws.build_graph_for_topology(conf_path, var) + except Exception: + return None + diff = diff_binary_vs_source(tplg, vm) + rel = os.path.relpath(conf_path, ws.root_dir) + return TplgSourceMatchResult( + conf_path=conf_path, + rel_path=rel, + entry=entry, + variant=var, + match_reason=reason, + diff=diff, + source_vm=vm, + version_info=bin_ver, + ) + + for entry, cpath, var, reason in tier1_candidates: + res = evaluate_candidate(entry, cpath, var, reason) + if res is not None: + if best_match is None or res.diff.similarity_pct > best_match.diff.similarity_pct: + best_match = res + if res.diff.is_exact: + return res + + if best_match is not None and best_match.diff.similarity_pct >= 90.0: + return best_match + + # Tier 2: Structural fingerprint search across top candidate .conf files (handles renamed .tplg) + scored_entries: List[Tuple[float, Optional[MachineTopologyEntry], str, List[Optional[CMakeTargetVariant]]]] = [] + for entry in ws.machine_topologies: + s = _pre_score_entry_text(entry.conf_path, stem, tplg) + vars_list: List[Optional[CMakeTargetVariant]] = list(entry.variants[:4]) if entry.variants else [None] + scored_entries.append((s, entry, entry.conf_path, vars_list)) + for pdef in ws.platform_definitions: + if pdef.get("has_objects"): + ap = str(pdef.get("abs_path", "")) + if ap and os.path.isfile(ap): + s = _pre_score_entry_text(ap, stem, tplg) + scored_entries.append((s, None, ap, [None])) + + scored_entries.sort(key=lambda item: item[0], reverse=True) + eval_budget = 28 + for rank, (_sc, entry, cpath, vars_list) in enumerate(scored_entries[:6]): + cand_vars = list(entry.variants) if (entry and rank < 2 and entry.variants) else vars_list + for var in cand_vars: + if eval_budget <= 0: + break + vkey = (os.path.abspath(cpath), var.output_name if var else os.path.basename(cpath)) + if vkey in seen_pairs: + continue + seen_pairs.add(vkey) + eval_budget -= 1 + res = evaluate_candidate( + entry, + cpath, + var, + f"Structural fingerprint ({var.output_name if var else os.path.basename(cpath)})", + ) + if res is not None: + if best_match is None or res.diff.similarity_pct > best_match.diff.similarity_pct: + best_match = res + if res.diff.is_exact: + return res + if eval_budget <= 0: + break + + if best_match is not None and best_match.diff.similarity_pct >= 35.0: + return best_match + return None + + +def _build_uuid_index(ws: Optional[_parser_mod.Topology2Workspace]) -> Dict[str, List[Tuple[str, TplgClassDef]]]: + idx: Dict[str, List[Tuple[str, TplgClassDef]]] = {} + if ws is None: + return idx + for mname, cdef in ws.processing_modules.items(): + uhex = _uuid_str_to_hex(str(cdef.defaults.get("uuid", ""))) + if uhex: + idx.setdefault(uhex, []).append((mname, cdef)) + return idx + + +def _resolve_widget_class_and_instance( + w: _ipc4.TplgWidgetDesc, + uuid_idx: Dict[str, List[Tuple[str, TplgClassDef]]], + ws: Optional[_parser_mod.Topology2Workspace], +) -> Tuple[str, str, str, Optional[TplgClassDef]]: + """Map binary widget UUID + DAPM type + name -> (wclass, winst, direction, cdef).""" + uhex = w.orig_uuid_bytes.hex() if any(w.orig_uuid_bytes) else "" + candidates = uuid_idx.get(uhex, []) + lname = w.name.lower() + + # Copier UUID is shared across host-copier, dai-copier, alh-dai-copier, module-copier + wclass = "" + if len(candidates) > 1 or any("copier" in c[0] for c in candidates): + if w.orig_dapm_type == _ipc4.SND_SOC_TPLG_DAPM_AIF_IN: + wclass = "host-copier" + elif w.orig_dapm_type == _ipc4.SND_SOC_TPLG_DAPM_AIF_OUT: + wclass = "host-copier" + elif w.orig_dapm_type in (_ipc4.SND_SOC_TPLG_DAPM_DAI_IN, _ipc4.SND_SOC_TPLG_DAPM_DAI_OUT): + wclass = "alh-dai-copier" if "alh" in lname else "dai-copier" + elif w.orig_dapm_type == _ipc4.SND_SOC_TPLG_DAPM_BUFFER: + wclass = "module-copier" + elif len(candidates) == 1: + wclass = candidates[0][0] + + if not wclass and uhex in _KNOWN_UUID_CLASS_HINTS: + wclass = _KNOWN_UUID_CLASS_HINTS[uhex] + + if not wclass: + for pfx, mapped in _PREFIX_CLASS_HINTS: + if lname.startswith(pfx): + wclass = mapped + break + + if not wclass: + wclass = _DAPM_TYPE_CLASS_HINTS.get(w.orig_dapm_type, "process") + + if wclass == "alh-dai-copier" and ws and wclass not in ws.processing_modules and "alh-copier" in ws.processing_modules: + wclass = "alh-copier" + + cdef = ws.processing_modules.get(wclass) if ws else None + + # Determine direction & instance ID + direction = "" + if w.orig_dapm_type in (_ipc4.SND_SOC_TPLG_DAPM_AIF_IN, _ipc4.SND_SOC_TPLG_DAPM_DAI_IN): + direction = "playback" + elif w.orig_dapm_type in (_ipc4.SND_SOC_TPLG_DAPM_AIF_OUT, _ipc4.SND_SOC_TPLG_DAPM_DAI_OUT): + direction = "capture" + elif ".capture" in lname: + direction = "capture" + elif ".playback" in lname: + direction = "playback" + + parts = w.name.split(".") + if parts[-1].isdigit(): + winst = parts[-1] + elif len(parts) >= 2 and parts[1].isdigit(): + winst = parts[1] + elif len(parts) >= 3: + winst = parts[-2] if parts[-1].lower() in ("playback", "capture") else parts[-1] + else: + winst = str(w.comp_id) + + return wclass, winst, direction, cdef + + +def _dapm_type_str(dapm_type: int, wclass: str) -> str: + rev = { + _ipc4.SND_SOC_TPLG_DAPM_INPUT: "input", + _ipc4.SND_SOC_TPLG_DAPM_OUTPUT: "output", + _ipc4.SND_SOC_TPLG_DAPM_PGA: "pga", + _ipc4.SND_SOC_TPLG_DAPM_MIXER: "mixer", + _ipc4.SND_SOC_TPLG_DAPM_AIF_IN: "aif_in", + _ipc4.SND_SOC_TPLG_DAPM_AIF_OUT: "aif_out", + _ipc4.SND_SOC_TPLG_DAPM_DAI_IN: "dai_in", + _ipc4.SND_SOC_TPLG_DAPM_DAI_OUT: "dai_out", + _ipc4.SND_SOC_TPLG_DAPM_BUFFER: "buffer", + _ipc4.SND_SOC_TPLG_DAPM_SCHEDULER: "scheduler", + _ipc4.SND_SOC_TPLG_DAPM_EFFECT: "effect", + _ipc4.SND_SOC_TPLG_DAPM_SIGGEN: "siggen", + _ipc4.SND_SOC_TPLG_DAPM_SRC: "src", + _ipc4.SND_SOC_TPLG_DAPM_ASRC: "asrc", + } + return rev.get(dapm_type, wclass) + + +def _fmt_to_ch_cfg(ch: int, ch_cfg_raw: int) -> str: + if ch_cfg_raw == 0: + return "0" + return str(ch_cfg_raw) + + +def _populate_pin_formats_cfg( + cfg: ConfigNode, + key: str, + pin_fmts: List[_ipc4.Ipc4PinFormat], + is_output: bool, +) -> None: + if not pin_fmts: + return + prefix = "out_" if is_output else "in_" + bs_key = "obs" if is_output else "ibs" + pin_key = "output_pin_index" if is_output else "input_pin_index" + arr = ConfigNode(key=key, node_type="array", category_info=f"{len(pin_fmts)} formats", origin="instance") + for idx, pf in enumerate(pin_fmts): + af = pf.audio_fmt + ch = af.channels_count or 2 + vb = af.valid_bit_depth or af.bit_depth or 32 + item = ConfigNode(key=f"[{idx}]", node_type="object", category_info="format", origin="instance") + if len(pin_fmts) > 1 or pf.pin_index != 0: + item.set_scalar(pin_key, str(pf.pin_index), origin="instance") + item.set_scalar(f"{prefix}rate", str(af.sampling_frequency), origin="instance") + item.set_scalar(f"{prefix}channels", str(ch), origin="instance") + item.set_scalar(f"{prefix}bit_depth", str(af.bit_depth), origin="instance") + item.set_scalar(f"{prefix}valid_bit_depth", str(vb), origin="instance") + item.set_scalar(f"{prefix}ch_cfg", _fmt_to_ch_cfg(ch, af.ch_cfg), origin="instance") + item.set_scalar(f"{prefix}ch_map", f"0x{af.ch_map:08x}", origin="instance") + if pf.buffer_size > 0: + item.set_scalar(bs_key, str(pf.buffer_size), origin="instance") + arr.children.append(item) + cfg.children = [ + c for c in cfg.children + if c.key not in (key, f"CombineArrays.{key}") + ] + cfg.children.append(arr) + + +def _fmt_bitmask_to_names(mask: int) -> str: + bits = [ + (0, "S8"), (2, "S16_LE"), (6, "S24_LE"), (10, "S32_LE"), (14, "FLOAT_LE"), (32, "S24_3LE"), + ] + found = [name for bit, name in bits if mask & (1 << bit)] + return ",".join(found) if found else "S16_LE,S32_LE" + + +def _rate_bitmask_to_names(mask: int, rmin: int, rmax: int) -> str: + bits = [ + (0, "5512"), (1, "8000"), (2, "11025"), (3, "16000"), (4, "22050"), + (5, "32000"), (6, "44100"), (7, "48000"), (8, "64000"), (9, "88200"), + (10, "96000"), (11, "176400"), (12, "192000"), + ] + found = [name for bit, name in bits if mask & (1 << bit)] + if found: + return ",".join(found) + if rmin and rmax and rmin == rmax: + return str(rmin) + return "48000" + + +def _populate_kcontrols_cfg( + cfg: ConfigNode, + kctls: List[_ipc4.TplgKcontrolDesc], +) -> None: + if not kctls: + return + ctrl_group = cfg.get_child("Object.Control") + if ctrl_group is None: + ctrl_group = ConfigNode(key="Object.Control", node_type="object", category_info="controls", origin="instance") + cfg.children.append(ctrl_group) + else: + ctrl_group.children.clear() + + counts = {"mixer": 0, "enum": 0, "bytes": 0} + for kc in kctls: + if kc.ops_info == _ipc4.SND_SOC_TPLG_CTL_BYTES or kc.ctl_type == _ipc4.SND_SOC_TPLG_TYPE_BYTES: + counts["bytes"] += 1 + ckey = f"bytes.{counts['bytes']}" + node = ConfigNode(key=ckey, node_type="object", category_info="Control.bytes", origin="instance") + node.set_scalar("name", kc.name, origin="instance") + if kc.abi_size > 0: + node.set_scalar("max", str(kc.abi_size + 32), origin="instance") + node.set_scalar("abi_type", str(kc.abi_type), origin="instance") + payload = kc.raw_priv_data or kc.abi_data + if payload: + hex_bytes = ",".join(f"0x{b:02x}" for b in payload) + node.set_scalar("bytes_hex", hex_bytes, category_info=f"{len(payload)} bytes", origin="instance") + ctrl_group.children.append(node) + elif kc.enum_texts or kc.ctl_type == _ipc4.SND_SOC_TPLG_TYPE_ENUM: + counts["enum"] += 1 + ckey = f"enum.{counts['enum']}" + node = ConfigNode(key=ckey, node_type="object", category_info="Control.enum", origin="instance") + node.set_scalar("name", kc.name, origin="instance") + if kc.enum_texts: + node.set_scalar("enum_options", ",".join(kc.enum_texts), origin="instance", is_immutable=True) + node.set_scalar("value", kc.enum_texts[0], origin="instance", valid_values=list(kc.enum_texts)) + texts_node = ConfigNode(key="texts", node_type="object", origin="instance") + vals_node = ConfigNode(key="!values", node_type="array", origin="instance") + for t in kc.enum_texts: + vals_node.children.append(ConfigNode(key=t, value=t, node_type="scalar", origin="instance")) + texts_node.children.append(vals_node) + node.children.append(texts_node) + ctrl_group.children.append(node) + else: + counts["mixer"] += 1 + ckey = f"mixer.{counts['mixer']}" + node = ConfigNode(key=ckey, node_type="object", category_info="Control.mixer", origin="instance") + node.set_scalar("name", kc.name, origin="instance") + node.set_scalar("min", str(kc.min_val), origin="instance") + node.set_scalar("max", str(kc.max_val), origin="instance") + if kc.invert: + node.set_scalar("invert", "true", origin="instance") + if kc.scale_step > 0 or kc.scale_min != 0: + tlv = ConfigNode(key="Object.Base.tlv.scale", node_type="object", origin="instance") + tlv.set_scalar("min", str(kc.scale_min), origin="instance") + tlv.set_scalar("step", str(kc.scale_step), origin="instance") + tlv.set_scalar("mute", str(kc.scale_mute), origin="instance") + node.children.append(tlv) + if kc.max_val == 1: + node.set_scalar("value", "1", origin="instance") + else: + def_v = kc.default_step_value() + chs = ",".join([str(def_v)] * max(1, kc.num_channels)) + node.set_scalar("value", chs, origin="instance") + ctrl_group.children.append(node) + + +def attach_binary_manifest_metadata( + vm: GraphViewModel, + tplg: _ipc4.TplgIpc4Topology, + bin_ver: Optional[TplgBinaryVersionInfo] = None, + ver_match: Optional[WorkspaceVersionMatch] = None, +) -> None: + """Attach decoded binary manifest ABI/protocol/version metadata onto vm.root_config.""" + if vm is None or vm.root_config is None: + return + if bin_ver is None: + bin_ver = extract_tplg_version_info(tplg) + if not (tplg.sof_abi_bytes or bin_ver.ipc_protocol or bin_ver.sof_abi_str or bin_ver.tplg_abi_version): + return + abi_node = vm.root_config.get_child("Object.Base.manifest") + if abi_node is None: + abi_node = ConfigNode( + key="Object.Base.manifest", + node_type="object", + category_info="SOF Binary ABI", + origin="instance", + ) + vm.root_config.children.append(abi_node) + if bin_ver.ipc_protocol: + abi_node.set_scalar("ipc_protocol", bin_ver.ipc_protocol, origin="instance") + if bin_ver.sof_abi_str: + abi_node.set_scalar("sof_abi", bin_ver.sof_abi_str, origin="instance") + abi_node.set_scalar("abi_version", str(bin_ver.tplg_abi_version), origin="instance") + abi_node.set_scalar("tplg_version", str(bin_ver.tplg_version), origin="instance") + if tplg.sof_abi_bytes: + abi_node.set_scalar("sof_abi_bytes", ",".join(f"0x{b:02x}" for b in tplg.sof_abi_bytes), origin="instance") + if ver_match is not None: + abi_node.set_scalar("version_match", ver_match.status, origin="instance") + if ver_match.workspace_abi: + w_s = f"{ver_match.workspace_abi[0]}.{ver_match.workspace_abi[1]}.{ver_match.workspace_abi[2]}" + abi_node.set_scalar("source_workspace_abi", w_s, origin="instance") + + +def build_graph_from_tplg( + ws: Optional[_parser_mod.Topology2Workspace], + tplg_path: str, + tplg: Optional[_ipc4.TplgIpc4Topology] = None, + match_result: Optional[TplgSourceMatchResult] = None, + version_match: Optional[WorkspaceVersionMatch] = None, +) -> GraphViewModel: + """Reconstruct an editable GraphViewModel directly from a parsed ALSA .tplg binary.""" + abs_path = os.path.abspath(tplg_path) + if tplg is None: + tplg = _ipc4.TplgIpc4Parser.parse_file(abs_path) + + bin_ver = (match_result.version_info if match_result and match_result.version_info else None) or extract_tplg_version_info(tplg) + eff_ver_match = version_match or (match_result.version_match if match_result else None) + + uuid_idx = _build_uuid_index(ws) + bname = os.path.basename(abs_path) + defines: Dict[str, str] = {} + if match_result and match_result.source_vm: + for dk in ("PLATFORM", "NUM_DMICS", "DMIC_DRIVER_VERSION"): + if dk in match_result.source_vm.defines: + defines[dk] = str(match_result.source_vm.defines[dk]) + if "PLATFORM" not in defines: + # Infer likely platform from binary stem or widget types + low_b = bname.lower() + for plat in ("ptl", "wcl", "lnl", "mtl", "arl", "nvl", "tgl", "adl"): + if f"-{plat}" in low_b: + defines["PLATFORM"] = "ptl" if plat in ("ptl", "wcl") else ("mtl" if plat == "arl" else plat) + break + if "PLATFORM" not in defines: + defines["PLATFORM"] = ws.global_defines.get("PLATFORM", "mtl") if ws else "mtl" + + summary = match_result.diff.summary if match_result else "Decoded directly from .tplg binary" + if eff_ver_match and eff_ver_match.source_desc: + summary = f"{bin_ver.label} • {eff_ver_match.source_desc} • {summary}" + elif bin_ver.label: + summary = f"{bin_ver.label} • {summary}" + + subtitle = f"Binary .tplg [{bname}] • {bin_ver.label}" + if match_result: + subtitle += f" • Source candidate: {match_result.rel_path} ({match_result.diff.similarity_pct:.0f}%)" + + root_cfg = ConfigNode(key=bname, node_type="object", category_info=subtitle) + + def_node = ConfigNode(key="Define (Active Variables)", node_type="define", category_info=f"{len(defines)} vars") + for dk, dv in sorted(defines.items()): + def_node.set_scalar(dk, dv, category_info="Define", origin="define") + root_cfg.children.append(def_node) + + vm = GraphViewModel( + title=bname, + subtitle=subtitle, + view_kind="topology", + source_file="", + defines=defines, + root_config=root_cfg, + source_tplg=abs_path, + binary_match_summary=summary, + ) + attach_binary_manifest_metadata(vm, tplg, bin_ver, eff_ver_match) + + # Determine pipeline directions from child AIF/DAI widgets before creating containers + pipe_dir_hints: Dict[int, str] = {} + for w in tplg.widgets: + if w.pipeline_id not in tplg.pipelines: + continue + if w.orig_dapm_type in (_ipc4.SND_SOC_TPLG_DAPM_AIF_OUT, _ipc4.SND_SOC_TPLG_DAPM_DAI_OUT) or ".capture" in w.name.lower(): + pipe_dir_hints[w.pipeline_id] = "capture" + elif w.pipeline_id not in pipe_dir_hints and ( + w.orig_dapm_type in (_ipc4.SND_SOC_TPLG_DAPM_AIF_IN, _ipc4.SND_SOC_TPLG_DAPM_DAI_IN) or ".playback" in w.name.lower() + ): + pipe_dir_hints[w.pipeline_id] = "playback" + + # Build PipelineContainers + p_base = ws.processing_modules.get("pipeline") if ws else None + for pid, pdesc in sorted(tplg.pipelines.items()): + pdir = pipe_dir_hints.get(pid) + if not pdir and pdesc.direction_valid: + pdir = "capture" if pdesc.direction == 1 else "playback" + pdir = pdir or "playback" + pcfg = p_base.config_tree.clone() if p_base else ConfigNode("Object.Widget.pipeline", node_type="object") + pcfg.set_scalar("index", str(pid), origin="instance", is_constructor=True) + pcfg.set_scalar("priority", str(pdesc.priority), origin="instance") + pcfg.set_scalar("lp_mode", str(pdesc.lp_mode), origin="instance") + pcfg.set_scalar("core_id", str(pdesc.core_id), origin="instance") + pcfg.set_scalar("dynamic_pipeline", str(pdesc.dynamic_pipeline), origin="instance") + if pdesc.period: + pcfg.set_scalar("period", str(pdesc.period), origin="instance") + pcfg.set_scalar("time_domain", "timer" if pdesc.time_domain == 1 else "dma", origin="instance") + en_by = f"Decoded from {bname} ({pdesc.name})" + pcfg.set_scalar("enabled_by", en_by, category_info="Binary Source", origin="default", is_immutable=True) + + p_class = f"tplg-{pdir}" if pdesc.dynamic_pipeline else f"tplg-static-{pdir}" + vm.containers[pid] = PipelineContainer( + pipeline_id=pid, + class_name=p_class, + direction=pdir, + enabled_by=en_by, + config=pcfg, + ) + + # PCM stream -> pcm_id map for host-copier enrichment + stream_to_pcm: Dict[str, _ipc4.TplgPcmDesc] = {} + for pcm in tplg.pcms: + if pcm.playback_stream_name: + stream_to_pcm[pcm.playback_stream_name] = pcm + if pcm.capture_stream_name: + stream_to_pcm[pcm.capture_stream_name] = pcm + + # Build GraphNodes for active SOF widgets (skip dummy ALSA codec endpoint pins outside pipelines) + reconstructed_widgets: Dict[str, _ipc4.TplgWidgetDesc] = {} + for w in tplg.widgets: + has_uuid = any(w.orig_uuid_bytes) + if w.pipeline_id not in vm.containers: + if not has_uuid: + continue + vm.containers[w.pipeline_id] = PipelineContainer( + pipeline_id=w.pipeline_id, + class_name="tplg-pipeline", + direction=pipe_dir_hints.get(w.pipeline_id, "playback"), + enabled_by=f"Decoded from {bname}", + ) + if not has_uuid and w.orig_dapm_type in ( + _ipc4.SND_SOC_TPLG_DAPM_INPUT, + _ipc4.SND_SOC_TPLG_DAPM_OUTPUT, + _ipc4.SND_SOC_TPLG_DAPM_OUT_DRV, + ): + continue + + wclass, winst, wdir, cdef = _resolve_widget_class_and_instance(w, uuid_idx, ws) + cfg = cdef.config_tree.clone() if cdef else ConfigNode(f"Class.Widget.{wclass}", node_type="object") + pdir = vm.containers[w.pipeline_id].direction + eff_dir = wdir or pdir + + cfg.set_scalar("index", str(w.pipeline_id), origin="pipeline", is_constructor=True) + cfg.set_scalar("instance", winst, origin="pipeline", is_constructor=True) + cfg.set_scalar("type", _dapm_type_str(w.orig_dapm_type, wclass), origin="instance") + if has_uuid: + cfg.set_scalar("uuid", _uuid_bytes_to_colon(w.orig_uuid_bytes), origin="instance") + cfg.set_scalar("core_id", str(w.core_id), origin="instance") + cfg.set_scalar("num_input_pins", str(w.num_input_pins), origin="instance") + cfg.set_scalar("num_output_pins", str(w.num_output_pins), origin="instance") + cfg.set_scalar("num_input_audio_formats", str(len(w.input_pin_fmts)), origin="instance") + cfg.set_scalar("num_output_audio_formats", str(len(w.output_pin_fmts)), origin="instance") + if _ipc4.SOF_TKN_COMP_CPC in w.word_tokens: + cfg.set_scalar("cpc", str(w.word_tokens[_ipc4.SOF_TKN_COMP_CPC]), origin="instance") + if _ipc4.SOF_TKN_COMP_IS_PAGES in w.word_tokens: + cfg.set_scalar("is_pages", str(w.word_tokens[_ipc4.SOF_TKN_COMP_IS_PAGES]), origin="instance") + if w.proc_domain == 1: + cfg.set_scalar("scheduler_domain", "DP", origin="instance") + if w.stream_name: + cfg.set_scalar("stream_name", w.stream_name, origin="instance") + if wclass in ("host-copier", "dai-copier", "alh-dai-copier", "alh-copier"): + cfg.set_scalar("direction", eff_dir, origin="instance") + if _ipc4.SOF_TKN_DAI_TYPE in w.str_tokens: + dt = w.str_tokens[_ipc4.SOF_TKN_DAI_TYPE] + cfg.set_scalar("dai_type", dt, origin="instance") + cfg.set_scalar("copier_type", dt, origin="instance") + if _ipc4.SOF_TKN_DAI_INDEX in w.word_tokens: + cfg.set_scalar("dai_index", str(w.word_tokens[_ipc4.SOF_TKN_DAI_INDEX]), origin="instance") + if _ipc4.SOF_TKN_COMP_NODE_TYPE in w.word_tokens: + cfg.set_scalar("node_type", f"0x{w.word_tokens[_ipc4.SOF_TKN_COMP_NODE_TYPE]:x}", origin="instance") + if _ipc4.SOF_TKN_DEEP_BUFFER_DMA_MS in w.word_tokens: + cfg.set_scalar("deep_buffer_dma_ms", str(w.word_tokens[_ipc4.SOF_TKN_DEEP_BUFFER_DMA_MS]), origin="instance") + + pcm_match = stream_to_pcm.get(w.stream_name) + if pcm_match is not None and wclass == "host-copier": + cfg.set_scalar("pcm_id", str(pcm_match.pcm_id), origin="instance") + + _populate_pin_formats_cfg(cfg, "Object.Base.input_audio_format", w.input_pin_fmts, is_output=False) + _populate_pin_formats_cfg(cfg, "Object.Base.output_audio_format", w.output_pin_fmts, is_output=True) + + for pin_idx, target_wname in enumerate(w.input_pin_binding, start=1): + if target_wname: + bnode = ConfigNode(key=f"Object.Base.input_pin_binding.{pin_idx}", node_type="object", origin="instance") + bnode.set_scalar("input_pin_binding_name", target_wname, origin="instance") + cfg.children.append(bnode) + for pin_idx, target_wname in enumerate(w.output_pin_binding, start=1): + if target_wname: + bnode = ConfigNode(key=f"Object.Base.output_pin_binding.{pin_idx}", node_type="object", origin="instance") + bnode.set_scalar("output_pin_binding_name", target_wname, origin="instance") + cfg.children.append(bnode) + + _populate_kcontrols_cfg(cfg, w.orig_kcontrols) + + in_badge = _parser_mod.Topology2Workspace.summarize_pin_audio_format(cfg, "in") + out_badge = _parser_mod.Topology2Workspace.summarize_pin_audio_format(cfg, "out") + wtype_s = str(cfg.get_scalar("type", wclass)) + w_sub = f"Pipe {w.pipeline_id} • {wclass} ({wtype_s})" + if pcm_match is not None and wclass == "host-copier": + w_sub += f" • PCM {pcm_match.pcm_id}" + if w.stream_name: + w_sub += f" ({w.stream_name})" + + badges: List[str] = [] + if w.orig_kcontrols: + badges.append(f"{len(w.orig_kcontrols)} ctl") + if w.proc_domain == 1: + badges.append("DP") + + n_in = 0 if wclass == "siggen" else max(1, w.num_input_pins) + n_out = max(1, w.num_output_pins) + in_ports = [GraphPort(f"in{i}", f"in.{i}", "in", "audio") for i in range(n_in)] + out_ports = [GraphPort(f"out{i}", f"out.{i}", "out", "audio") for i in range(n_out)] + + map_cat = _parser_mod.Topology2Workspace._map_category("Widget", wclass) + wnode = GraphNode( + id=w.name, + title=w.name, + subtitle=w_sub, + category=map_cat, + class_category="Widget", + class_name=wclass, + instance_id=winst, + pipeline_id=w.pipeline_id, + pipeline_class=vm.containers[w.pipeline_id].class_name, + in_ports=in_ports, + out_ports=out_ports, + in_fmt_badge=in_badge, + out_fmt_badge=out_badge, + badges=badges, + config=cfg, + class_def=cdef, + source_file="", + ) + vm.nodes[wnode.id] = wnode + reconstructed_widgets[w.name] = w + if ws is not None: + ws.attach_widget_kcontrol_nodes(vm, wnode) + + # Build GraphEdges from DAPM routes with pin binding resolution + seen_edges: Set[Tuple[str, str]] = set() + for ridx, r in enumerate(tplg.routes): + if r.source_name not in vm.nodes or r.sink_name not in vm.nodes: + continue + if (r.source_name, r.sink_name) in seen_edges: + continue + seen_edges.add((r.source_name, r.sink_name)) + + src_node = vm.nodes[r.source_name] + snk_node = vm.nodes[r.sink_name] + src_w = reconstructed_widgets.get(r.source_name) + snk_w = reconstructed_widgets.get(r.sink_name) + + src_port = "out0" + if src_w and src_w.output_pin_binding and r.sink_name in src_w.output_pin_binding: + src_port = f"out{src_w.output_pin_binding.index(r.sink_name)}" + snk_port = "in0" + if snk_w and snk_w.input_pin_binding and r.source_name in snk_w.input_pin_binding: + snk_port = f"in{snk_w.input_pin_binding.index(r.source_name)}" + + is_inter = ( + src_node.pipeline_id is not None + and snk_node.pipeline_id is not None + and src_node.pipeline_id != snk_node.pipeline_id + ) + ecfg = ConfigNode("Object.Base.route", node_type="object") + ecfg.set_scalar("source", r.source_name, origin="instance") + ecfg.set_scalar("sink", r.sink_name, origin="instance") + vm.edges.append( + GraphEdge( + id=f"edge_{ridx}", + source_node=r.source_name, + sink_node=r.sink_name, + source_port=src_port, + sink_port=snk_port, + pipeline_id=src_node.pipeline_id, + is_inter_pipeline=is_inter, + config=ecfg, + ) + ) + + # Record decoded PCMs and DAI Backend Links in root_config + for pcm in tplg.pcms: + pnode = ConfigNode(key=f"Object.PCM.pcm.{pcm.pcm_id}", node_type="object", category_info="Binary PCM", origin="instance") + pnode.set_scalar("id", str(pcm.pcm_id), origin="instance") + pnode.set_scalar("name", pcm.name, origin="instance") + direction = "duplex" if (pcm.playback and pcm.capture) else ("capture" if pcm.capture else "playback") + pnode.set_scalar("direction", direction, origin="instance") + if pcm.capture_compatible_d0i3: + pnode.set_scalar("capture_compatible_d0i3", "true", origin="instance") + if pcm.playback and pcm.playback_stream_name: + pb_caps = ConfigNode(key="Object.PCM.pcm_caps.playback", node_type="object", origin="instance") + pb_caps.set_scalar("name", pcm.playback_stream_name, origin="instance") + pb_caps.set_scalar("formats", _fmt_bitmask_to_names(pcm.pb_formats), origin="instance") + pb_caps.set_scalar("rates", _rate_bitmask_to_names(pcm.pb_rates, pcm.pb_rate_min, pcm.pb_rate_max), origin="instance") + pb_caps.set_scalar("channels_min", str(pcm.pb_channels_min or 2), origin="instance") + pb_caps.set_scalar("channels_max", str(pcm.pb_channels_max or 2), origin="instance") + pnode.children.append(pb_caps) + if pcm.capture and pcm.capture_stream_name: + cap_caps = ConfigNode(key="Object.PCM.pcm_caps.capture", node_type="object", origin="instance") + cap_caps.set_scalar("name", pcm.capture_stream_name, origin="instance") + cap_caps.set_scalar("formats", _fmt_bitmask_to_names(pcm.cap_formats), origin="instance") + cap_caps.set_scalar("rates", _rate_bitmask_to_names(pcm.cap_rates, pcm.cap_rate_min, pcm.cap_rate_max), origin="instance") + cap_caps.set_scalar("channels_min", str(pcm.cap_channels_min or 2), origin="instance") + cap_caps.set_scalar("channels_max", str(pcm.cap_channels_max or 2), origin="instance") + pnode.children.append(cap_caps) + root_cfg.children.append(pnode) + + for link in tplg.links: + lnode = ConfigNode(key=f"Object.Dai.link.{link.link_id}", node_type="object", category_info="Binary Backend Link", origin="instance") + lnode.set_scalar("id", str(link.link_id), origin="instance") + lnode.set_scalar("name", link.name or f"link_{link.link_id}", origin="instance") + if _ipc4.SOF_TKN_DAI_TYPE in link.str_tokens: + lnode.set_scalar("dai_type", link.str_tokens[_ipc4.SOF_TKN_DAI_TYPE], origin="instance") + if _ipc4.SOF_TKN_DAI_INDEX in link.word_tokens: + lnode.set_scalar("dai_index", str(link.word_tokens[_ipc4.SOF_TKN_DAI_INDEX]), origin="instance") + if link.hw_configs: + hw0 = link.hw_configs[0] + if hw0.fsync_rate: + lnode.set_scalar("fsync_rate", str(hw0.fsync_rate), origin="instance") + if hw0.bclk_rate: + lnode.set_scalar("bclk_rate", str(hw0.bclk_rate), origin="instance") + if hw0.tdm_slots: + lnode.set_scalar("tdm_slots", str(hw0.tdm_slots), origin="instance") + if hw0.tdm_slot_width: + lnode.set_scalar("tdm_slot_width", str(hw0.tdm_slot_width), origin="instance") + root_cfg.children.append(lnode) + + if ws is not None: + ws.attach_host_copier_io_nodes(vm) + + return vm diff --git a/sof-builder/sof_builder/tplg_ipc4.py b/sof-builder/sof_builder/tplg_ipc4.py index 7d724d9..c6387c2 100644 --- a/sof-builder/sof_builder/tplg_ipc4.py +++ b/sof-builder/sof_builder/tplg_ipc4.py @@ -79,14 +79,28 @@ SND_SOC_TPLG_TUPLE_TYPE_SHORT = 5 # SOF Topology Tokens (from src/include/kernel/tokens.h) +SOF_TKN_DAI_TYPE = 154 +SOF_TKN_DAI_INDEX = 155 +SOF_TKN_DAI_DIRECTION = 156 + +SOF_TKN_SCHED_PERIOD = 200 SOF_TKN_SCHED_PRIORITY = 201 SOF_TKN_SCHED_CORE = 203 +SOF_TKN_SCHED_TIME_DOMAIN = 205 +SOF_TKN_SCHED_DYNAMIC_PIPELINE = 206 +SOF_TKN_SCHED_LP_MODE = 207 +SOF_TKN_SCHED_USE_CHAIN_DMA = 209 +SOF_TKN_SCHED_KCPS = 210 +SOF_TKN_SCHED_DIRECTION = 211 +SOF_TKN_SCHED_DIRECTION_VALID = 212 + SOF_TKN_GAIN_RAMP_TYPE = 260 SOF_TKN_GAIN_RAMP_DURATION = 261 SOF_TKN_GAIN_VAL = 262 SOF_TKN_SRC_RATE_OUT = 301 SOF_TKN_ASRC_RATE_OUT = 321 SOF_TKN_ASRC_OPERATION_MODE = 323 +SOF_TKN_COMP_FORMAT = 402 SOF_TKN_COMP_CORE_ID = 404 SOF_TKN_COMP_UUID = 405 SOF_TKN_COMP_CPC = 406 @@ -97,29 +111,40 @@ SOF_TKN_COMP_OUTPUT_PIN_BINDING_WNAME = 414 SOF_TKN_COMP_NUM_INPUT_AUDIO_FORMATS = 415 SOF_TKN_COMP_NUM_OUTPUT_AUDIO_FORMATS = 416 +SOF_TKN_COMP_NO_WNAME_IN_KCONTROL_NAME = 417 SOF_TKN_COMP_SCHED_DOMAIN = 418 SOF_TKN_COMP_DOMAIN_ID = 419 SOF_TKN_COMP_STACK_BYTES = 420 SOF_TKN_COMP_HEAP_BYTES = 421 +SOF_TKN_STREAM_CAPTURE_COMPATIBLE_D0I3 = 1201 +SOF_TKN_MIXER_TYPE = 1700 SOF_TKN_CAVS_AUDIO_FORMAT_IN_RATE = 1900 SOF_TKN_CAVS_AUDIO_FORMAT_IN_BIT_DEPTH = 1901 +SOF_TKN_CAVS_AUDIO_FORMAT_IN_VALID_BITS = 1902 +SOF_TKN_CAVS_AUDIO_FORMAT_IN_CHANNELS = 1903 SOF_TKN_CAVS_AUDIO_FORMAT_IN_CH_MAP = 1904 SOF_TKN_CAVS_AUDIO_FORMAT_IN_CH_CFG = 1905 SOF_TKN_CAVS_AUDIO_FORMAT_IN_INTERLEAVING_STYLE = 1906 SOF_TKN_CAVS_AUDIO_FORMAT_IN_FMT_CFG = 1907 +SOF_TKN_CAVS_AUDIO_FORMAT_IN_SAMPLE_TYPE = 1908 SOF_TKN_CAVS_AUDIO_FORMAT_INPUT_PIN_INDEX = 1909 SOF_TKN_CAVS_AUDIO_FORMAT_OUT_RATE = 1930 SOF_TKN_CAVS_AUDIO_FORMAT_OUT_BIT_DEPTH = 1931 +SOF_TKN_CAVS_AUDIO_FORMAT_OUT_VALID_BITS = 1932 +SOF_TKN_CAVS_AUDIO_FORMAT_OUT_CHANNELS = 1933 SOF_TKN_CAVS_AUDIO_FORMAT_OUT_CH_MAP = 1934 SOF_TKN_CAVS_AUDIO_FORMAT_OUT_CH_CFG = 1935 SOF_TKN_CAVS_AUDIO_FORMAT_OUT_INTERLEAVING_STYLE = 1936 SOF_TKN_CAVS_AUDIO_FORMAT_OUT_FMT_CFG = 1937 +SOF_TKN_CAVS_AUDIO_FORMAT_OUT_SAMPLE_TYPE = 1938 SOF_TKN_CAVS_AUDIO_FORMAT_OUTPUT_PIN_INDEX = 1939 SOF_TKN_CAVS_AUDIO_FORMAT_IBS = 1970 SOF_TKN_CAVS_AUDIO_FORMAT_OBS = 1971 +SOF_TKN_COMP_NODE_TYPE = 1980 +SOF_TKN_DEEP_BUFFER_DMA_MS = 1981 # Testbench Module IDs (from tools/testbench/include/testbench/topology_ipc4.h) TB_COPIER_MODULE_ID = 0x1 @@ -253,7 +278,9 @@ class TplgKcontrolDesc: widget_name: str = "" pipeline_id: int = 0 # Mixer fields + min_val: int = 0 max_val: int = 0 + invert: int = 0 num_channels: int = 2 scale_min: int = 0 scale_step: int = 0 @@ -263,11 +290,12 @@ class TplgKcontrolDesc: curve_duration: int = 0 # Enum fields enum_texts: List[str] = field(default_factory=list) - # Bytes fields (ABI header + payload) + # Bytes fields (ABI header + payload + raw private payload) abi_magic: int = 0 abi_type: int = 0 # param_id for LARGE_CONFIG_SET abi_size: int = 0 abi_data: bytes = b"" + raw_priv_data: bytes = b"" def default_step_value(self) -> int: """Return the 0 dB step index for volume controls, 1 for switches, or 0 for enums.""" @@ -288,6 +316,46 @@ class TplgPipelineDesc: priority: int = 0 instance_id: int = 0 mem_usage: int = 0 + period: int = 0 + time_domain: int = 0 + dynamic_pipeline: int = 0 + lp_mode: int = 0 + direction: int = 0 + direction_valid: int = 0 + word_tokens: Dict[int, int] = field(default_factory=dict) + str_tokens: Dict[int, str] = field(default_factory=dict) + + +@dataclass +class TplgHwConfigDesc: + config_id: int = 0 + fmt: int = 0 + mclk_rate: int = 0 + bclk_rate: int = 0 + fsync_rate: int = 0 + tdm_slots: int = 0 + tdm_slot_width: int = 0 + + +@dataclass +class TplgLinkDesc: + link_id: int = 0 + name: str = "" + stream_name: str = "" + default_hw_config_id: int = 0 + hw_configs: List[TplgHwConfigDesc] = field(default_factory=list) + word_tokens: Dict[int, int] = field(default_factory=dict) + str_tokens: Dict[int, str] = field(default_factory=dict) + + +@dataclass +class TplgDaiDesc: + dai_id: int = 0 + name: str = "" + playback: int = 0 + capture: int = 0 + word_tokens: Dict[int, int] = field(default_factory=dict) + str_tokens: Dict[int, str] = field(default_factory=dict) @dataclass @@ -307,6 +375,8 @@ class TplgWidgetDesc: is_pages: int = 0 cpc: int = 0 uuid_bytes: bytes = b"\x00" * 16 + orig_dapm_type: int = 0 + orig_uuid_bytes: bytes = b"\x00" * 16 num_input_pins: int = 1 num_output_pins: int = 1 input_pin_binding: List[str] = field(default_factory=list) @@ -320,7 +390,10 @@ class TplgWidgetDesc: src_sink_rate: int = 0 asrc_out_freq: int = 0 asrc_mode: int = 0 + word_tokens: Dict[int, int] = field(default_factory=dict) + str_tokens: Dict[int, str] = field(default_factory=dict) kcontrols: List[TplgKcontrolDesc] = field(default_factory=list) + orig_kcontrols: List[TplgKcontrolDesc] = field(default_factory=list) # Computed during prepare pass in_audio_fmt: Ipc4AudioFormat = field(default_factory=Ipc4AudioFormat) out_audio_fmt: Ipc4AudioFormat = field(default_factory=Ipc4AudioFormat) @@ -345,6 +418,23 @@ class TplgPcmDesc: capture_stream_name: str playback_host_name: str = "" capture_host_name: str = "" + playback: int = 0 + capture: int = 0 + compress: int = 0 + pb_formats: int = 0 + pb_rates: int = 0 + pb_rate_min: int = 0 + pb_rate_max: int = 0 + pb_channels_min: int = 0 + pb_channels_max: int = 0 + cap_formats: int = 0 + cap_rates: int = 0 + cap_rate_min: int = 0 + cap_rate_max: int = 0 + cap_channels_min: int = 0 + cap_channels_max: int = 0 + capture_compatible_d0i3: int = 0 + word_tokens: Dict[int, int] = field(default_factory=dict) @dataclass @@ -355,6 +445,29 @@ class TplgIpc4Topology: routes: List[TplgRouteDesc] = field(default_factory=list) pcms: List[TplgPcmDesc] = field(default_factory=list) kcontrols: List[TplgKcontrolDesc] = field(default_factory=list) + links: List[TplgLinkDesc] = field(default_factory=list) + dais: List[TplgDaiDesc] = field(default_factory=list) + abi_version: int = 0 + tplg_version: int = 0 + manifest_priv: bytes = b"" + sof_abi_bytes: bytes = b"" + sof_abi_major: int = 0 + sof_abi_minor: int = 0 + sof_abi_patch: int = 0 + ipc_protocol: str = "" # "IPC4", "IPC3", or "" + block_counts: Dict[int, int] = field(default_factory=dict) + + @property + def sof_abi_tuple(self) -> Optional[Tuple[int, int, int]]: + if self.sof_abi_major > 0: + return (self.sof_abi_major, self.sof_abi_minor, self.sof_abi_patch) + return None + + @property + def sof_abi_str(self) -> str: + if self.sof_abi_major > 0: + return f"{self.sof_abi_major}.{self.sof_abi_minor}.{self.sof_abi_patch}" + return "" # --------------------------------------------------------------------------- @@ -882,10 +995,47 @@ def parse_bytes(data: bytes) -> TplgIpc4Topology: ) = struct.unpack_from("<9I", data, off) if hdr_size != 36 or off + 36 + payload_size > size: break + tplg.block_counts[hdr_type] = tplg.block_counts.get(hdr_type, 0) + hdr_count + if tplg.abi_version == 0 and _abi: + tplg.abi_version = _abi + if tplg.tplg_version == 0 and _version: + tplg.tplg_version = _version block_end = off + 36 + payload_size off += 36 - if hdr_type == SND_SOC_TPLG_TYPE_DAPM_WIDGET: + if hdr_type == SND_SOC_TPLG_TYPE_MANIFEST: + if off + 112 <= block_end: + priv_sz = struct.unpack_from("= 6 and tplg.manifest_priv[1] == 0 and tplg.manifest_priv[3] == 0 and tplg.manifest_priv[5] == 0: + # IPC4 manifest encodes SOF ABI as three 16-bit LE values + maj, min_v, pat = struct.unpack_from("<3H", tplg.manifest_priv, 0) + if 1 <= maj <= 255: + tplg.sof_abi_bytes = tplg.manifest_priv[:6] + tplg.sof_abi_major = maj + tplg.sof_abi_minor = min_v + tplg.sof_abi_patch = pat + tplg.ipc_protocol = "IPC4" + elif priv_sz == 3 or (priv_sz >= 3 and tplg.manifest_priv[1] != 0): + # IPC3 manifest encodes SOF ABI as three 8-bit values (major, minor, patch) + maj, min_v, pat = struct.unpack_from("<3B", tplg.manifest_priv, 0) + if 1 <= maj <= 255: + tplg.sof_abi_bytes = tplg.manifest_priv[:3] + tplg.sof_abi_major = maj + tplg.sof_abi_minor = min_v + tplg.sof_abi_patch = pat + tplg.ipc_protocol = "IPC3" + elif priv_sz >= 6: + maj, min_v, pat = struct.unpack_from("<3H", tplg.manifest_priv, 0) + if 1 <= maj <= 255 and min_v <= 4095 and pat <= 4095: + tplg.sof_abi_bytes = tplg.manifest_priv[:6] + tplg.sof_abi_major = maj + tplg.sof_abi_minor = min_v + tplg.sof_abi_patch = pat + tplg.ipc_protocol = "IPC4" + + elif hdr_type == SND_SOC_TPLG_TYPE_DAPM_WIDGET: pipeline_id = hdr_index for _ in range(hdr_count): if off + 132 > block_end: @@ -926,6 +1076,14 @@ def parse_bytes(data: bytes) -> TplgIpc4Topology: core_id=p_core, priority=p_prio, instance_id=pipeline_id, + period=word_map.get(SOF_TKN_SCHED_PERIOD, 0), + time_domain=word_map.get(SOF_TKN_SCHED_TIME_DOMAIN, 0), + dynamic_pipeline=word_map.get(SOF_TKN_SCHED_DYNAMIC_PIPELINE, 0), + lp_mode=word_map.get(SOF_TKN_SCHED_LP_MODE, 0), + direction=word_map.get(SOF_TKN_SCHED_DIRECTION, 0), + direction_valid=word_map.get(SOF_TKN_SCHED_DIRECTION_VALID, 0), + word_tokens=dict(word_map), + str_tokens=dict(str_map), ) # Consume any attached kcontrols if present off, _ = TplgIpc4Parser._parse_widget_controls( @@ -957,6 +1115,8 @@ def parse_bytes(data: bytes) -> TplgIpc4Topology: is_pages=word_map.get(SOF_TKN_COMP_IS_PAGES, 0), cpc=cpc, uuid_bytes=uuid_val, + orig_dapm_type=w_id, + orig_uuid_bytes=uuid_val, num_input_pins=word_map.get(SOF_TKN_COMP_NUM_INPUT_PINS, 1) or 1, num_output_pins=word_map.get(SOF_TKN_COMP_NUM_OUTPUT_PINS, 1) or 1, pga_target_volume=word_map.get(SOF_TKN_GAIN_VAL, 0x7FFFFFFF), @@ -965,6 +1125,8 @@ def parse_bytes(data: bytes) -> TplgIpc4Topology: src_sink_rate=word_map.get(SOF_TKN_SRC_RATE_OUT, 0), asrc_out_freq=word_map.get(SOF_TKN_ASRC_RATE_OUT, 0), asrc_mode=word_map.get(SOF_TKN_ASRC_OPERATION_MODE, 0), + word_tokens=dict(word_map), + str_tokens=dict(str_map), ) # Parse pin audio formats & bindings @@ -975,19 +1137,28 @@ def parse_bytes(data: bytes) -> TplgIpc4Topology: { SOF_TKN_CAVS_AUDIO_FORMAT_IN_RATE, SOF_TKN_CAVS_AUDIO_FORMAT_IN_BIT_DEPTH, + SOF_TKN_CAVS_AUDIO_FORMAT_IN_VALID_BITS, + SOF_TKN_CAVS_AUDIO_FORMAT_IN_CHANNELS, SOF_TKN_CAVS_AUDIO_FORMAT_IN_CH_MAP, SOF_TKN_CAVS_AUDIO_FORMAT_IN_CH_CFG, SOF_TKN_CAVS_AUDIO_FORMAT_IN_INTERLEAVING_STYLE, SOF_TKN_CAVS_AUDIO_FORMAT_IN_FMT_CFG, + SOF_TKN_CAVS_AUDIO_FORMAT_IN_SAMPLE_TYPE, SOF_TKN_CAVS_AUDIO_FORMAT_INPUT_PIN_INDEX, SOF_TKN_CAVS_AUDIO_FORMAT_IBS, }, num_in_fmts, ) - for fset in in_fmt_sets: + for fidx, fset in enumerate(in_fmt_sets): + fmt_cfg = fset.get(SOF_TKN_CAVS_AUDIO_FORMAT_IN_FMT_CFG, 0) + if fmt_cfg == 0: + ch = fset.get(SOF_TKN_CAVS_AUDIO_FORMAT_IN_CHANNELS, 2) + vb = fset.get(SOF_TKN_CAVS_AUDIO_FORMAT_IN_VALID_BITS, fset.get(SOF_TKN_CAVS_AUDIO_FORMAT_IN_BIT_DEPTH, 32)) + st_v = fset.get(SOF_TKN_CAVS_AUDIO_FORMAT_IN_SAMPLE_TYPE, 0) + fmt_cfg = (ch & 0xFF) | ((vb & 0xFF) << 8) | ((st_v & 0xFF) << 16) wdesc.input_pin_fmts.append( Ipc4PinFormat( - pin_index=fset.get(SOF_TKN_CAVS_AUDIO_FORMAT_INPUT_PIN_INDEX, 0), + pin_index=fset.get(SOF_TKN_CAVS_AUDIO_FORMAT_INPUT_PIN_INDEX, fidx), buffer_size=fset.get(SOF_TKN_CAVS_AUDIO_FORMAT_IBS, 0), audio_fmt=Ipc4AudioFormat( sampling_frequency=fset.get(SOF_TKN_CAVS_AUDIO_FORMAT_IN_RATE, 48000), @@ -995,7 +1166,7 @@ def parse_bytes(data: bytes) -> TplgIpc4Topology: ch_map=fset.get(SOF_TKN_CAVS_AUDIO_FORMAT_IN_CH_MAP, 0xFFFFFF10), ch_cfg=fset.get(SOF_TKN_CAVS_AUDIO_FORMAT_IN_CH_CFG, 1), interleaving_style=fset.get(SOF_TKN_CAVS_AUDIO_FORMAT_IN_INTERLEAVING_STYLE, 0), - fmt_cfg=fset.get(SOF_TKN_CAVS_AUDIO_FORMAT_IN_FMT_CFG, 0), + fmt_cfg=fmt_cfg, ), ) ) @@ -1005,19 +1176,28 @@ def parse_bytes(data: bytes) -> TplgIpc4Topology: { SOF_TKN_CAVS_AUDIO_FORMAT_OUT_RATE, SOF_TKN_CAVS_AUDIO_FORMAT_OUT_BIT_DEPTH, + SOF_TKN_CAVS_AUDIO_FORMAT_OUT_VALID_BITS, + SOF_TKN_CAVS_AUDIO_FORMAT_OUT_CHANNELS, SOF_TKN_CAVS_AUDIO_FORMAT_OUT_CH_MAP, SOF_TKN_CAVS_AUDIO_FORMAT_OUT_CH_CFG, SOF_TKN_CAVS_AUDIO_FORMAT_OUT_INTERLEAVING_STYLE, SOF_TKN_CAVS_AUDIO_FORMAT_OUT_FMT_CFG, + SOF_TKN_CAVS_AUDIO_FORMAT_OUT_SAMPLE_TYPE, SOF_TKN_CAVS_AUDIO_FORMAT_OUTPUT_PIN_INDEX, SOF_TKN_CAVS_AUDIO_FORMAT_OBS, }, num_out_fmts, ) - for fset in out_fmt_sets: + for fidx, fset in enumerate(out_fmt_sets): + fmt_cfg = fset.get(SOF_TKN_CAVS_AUDIO_FORMAT_OUT_FMT_CFG, 0) + if fmt_cfg == 0: + ch = fset.get(SOF_TKN_CAVS_AUDIO_FORMAT_OUT_CHANNELS, 2) + vb = fset.get(SOF_TKN_CAVS_AUDIO_FORMAT_OUT_VALID_BITS, fset.get(SOF_TKN_CAVS_AUDIO_FORMAT_OUT_BIT_DEPTH, 32)) + st_v = fset.get(SOF_TKN_CAVS_AUDIO_FORMAT_OUT_SAMPLE_TYPE, 0) + fmt_cfg = (ch & 0xFF) | ((vb & 0xFF) << 8) | ((st_v & 0xFF) << 16) wdesc.output_pin_fmts.append( Ipc4PinFormat( - pin_index=fset.get(SOF_TKN_CAVS_AUDIO_FORMAT_OUTPUT_PIN_INDEX, 0), + pin_index=fset.get(SOF_TKN_CAVS_AUDIO_FORMAT_OUTPUT_PIN_INDEX, fidx), buffer_size=fset.get(SOF_TKN_CAVS_AUDIO_FORMAT_OBS, 0), audio_fmt=Ipc4AudioFormat( sampling_frequency=fset.get(SOF_TKN_CAVS_AUDIO_FORMAT_OUT_RATE, 48000), @@ -1025,19 +1205,17 @@ def parse_bytes(data: bytes) -> TplgIpc4Topology: ch_map=fset.get(SOF_TKN_CAVS_AUDIO_FORMAT_OUT_CH_MAP, 0xFFFFFF10), ch_cfg=fset.get(SOF_TKN_CAVS_AUDIO_FORMAT_OUT_CH_CFG, 1), interleaving_style=fset.get(SOF_TKN_CAVS_AUDIO_FORMAT_OUT_INTERLEAVING_STYLE, 0), - fmt_cfg=fset.get(SOF_TKN_CAVS_AUDIO_FORMAT_OUT_FMT_CFG, 0), + fmt_cfg=fmt_cfg, ), ) ) - if wdesc.num_input_pins > 1: - wdesc.input_pin_binding = _parse_token_sets_string( - arrays, SOF_TKN_COMP_INPUT_PIN_BINDING_WNAME, wdesc.num_input_pins - ) - if wdesc.num_output_pins > 1: - wdesc.output_pin_binding = _parse_token_sets_string( - arrays, SOF_TKN_COMP_OUTPUT_PIN_BINDING_WNAME, wdesc.num_output_pins - ) + wdesc.input_pin_binding = _parse_token_sets_string( + arrays, SOF_TKN_COMP_INPUT_PIN_BINDING_WNAME, max(1, wdesc.num_input_pins) + ) + wdesc.output_pin_binding = _parse_token_sets_string( + arrays, SOF_TKN_COMP_OUTPUT_PIN_BINDING_WNAME, max(1, wdesc.num_output_pins) + ) # Assign module_id and instance_id exactly like topology_ipc4.c if w_id == SND_SOC_TPLG_DAPM_PGA: @@ -1127,10 +1305,11 @@ def parse_bytes(data: bytes) -> TplgIpc4Topology: wdesc.instance_id = instance_ids.get(SND_SOC_TPLG_DAPM_EFFECT, 0) instance_ids[SND_SOC_TPLG_DAPM_EFFECT] = wdesc.instance_id + 1 - # Parse widget kcontrols + # Parse widget kcontrols (keep raw orig_kcontrols untouched before testbench remapping) off, w_ctls = TplgIpc4Parser._parse_widget_controls( data, off, block_end, num_kctls, wdesc, tplg ) + wdesc.orig_kcontrols = list(w_ctls) if w_id == SND_SOC_TPLG_DAPM_EFFECT and wdesc.dapm_type == SND_SOC_TPLG_DAPM_BUFFER: w_ctls = [c for c in w_ctls if c.ctl_type != SND_SOC_TPLG_TYPE_BYTES] wdesc.kcontrols = w_ctls @@ -1156,15 +1335,48 @@ def parse_bytes(data: bytes) -> TplgIpc4Topology: break pcm_name = _cstr(data[off + 4:off + 48]) pcm_id = struct.unpack_from(" 0 and off + 912 + pcm_priv_size <= block_end: + for _at, elems in _parse_vendor_arrays(data[off + 912:off + 912 + pcm_priv_size]): + for tkn, vval in elems: + if isinstance(vval, int): + pcm_word_map[tkn] = int(vval) off += 912 + pcm_priv_size pdesc = TplgPcmDesc( pcm_id=pcm_id, name=pcm_name, playback_stream_name=pb_sname, capture_stream_name=cap_sname, + playback=pb_flag, + capture=cap_flag, + compress=comp_flag, + pb_formats=pb_fmts, + pb_rates=pb_rates, + pb_rate_min=pb_rmin, + pb_rate_max=pb_rmax, + pb_channels_min=pb_cmin, + pb_channels_max=pb_cmax, + cap_formats=cap_fmts, + cap_rates=cap_rates, + cap_rate_min=cap_rmin, + cap_rate_max=cap_rmax, + cap_channels_min=cap_cmin, + cap_channels_max=cap_cmax, + capture_compatible_d0i3=pcm_word_map.get( + SOF_TKN_STREAM_CAPTURE_COMPATIBLE_D0I3, 0 + ), + word_tokens=pcm_word_map, ) for w in tplg.widgets: if w.dapm_type in (SND_SOC_TPLG_DAPM_AIF_IN, SND_SOC_TPLG_DAPM_AIF_OUT): @@ -1174,6 +1386,84 @@ def parse_bytes(data: bytes) -> TplgIpc4Topology: pdesc.capture_host_name = w.name tplg.pcms.append(pdesc) + elif hdr_type in (SND_SOC_TPLG_TYPE_DAI_LINK, SND_SOC_TPLG_TYPE_BACKEND_LINK): + for _ in range(hdr_count): + if off + 1656 > block_end: + break + link_id = struct.unpack_from(" 0 and off + 1656 + lpriv_sz <= block_end: + for at, elems in _parse_vendor_arrays(data[off + 1656:off + 1656 + lpriv_sz]): + if at == SND_SOC_TPLG_TUPLE_TYPE_STRING: + for tkn, sval in elems: + l_smap[tkn] = str(sval) + elif at != SND_SOC_TPLG_TUPLE_TYPE_UUID: + for tkn, vval in elems: + l_wmap[tkn] = int(vval) + off += 1656 + lpriv_sz + tplg.links.append( + TplgLinkDesc( + link_id=link_id, + name=lname, + stream_name=lsname, + default_hw_config_id=def_hw_id, + hw_configs=hw_cfgs, + word_tokens=l_wmap, + str_tokens=l_smap, + ) + ) + + elif hdr_type == SND_SOC_TPLG_TYPE_DAI: + for _ in range(hdr_count): + if off + 280 > block_end: + break + dname = _cstr(data[off + 4:off + 48]) + dai_id, pb_f, cap_f = struct.unpack_from("<3I", data, off + 48) + dpriv_sz = struct.unpack_from(" 0 and off + 280 + dpriv_sz <= block_end: + for at, elems in _parse_vendor_arrays(data[off + 280:off + 280 + dpriv_sz]): + if at == SND_SOC_TPLG_TUPLE_TYPE_STRING: + for tkn, sval in elems: + d_smap[tkn] = str(sval) + elif at != SND_SOC_TPLG_TUPLE_TYPE_UUID: + for tkn, vval in elems: + d_wmap[tkn] = int(vval) + off += 280 + dpriv_sz + tplg.dais.append( + TplgDaiDesc( + dai_id=dai_id, + name=dname, + playback=pb_f, + capture=cap_f, + word_tokens=d_wmap, + str_tokens=d_smap, + ) + ) + off = block_end # Assign pipeline core_id to LL widgets matching topology_ipc4.c lines 1858-1879 @@ -1217,17 +1507,20 @@ def _parse_widget_controls( break idx = num_mixers num_mixers += 1 - max_val = struct.unpack_from("= 32: - abi_magic, abi_type, abi_size, _abi_ver = struct.unpack_from( - "<4I", priv_data, 0 - ) - if 32 + abi_size <= len(priv_data): - kctl = TplgKcontrolDesc( - name=cname, - ctl_type=ctype, - ops_info=ops_info, - index=idx, - module_id=wdesc.module_id, - instance_id=wdesc.instance_id, - widget_name=wdesc.name, - pipeline_id=wdesc.pipeline_id, - abi_magic=abi_magic, - abi_type=abi_type, - abi_size=abi_size, - abi_data=priv_data[32:32 + abi_size], + if wdesc is not None: + abi_magic, abi_type, abi_size, _abi_ver = (0, 0, 0, 0) + abi_payload = b"" + if len(priv_data) >= 32: + abi_magic, abi_type, abi_size, _abi_ver = struct.unpack_from( + "<4I", priv_data, 0 ) - ctls.append(kctl) - tplg.kcontrols.append(kctl) + if 32 + abi_size <= len(priv_data): + abi_payload = priv_data[32:32 + abi_size] + kctl = TplgKcontrolDesc( + name=cname, + ctl_type=ctype, + ops_info=ops_info, + index=idx, + module_id=wdesc.module_id, + instance_id=wdesc.instance_id, + widget_name=wdesc.name, + pipeline_id=wdesc.pipeline_id, + abi_magic=abi_magic, + abi_type=abi_type, + abi_size=abi_size, + abi_data=abi_payload, + raw_priv_data=priv_data, + ) + ctls.append(kctl) + tplg.kcontrols.append(kctl) else: break diff --git a/sof-builder/sof_builder/window.py b/sof-builder/sof_builder/window.py index 701d961..83f06b7 100644 --- a/sof-builder/sof_builder/window.py +++ b/sof-builder/sof_builder/window.py @@ -72,6 +72,17 @@ SchedulingTelemetryWidget, ) from .text_editor import TopologyTextEditor +from .tplg_binary import ( + TplgBinaryVersionInfo, + TplgSourceMatchResult, + WorkspaceVersionMatch, + attach_binary_manifest_metadata, + build_graph_from_tplg, + extract_tplg_version_info, + identify_tplg_source, + resolve_workspace_for_binary, +) +from .tplg_ipc4 import TplgIpc4Parser @dataclass @@ -88,6 +99,7 @@ class GraphTabPage: mode_switch_btn: Gtk.ToggleButton tab_box: Gtk.Box title_lbl: Gtk.Label + banner_box: Optional[Gtk.Box] = None is_untitled: bool = False text_needs_refresh_from_graph: bool = True stream_waveforms: Dict[str, Tuple[List[float], List[float]]] = field(default_factory=dict) @@ -120,6 +132,8 @@ def __init__(self, app: Gtk.Application, initial_dir: Optional[str] = None): self._saved_open_tabs: List[Dict[str, Any]] = [] self._saved_active_tab_key: str = "" self._saved_topology2_dir: str = "" + self._text_editor_font_family: str = "Monospace" + self._text_editor_font_size: int = 11 self._restoring_session_tabs: bool = False self._applying_programmatic_paned_pos: bool = True self._paned_layout_ready: bool = False @@ -174,10 +188,34 @@ def __init__(self, app: Gtk.Application, initial_dir: Optional[str] = None): 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) + # Load initial topology2 directory if valid (for .tplg files, resolve binary ABI workspace first) + abs_init = ( + os.path.abspath(initial_dir) + if (initial_dir and os.path.isfile(os.path.abspath(initial_dir))) + else "" + ) + if abs_init and abs_init.lower().endswith(".tplg"): + try: + init_tplg = TplgIpc4Parser.parse_file(abs_init) + init_ver = extract_tplg_version_info(init_tplg) + ver_ws, _ver_match = resolve_workspace_for_binary(init_ver, None) + if ver_ws is not None and isinstance(ver_ws, Topology2Workspace): + self.load_topology2_directory( + ver_ws.root_dir, open_default_tab=False, preloaded_ws=ver_ws + ) + except Exception: + pass + if self.workspace is None: + default_dir = self._discover_default_topology2_dir(initial_dir) + if default_dir and os.path.isdir(default_dir): + self.load_topology2_directory(default_dir, open_default_tab=False) + self.open_tplg_file_in_tab(abs_init) + else: + default_dir = self._discover_default_topology2_dir(initial_dir) + if default_dir and os.path.isdir(default_dir): + self.load_topology2_directory(default_dir, open_default_tab=not bool(abs_init)) + if abs_init: + self.open_conf_file_in_tab(abs_init) def _discover_default_topology2_dir(self, initial_dir: Optional[str] = None) -> str: """Locate a valid topology2 workspace directory via west, env vars, or sibling checkouts.""" @@ -341,6 +379,7 @@ def _build_menubar(self) -> Gtk.PopoverMenuBar: 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_tplg", self.action_export_tplg) self._register_win_action("export_pdf", self.action_export_pdf) self._register_win_action("close_tab", lambda: self.close_current_tab()) @@ -354,13 +393,16 @@ def _build_menubar(self) -> Gtk.PopoverMenuBar: 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("find_text", lambda: self.action_find_text(with_replace=False)) + self._register_win_action("replace_text", lambda: self.action_find_text(with_replace=True)) + self._register_win_action("goto_line", self.action_goto_line) 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("zoom_in", self.action_zoom_in) + self._register_win_action("zoom_out", self.action_zoom_out) + self._register_win_action("reset_zoom", self.action_reset_zoom) self._register_win_action( "toggle_fullscreen", lambda: self.unfullscreen() if self.is_fullscreen() else self.fullscreen(), @@ -404,9 +446,12 @@ def _build_menubar(self) -> Gtk.PopoverMenuBar: "win.export_pdf": ["e"], "win.close_tab": ["w"], "win.toggle_text_mode": ["t"], - "win.zoom_in": ["plus", "equal"], - "win.zoom_out": ["minus"], - "win.reset_zoom": ["0"], + "win.find_text": ["f"], + "win.replace_text": ["h"], + "win.goto_line": ["g"], + "win.zoom_in": ["plus", "equal", "KP_Add"], + "win.zoom_out": ["minus", "KP_Subtract"], + "win.reset_zoom": ["0", "KP_0"], "win.toggle_fullscreen": ["F11"], } for act_name, keys in accels.items(): @@ -433,6 +478,7 @@ def _build_menubar(self) -> Gtk.PopoverMenuBar: 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("Compile & Export .tplg…", "win.export_tplg") file_save_sec.append("Export to PDF…", "win.export_pdf") file_menu.append_section(None, file_save_sec) @@ -461,6 +507,12 @@ def _build_menubar(self) -> Gtk.PopoverMenuBar: edit_del_sec.append("Delete", "win.delete_selected") edit_menu.append_section(None, edit_del_sec) + edit_find_sec = Gio.Menu.new() + edit_find_sec.append("Find…", "win.find_text") + edit_find_sec.append("Find & Replace…", "win.replace_text") + edit_find_sec.append("Go to Line…", "win.goto_line") + edit_menu.append_section(None, edit_find_sec) + menubar_model.append_submenu("Edit", edit_menu) # 3. View Menu (Fit Graph, Auto-Layout, Toggle Text/Graph, Zoom In/Out/Reset, Fullscreen) @@ -1851,6 +1903,11 @@ def _load_ui_state(self) -> None: self._saved_active_tab_key = data["active_tab_key"] if "last_topology2_dir" in data and isinstance(data["last_topology2_dir"], str): self._saved_topology2_dir = data["last_topology2_dir"] + if "text_editor_font_family" in data and isinstance(data["text_editor_font_family"], str): + if data["text_editor_font_family"].strip(): + self._text_editor_font_family = data["text_editor_font_family"].strip() + if "text_editor_font_size" in data and isinstance(data["text_editor_font_size"], (int, float)): + self._text_editor_font_size = max(8, min(36, int(data["text_editor_font_size"]))) except Exception as exc: debug_log_line("UI-STATE", f"Failed to load '{path}': {exc}") @@ -1935,6 +1992,8 @@ def _save_ui_state(self) -> None: if (getattr(self, "workspace", None) and self.workspace.root_dir) else self._saved_topology2_dir ), + "text_editor_font_family": self._text_editor_font_family, + "text_editor_font_size": self._text_editor_font_size, } parent_dir = os.path.dirname(path) if parent_dir: @@ -2077,12 +2136,21 @@ def _finish_programmatic_paned_sync(self, sync_seq: int) -> bool: # Workspace Loading & Left Pane Selection Handling # ------------------------------------------------------------------------- - def load_topology2_directory(self, path: str) -> None: + def load_topology2_directory( + self, + path: str, + open_default_tab: bool = True, + preloaded_ws: Optional[Topology2Workspace] = None, + ) -> None: abs_path = os.path.abspath(path) debug_log_action("LOAD-WORKSPACE", f"Load topology2 directory '{abs_path}'") - self.append_log(f"Scanning Topology2 directory: {abs_path} …") - ws = Topology2Workspace(abs_path) - ws.scan_all() + if preloaded_ws is not None and os.path.abspath(preloaded_ws.root_dir) == abs_path: + ws = preloaded_ws + self.append_log(f"Loaded Topology2 directory: {abs_path}") + else: + self.append_log(f"Scanning Topology2 directory: {abs_path} …") + ws = Topology2Workspace(abs_path) + ws.scan_all() self.workspace = ws self.compiler = TopologyCompiler(abs_path) self.compiler.target_platform = self.target_platform @@ -2108,7 +2176,7 @@ def load_topology2_directory(self, path: str) -> None: self.status_lbl.set_text(summary) self.append_log(summary) - if not self._restore_saved_session_tabs(): + if open_default_tab and not self._restore_saved_session_tabs(): # Select default topology (`sof-hda-generic` if present, else first pipeline) hda = next((m for m in ws.machine_topologies if m.name == "sof-hda-generic"), None) if hda: @@ -2138,6 +2206,10 @@ def _restore_saved_session_tabs(self) -> bool: tab: Optional[GraphTabPage] = None if tab_key.startswith("source:"): tab = self.open_source_in_tab(pane_kind or "file", primary_id or source_file, secondary_id) + elif tab_key.startswith("tplg:"): + fpath = primary_id if (primary_id and os.path.isfile(primary_id)) else source_file + if fpath and os.path.isfile(fpath): + tab = self.open_tplg_file_in_tab(fpath, force_mode="binary") elif tab_key.startswith("file:"): fpath = primary_id if (primary_id and os.path.isfile(primary_id)) else source_file if fpath and os.path.isfile(fpath): @@ -2240,15 +2312,36 @@ def _format_tab_title( dirty_mark = " •" if vm.dirty else "" return f"{icon} {base}{dirty_mark}" + def _get_active_text_editor(self) -> Optional[TopologyTextEditor]: + active = self.get_active_tab() + if active is not None and active.view_stack.get_visible_child_name() == "text": + return active.text_editor + return None + + def _on_text_editor_state_changed(self) -> None: + self._update_undo_redo_buttons() + self._update_active_tab_header() + + def _on_text_editor_font_changed(self, font_family: str, font_size_pt: int) -> None: + self._text_editor_font_family = font_family + self._text_editor_font_size = font_size_pt + for t in self.graph_tabs: + t.text_editor.set_font(font_family=font_family, font_size_pt=font_size_pt, notify=False) + self._schedule_ui_state_save() + def _update_active_tab_header(self) -> None: tab = self.get_active_tab() if tab is None: return vm = tab.canvas.vm is_src = tab.tab_key.startswith("source:") or tab.mode_switch_btn.get_active() - tab.title_lbl.set_text(self._format_tab_title(vm, tab.primary_id, is_source_mode=is_src)) + title_txt = self._format_tab_title(vm, tab.primary_id, is_source_mode=is_src) + if tab.text_editor.is_modified_in_text and not title_txt.endswith(" •"): + title_txt += " •" + tab.title_lbl.set_text(title_txt) if vm is not None: - tip = f"{vm.title}\nFile: {vm.source_file or '(Unsaved)'}" + loc = vm.source_file or vm.source_tplg or "(Unsaved)" + tip = f"{vm.title}\nFile: {loc}" tab.tab_box.set_tooltip_text(tip) def _open_or_switch_graph_tab( @@ -2286,14 +2379,33 @@ def _open_or_switch_graph_tab( new_canvas.ignore_tick0_underrun = self.sched_ignore_tick0_chk.get_active() new_canvas.set_graph(vm, self.workspace) - new_text_editor = TopologyTextEditor() + new_text_editor = TopologyTextEditor( + on_edit_state_changed=self._on_text_editor_state_changed, + on_font_changed=self._on_text_editor_font_changed, + font_family=self._text_editor_font_family, + font_size_pt=self._text_editor_font_size, + ) + + banner_box = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=8) + banner_box.set_margin_top(4) + banner_box.set_margin_bottom(4) + banner_box.set_margin_start(8) + banner_box.set_margin_end(8) + banner_box.set_visible(False) + + graph_container = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=0) + graph_container.set_hexpand(True) + graph_container.set_vexpand(True) + new_canvas.set_vexpand(True) + graph_container.append(banner_box) + graph_container.append(new_canvas) view_stack = Gtk.Stack() view_stack.set_transition_type(Gtk.StackTransitionType.CROSSFADE) view_stack.set_transition_duration(120) view_stack.set_hexpand(True) view_stack.set_vexpand(True) - view_stack.add_named(new_canvas, "graph") + view_stack.add_named(graph_container, "graph") view_stack.add_named(new_text_editor, "text") view_stack.set_visible_child_name("graph") @@ -2326,11 +2438,12 @@ def _open_or_switch_graph_tab( view_stack=view_stack, tab_box=tab_box, title_lbl=title_lbl, + banner_box=banner_box, mode_switch_btn=mode_switch_btn, is_untitled=is_untitled, text_needs_refresh_from_graph=True, ) - tab_box.set_tooltip_text(f"{vm.title}\nFile: {vm.source_file or '(Unsaved)'}") + tab_box.set_tooltip_text(f"{vm.title}\nFile: {vm.source_file or vm.source_tplg or '(Unsaved)'}") new_text_editor.on_text_committed = lambda txt, tp=tab_page: self._on_tab_text_committed(tp, txt) mode_switch_btn.connect("toggled", self._on_tab_mode_switch_toggled, tab_page) close_btn.connect("clicked", lambda _b, tp=tab_page: self._close_graph_tab(tp)) @@ -2502,6 +2615,7 @@ def _on_tab_mode_switch_toggled( f"Text Editor mode: {vm.title if vm else tab_page.primary_id} " f"(Edit .conf text directly — changes sync to diagram)" ) + self._update_undo_redo_buttons() else: debug_log_action("TAB-MODE", f"Switch tab '{tab_page.primary_id}' to Visual Graph mode") btn.set_label(" Text") @@ -2834,22 +2948,31 @@ def action_new_monolithic_topology(self, name: Optional[str] = None) -> GraphTab return tab def action_open_file(self) -> None: - """Open a Gtk.FileDialog to open an existing .conf file in a new graph tab.""" + """Open a Gtk.FileDialog to open an existing .conf or .tplg file in a new graph tab.""" dialog = Gtk.FileDialog.new() - dialog.set_title("Open SOF Topology2 .conf File") + dialog.set_title("Open SOF Topology File (.conf / .tplg)") if self.workspace and os.path.isdir(self.workspace.root_dir): dialog.set_initial_folder(Gio.File.new_for_path(self.workspace.root_dir)) + both_filter = Gtk.FileFilter() + both_filter.set_name("SOF Topologies (*.conf, *.tplg)") + both_filter.add_pattern("*.conf") + both_filter.add_pattern("*.tplg") conf_filter = Gtk.FileFilter() conf_filter.set_name("ALSA Topology2 Config (*.conf)") conf_filter.add_pattern("*.conf") + tplg_filter = Gtk.FileFilter() + tplg_filter.set_name("ALSA Topology Binary (*.tplg)") + tplg_filter.add_pattern("*.tplg") all_filter = Gtk.FileFilter() all_filter.set_name("All Files (*)") all_filter.add_pattern("*") filters = Gio.ListStore.new(Gtk.FileFilter) + filters.append(both_filter) filters.append(conf_filter) + filters.append(tplg_filter) filters.append(all_filter) dialog.set_filters(filters) - dialog.set_default_filter(conf_filter) + dialog.set_default_filter(both_filter) dialog.open(self, None, self._on_conf_file_selected) def _on_conf_file_selected(self, dialog: Gtk.FileDialog, result: Gio.AsyncResult) -> None: @@ -2858,12 +2981,17 @@ def _on_conf_file_selected(self, dialog: Gtk.FileDialog, result: Gio.AsyncResult if gfile: path = gfile.get_path() if path: - self.open_conf_file_in_tab(path) + if path.lower().endswith(".tplg"): + self.open_tplg_file_in_tab(path) + else: + self.open_conf_file_in_tab(path) except Exception: pass def open_conf_file_in_tab(self, path: str) -> Optional[GraphTabPage]: - """Parse and open an arbitrary .conf file into a new or existing graph tab.""" + """Parse and open an arbitrary .conf (or .tplg) file into a new or existing graph tab.""" + if str(path).lower().endswith(".tplg"): + return self.open_tplg_file_in_tab(path) ws = self._ensure_workspace() abs_path = os.path.abspath(path) if not os.path.isfile(abs_path): @@ -2887,6 +3015,188 @@ def open_conf_file_in_tab(self, path: str) -> Optional[GraphTabPage]: self.status_lbl.set_text(f"Error opening {os.path.basename(abs_path)}: {exc}") return None + def open_tplg_file_in_tab( + self, + path: str, + force_mode: str = "auto", + ) -> Optional[GraphTabPage]: + """Parse a compiled .tplg binary, resolve versioned .conf source, and open editable graph tab.""" + abs_path = os.path.abspath(path) + if not os.path.isfile(abs_path): + self.status_lbl.set_text(f"Binary not found: {abs_path}") + return None + try: + tplg = TplgIpc4Parser.parse_file(abs_path) + bin_ver = extract_tplg_version_info(tplg) + bname = os.path.basename(abs_path) + + cur_ws = self.workspace + versioned_ws, ver_match = resolve_workspace_for_binary(bin_ver, cur_ws) + if ( + isinstance(versioned_ws, Topology2Workspace) + and ver_match.status in ("exact", "git_snapshot", "compatible") + and ( + cur_ws is None + or os.path.abspath(versioned_ws.root_dir) != os.path.abspath(cur_ws.root_dir) + ) + ): + self.load_topology2_directory( + versioned_ws.root_dir, open_default_tab=False, preloaded_ws=versioned_ws + ) + ws = versioned_ws + elif isinstance(versioned_ws, Topology2Workspace): + ws = versioned_ws + else: + ws = self._ensure_workspace() + + match_res = identify_tplg_source(ws, abs_path, tplg) + if match_res is not None: + match_res.version_info = bin_ver + match_res.version_match = ver_match + vname = match_res.variant.output_name if match_res.variant else "-" + self.append_log( + f"[TPLG] Parsed {bname} ({bin_ver.label}): {len(tplg.pipelines)} pipelines, " + f"{len(tplg.widgets)} widgets, {len(tplg.routes)} routes, {len(tplg.pcms)} PCMs\n" + f" Version workspace: {ver_match.source_desc or '-'}\n" + f" Source match: {match_res.rel_path} [variant={vname}] " + f"({match_res.diff.similarity_pct:.1f}%, {match_res.match_reason})\n" + f" Diff vs binary: {match_res.diff.summary}" + ) + else: + self.append_log( + f"[TPLG] Parsed {bname} ({bin_ver.label}): {len(tplg.pipelines)} pipelines, " + f"{len(tplg.widgets)} widgets, {len(tplg.routes)} routes, {len(tplg.pcms)} PCMs\n" + f" Version status: {ver_match.source_desc or 'no matching source .conf found'} " + f"— opening decompiled binary graph" + ) + + version_ok_for_source = ver_match.status not in ("ipc3_unsupported", "mismatch") + use_source = ( + match_res is not None + and match_res.source_vm is not None + and ( + force_mode == "source" + or ( + force_mode == "auto" + and version_ok_for_source + and (match_res.diff.is_exact or match_res.diff.similarity_pct >= 95.0) + ) + ) + ) + + if use_source and match_res is not None and match_res.source_vm is not None: + vm = match_res.source_vm.clone() + vm.source_tplg = abs_path + vlabel = match_res.variant.output_name if match_res.variant else os.path.basename(match_res.conf_path) + ver_prefix = f"{bin_ver.label} • " if bin_ver.label else "" + vm.binary_match_summary = ( + f"{ver_prefix}Source match {match_res.diff.similarity_pct:.0f}% ({vlabel}): {match_res.diff.summary}" + ) + attach_binary_manifest_metadata(vm, tplg, bin_ver, ver_match) + sec_id = match_res.variant.output_name if match_res.variant else None + tab = self._open_or_switch_graph_tab( + tab_key=f"tplg:source:{abs_path}", + pane_kind="topology", + primary_id=match_res.conf_path, + secondary_id=sec_id, + vm=vm, + is_untitled=False, + ) + self._populate_tplg_banner( + tab, abs_path, match_res, in_source_mode=True, bin_ver=bin_ver, ver_match=ver_match + ) + self.status_lbl.set_text( + f"Opened {bname} [{bin_ver.sof_abi_str or bin_ver.ipc_protocol or 'binary'}] " + f"via {match_res.rel_path} ({match_res.diff.similarity_pct:.0f}%)" + ) + return tab + + vm = build_graph_from_tplg(ws, abs_path, tplg, match_res, version_match=ver_match) + tab = self._open_or_switch_graph_tab( + tab_key=f"tplg:bin:{abs_path}", + pane_kind="topology", + primary_id=abs_path, + secondary_id=None, + vm=vm, + is_untitled=False, + ) + self._populate_tplg_banner( + tab, abs_path, match_res, in_source_mode=False, bin_ver=bin_ver, ver_match=ver_match + ) + self.status_lbl.set_text( + f"Opened decompiled binary: {bname} [{bin_ver.sof_abi_str or bin_ver.ipc_protocol or '?'}] " + f"({len(vm.containers)} pipelines, {len(vm.nodes)} nodes)" + ) + return tab + except Exception as exc: + self.append_log(f"Error opening binary {abs_path}: {exc}") + self.status_lbl.set_text(f"Error opening {os.path.basename(abs_path)}: {exc}") + return None + + def _populate_tplg_banner( + self, + tab: GraphTabPage, + tplg_path: str, + match_res: Optional[TplgSourceMatchResult], + in_source_mode: bool, + bin_ver: Optional[TplgBinaryVersionInfo] = None, + ver_match: Optional[WorkspaceVersionMatch] = None, + ) -> None: + if tab.banner_box is None: + return + ch = tab.banner_box.get_first_child() + while ch is not None: + nxt = ch.get_next_sibling() + tab.banner_box.remove(ch) + ch = nxt + + bname = os.path.basename(tplg_path) + ver_tag = f"[{bin_ver.label}] " if (bin_ver and bin_ver.label) else "" + ver_note = "" + if ver_match and ver_match.status in ("git_snapshot", "compatible", "mismatch", "ipc3_unsupported"): + ver_note = f" • {ver_match.source_desc}" + + if in_source_mode and match_res is not None: + vname = match_res.variant.output_name if match_res.variant else "default" + msg = ( + f"Binary '{bname}' {ver_tag}→ matched source {match_res.rel_path} [{vname}] " + f"({match_res.diff.similarity_pct:.0f}% — {match_res.diff.summary}){ver_note}" + ) + elif match_res is not None: + vname = match_res.variant.output_name if match_res.variant else "default" + msg = ( + f"Decoded binary '{bname}' {ver_tag}• Closest source: {match_res.rel_path} [{vname}] " + f"({match_res.diff.similarity_pct:.0f}% — {match_res.diff.summary}){ver_note}" + ) + elif ver_match and ver_match.source_desc: + msg = f"Decoded binary '{bname}' {ver_tag}• {ver_match.source_desc}" + else: + msg = f"Decoded binary '{bname}' {ver_tag}directly (no matching source .conf found in workspace)" + + lbl = Gtk.Label(label=msg, xalign=0.0) + lbl.set_hexpand(True) + lbl.set_wrap(True) + lbl.add_css_class("caption") + tab.banner_box.append(lbl) + + if match_res is not None: + sw_btn = Gtk.Button( + label="View Decompiled Binary" if in_source_mode else f"Open Source ({os.path.basename(match_res.conf_path)})" + ) + sw_btn.add_css_class("flat") + target_mode = "binary" if in_source_mode else "source" + sw_btn.connect( + "clicked", + lambda _b, p=tplg_path, m=target_mode: self.open_tplg_file_in_tab(p, force_mode=m), + ) + tab.banner_box.append(sw_btn) + + exp_btn = Gtk.Button(label="Compile & Export .tplg…") + exp_btn.add_css_class("flat") + exp_btn.connect("clicked", lambda _b: self.action_export_tplg()) + tab.banner_box.append(exp_btn) + tab.banner_box.set_visible(True) + def save_active_tab_to_path(self, target_path: str) -> bool: """Serialize and save the active graph tab's view model (or active text buffer) to target_path.""" active = self.get_active_tab() @@ -2928,7 +3238,7 @@ def save_active_tab_to_path(self, target_path: str) -> bool: return False def action_save(self) -> bool: - """Save the active graph tab in-place, or prompt Save As if untitled.""" + """Save the active graph tab in-place, or prompt Save As if untitled or decoded from binary.""" active = self.get_active_tab() if active is None or active.canvas.vm is None: return False @@ -2938,6 +3248,66 @@ def action_save(self) -> bool: return False return self.save_active_tab_to_path(vm.source_file) + def action_export_tplg(self) -> None: + """Compile active graph tab (full topology) and export as a binary .tplg file.""" + active = self.get_active_tab() + if active is None or active.canvas.vm is None or self.compiler is None: + return + if active.text_editor.is_modified_in_text: + active.text_editor.commit_to_diagram() + vm = active.canvas.vm + dialog = Gtk.FileDialog.new() + dialog.set_title(f"Compile & Export {vm.title} to .tplg…") + if vm.source_tplg: + default_name = os.path.basename(vm.source_tplg) + init_dir = os.path.dirname(vm.source_tplg) + else: + stem = ( + os.path.splitext(os.path.basename(vm.source_file))[0] + if vm.source_file + else re.sub(r"[^A-Za-z0-9_\-]", "_", vm.title) or "custom-topology" + ) + default_name = f"{stem}.tplg" + init_dir = os.path.dirname(vm.source_file) if vm.source_file else (self.workspace.root_dir if self.workspace else "") + dialog.set_initial_name(default_name) + tplg_filter = Gtk.FileFilter() + tplg_filter.set_name("ALSA Topology Binary (*.tplg)") + tplg_filter.add_pattern("*.tplg") + filters = Gio.ListStore.new(Gtk.FileFilter) + filters.append(tplg_filter) + dialog.set_filters(filters) + dialog.set_default_filter(tplg_filter) + if init_dir and os.path.isdir(init_dir): + dialog.set_initial_folder(Gio.File.new_for_path(init_dir)) + dialog.save(self, None, self._on_export_tplg_finished) + + def _on_export_tplg_finished(self, dialog: Gtk.FileDialog, result: Gio.AsyncResult) -> None: + try: + gfile = dialog.save_finish(result) + if not gfile: + return + path = gfile.get_path() + if not path: + return + if not path.lower().endswith(".tplg"): + path += ".tplg" + active = self.get_active_tab() + if active is None or active.canvas.vm is None or self.compiler is None: + return + vm = active.canvas.vm + self.left_panel.show_compile_pane() + res = self.compiler.compile_graph( + vm, + prefer_full_topology=(vm.view_kind == "topology"), + output_tplg_path=path, + ) + self._on_compile_finished(res, False) + if res.success: + vm.source_tplg = os.path.abspath(path) + self.status_lbl.set_text(f"Compiled & exported: {path} ({res.size_bytes} bytes)") + except Exception as exc: + self.append_log(f"Error exporting .tplg: {exc}") + def action_save_as(self) -> None: """Prompt user with Gtk.FileDialog to save the active graph tab to a chosen .conf path.""" active = self.get_active_tab() @@ -2947,10 +3317,15 @@ def action_save_as(self) -> None: dialog = Gtk.FileDialog.new() dialog.set_title(f"Save {vm.title} As…") - default_name = os.path.basename(vm.source_file) if vm.source_file else "custom-topology.conf" + if vm.source_file: + default_name = os.path.basename(vm.source_file) + elif vm.source_tplg: + default_name = os.path.splitext(os.path.basename(vm.source_tplg))[0] + ".conf" + else: + default_name = "custom-topology.conf" dialog.set_initial_name(default_name) - initial_dir = os.path.dirname(vm.source_file) if vm.source_file else "" + initial_dir = os.path.dirname(vm.source_file or vm.source_tplg) if (vm.source_file or vm.source_tplg) else "" if (not initial_dir or not os.path.isdir(initial_dir)) and self.workspace: initial_dir = self.workspace.root_dir if initial_dir and os.path.isdir(initial_dir): @@ -3037,13 +3412,23 @@ def _on_export_pdf_finished(self, dialog: Gtk.FileDialog, result: Gio.AsyncResul pass def action_select_all(self) -> int: - """Select all nodes and containers on the active graph tab.""" + """Select all text (when in Text Editor) or all nodes/containers on the active graph tab.""" + te = self._get_active_text_editor() + if te is not None: + te.select_all() + self.status_lbl.set_text("Selected all text") + return 1 cnt = self.canvas.select_all() self.status_lbl.set_text(f"Selected all ({cnt} items)") return cnt def action_copy(self) -> int: - """Copy selected nodes/containers on the active graph tab to clipboard.""" + """Copy selected text (in Text Editor) or selected nodes/containers to clipboard.""" + te = self._get_active_text_editor() + if te is not None: + te.copy_clipboard() + self.status_lbl.set_text("Copied text to clipboard") + return 1 cnt = self.canvas.copy_selected() if cnt > 0: self.status_lbl.set_text(f"Copied {cnt} item(s) to clipboard") @@ -3052,7 +3437,12 @@ def action_copy(self) -> int: return cnt def action_cut(self) -> int: - """Cut selected nodes/containers on the active graph tab to clipboard.""" + """Cut selected text (in Text Editor) or selected nodes/containers to clipboard.""" + te = self._get_active_text_editor() + if te is not None: + te.cut_clipboard() + self.status_lbl.set_text("Cut text to clipboard") + return 1 cnt = self.canvas.cut_selected() if cnt > 0: self._update_active_tab_header() @@ -3062,7 +3452,12 @@ def action_cut(self) -> int: return cnt def action_paste(self) -> int: - """Paste clipboard nodes/containers into the active graph tab.""" + """Paste clipboard text (in Text Editor) or nodes/containers into active tab.""" + te = self._get_active_text_editor() + if te is not None: + te.paste_clipboard() + self.status_lbl.set_text("Pasted clipboard text") + return 1 cnt = self.canvas.paste_clipboard() if cnt > 0: self._update_active_tab_header() @@ -3072,10 +3467,57 @@ def action_paste(self) -> int: return cnt def action_delete_selected(self) -> None: - """Delete selected nodes, containers, or route edge on the active graph tab.""" + """Delete selected text (in Text Editor) or selected nodes/containers/edge.""" + te = self._get_active_text_editor() + if te is not None: + te.delete_selection() + self._update_active_tab_header() + return self.canvas.delete_selected() self._update_active_tab_header() + def action_find_text(self, with_replace: bool = False) -> None: + """Open Find / Replace bar in the active tab's Text Editor (switching to Text mode if needed).""" + active = self.get_active_tab() + if active is None: + return + if not active.mode_switch_btn.get_active(): + active.mode_switch_btn.set_active(True) + active.text_editor.open_find_bar(with_replace=with_replace) + + def action_goto_line(self) -> None: + """Open Go-to-Line bar in the active tab's Text Editor (switching to Text mode if needed).""" + active = self.get_active_tab() + if active is None: + return + if not active.mode_switch_btn.get_active(): + active.mode_switch_btn.set_active(True) + active.text_editor.open_goto_line_bar() + + def action_zoom_in(self) -> None: + te = self._get_active_text_editor() + if te is not None: + pt = te.zoom_in() + self.status_lbl.set_text(f"Editor font: {te.font_family} {pt}pt") + return + self.canvas.zoom_in() + + def action_zoom_out(self) -> None: + te = self._get_active_text_editor() + if te is not None: + pt = te.zoom_out() + self.status_lbl.set_text(f"Editor font: {te.font_family} {pt}pt") + return + self.canvas.zoom_out() + + def action_reset_zoom(self) -> None: + te = self._get_active_text_editor() + if te is not None: + pt = te.reset_zoom() + self.status_lbl.set_text(f"Editor font reset: {te.font_family} {pt}pt") + return + self.canvas.reset_zoom_1to1() + def _get_ordered_enabled_tb_io_nodes( self, vm_override: Optional[GraphViewModel] = None, @@ -4917,6 +5359,14 @@ def _on_node_attribute_edited(self, config: ConfigNode, key: str, new_val: str) self.status_lbl.set_text(f"Updated attribute '{key}' = '{new_val}'") def _on_undo_clicked(self, _btn: Optional[Gtk.Button]) -> None: + te = self._get_active_text_editor() + if te is not None: + if te.undo(): + debug_log_action("TEXT-UNDO", "Undid text edit") + self._update_undo_redo_buttons() + self._update_active_tab_header() + self.status_lbl.set_text("Undid text edit") + return desc = self.canvas.history.undo_description if self.canvas.undo(): debug_log_action("UNDO", f"Undid '{desc}'") @@ -4926,6 +5376,14 @@ def _on_undo_clicked(self, _btn: Optional[Gtk.Button]) -> None: self.status_lbl.set_text(f"Undid: {desc}") def _on_redo_clicked(self, _btn: Optional[Gtk.Button]) -> None: + te = self._get_active_text_editor() + if te is not None: + if te.redo(): + debug_log_action("TEXT-REDO", "Redid text edit") + self._update_undo_redo_buttons() + self._update_active_tab_header() + self.status_lbl.set_text("Redid text edit") + return desc = self.canvas.history.redo_description if self.canvas.redo(): debug_log_action("REDO", f"Redid '{desc}'") @@ -4935,6 +5393,13 @@ def _on_redo_clicked(self, _btn: Optional[Gtk.Button]) -> None: self.status_lbl.set_text(f"Redid: {desc}") def _update_undo_redo_buttons(self) -> None: + te = self._get_active_text_editor() + if te is not None: + if hasattr(self, "undo_action") and self.undo_action is not None: + self.undo_action.set_enabled(te.can_undo) + if hasattr(self, "redo_action") and self.redo_action is not None: + self.redo_action.set_enabled(te.can_redo) + return h = self.canvas.history if hasattr(self, "undo_action") and self.undo_action is not None: self.undo_action.set_enabled(h.can_undo) @@ -4960,7 +5425,11 @@ def _on_export_conf_clicked(self, _btn: Gtk.Button) -> None: if not self.canvas.vm or not self.compiler: return self.left_panel.show_compile_pane() - res = self.compiler.compile_graph(self.canvas.vm) + vm = self.canvas.vm + res = self.compiler.compile_graph( + vm, + prefer_full_topology=(vm.view_kind == "topology" and bool(vm.source_tplg)), + ) self.append_log(f"Exported compilable .conf to: {res.conf_path}", diagnostics=res.diagnostics) self.status_lbl.set_text(f"Exported: {res.conf_path}") @@ -5009,7 +5478,10 @@ def _on_compile_clicked(self, _btn: Gtk.Button) -> None: self.compile_btn.set_sensitive(False) def worker() -> None: - res = self.compiler.compile_graph(vm) + res = self.compiler.compile_graph( + vm, + prefer_full_topology=(vm.view_kind == "topology" and bool(vm.source_tplg) and not vm.source_file), + ) GLib.idle_add(self._on_compile_finished, res, False) threading.Thread(target=worker, daemon=True).start()