struct2ui 0.6.0__tar.gz → 0.9.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (60) hide show
  1. struct2ui-0.9.0/PKG-INFO +847 -0
  2. struct2ui-0.9.0/README.md +794 -0
  3. {struct2ui-0.6.0 → struct2ui-0.9.0}/src/struct2ui/__init__.py +1 -1
  4. struct2ui-0.9.0/src/struct2ui/compare.py +300 -0
  5. {struct2ui-0.6.0 → struct2ui-0.9.0}/src/struct2ui/editor.py +2965 -2107
  6. {struct2ui-0.6.0 → struct2ui-0.9.0}/src/struct2ui/exporters/bin_emitter.py +69 -10
  7. {struct2ui-0.6.0 → struct2ui-0.9.0}/src/struct2ui/exporters/bin_reader.py +27 -7
  8. {struct2ui-0.6.0 → struct2ui-0.9.0}/src/struct2ui/exporters/c_emitter.py +362 -292
  9. {struct2ui-0.6.0 → struct2ui-0.9.0}/src/struct2ui/exporters/elf_verifier.py +21 -10
  10. {struct2ui-0.6.0 → struct2ui-0.9.0}/src/struct2ui/schema.py +641 -175
  11. struct2ui-0.9.0/src/struct2ui/ui/__init__.py +19 -0
  12. {struct2ui-0.6.0 → struct2ui-0.9.0}/src/struct2ui/ui/renderers.py +225 -333
  13. {struct2ui-0.6.0 → struct2ui-0.9.0}/src/struct2ui/ui/tables.py +189 -69
  14. {struct2ui-0.6.0 → struct2ui-0.9.0}/src/struct2ui/ui/widgets.py +1148 -1155
  15. struct2ui-0.9.0/src/struct2ui.egg-info/PKG-INFO +847 -0
  16. {struct2ui-0.6.0 → struct2ui-0.9.0}/src/struct2ui.egg-info/SOURCES.txt +3 -0
  17. struct2ui-0.9.0/tests/test_bin_emitter.py +168 -0
  18. struct2ui-0.9.0/tests/test_c_emitter.py +299 -0
  19. {struct2ui-0.6.0 → struct2ui-0.9.0}/tests/test_choices.py +23 -1
  20. struct2ui-0.9.0/tests/test_compare.py +539 -0
  21. {struct2ui-0.6.0 → struct2ui-0.9.0}/tests/test_container_verify.py +84 -7
  22. {struct2ui-0.6.0 → struct2ui-0.9.0}/tests/test_editor.py +615 -615
  23. {struct2ui-0.6.0 → struct2ui-0.9.0}/tests/test_elf_verifier.py +6 -5
  24. struct2ui-0.9.0/tests/test_groups.py +569 -0
  25. struct2ui-0.9.0/tests/test_load_report.py +360 -0
  26. {struct2ui-0.6.0 → struct2ui-0.9.0}/tests/test_macro_bounds.py +25 -0
  27. {struct2ui-0.6.0 → struct2ui-0.9.0}/tests/test_save.py +40 -1
  28. {struct2ui-0.6.0 → struct2ui-0.9.0}/tests/test_union.py +111 -69
  29. {struct2ui-0.6.0 → struct2ui-0.9.0}/tests/test_value_readback.py +1 -1
  30. struct2ui-0.6.0/PKG-INFO +0 -547
  31. struct2ui-0.6.0/README.md +0 -494
  32. struct2ui-0.6.0/src/struct2ui/ui/__init__.py +0 -36
  33. struct2ui-0.6.0/src/struct2ui.egg-info/PKG-INFO +0 -547
  34. struct2ui-0.6.0/tests/test_bin_emitter.py +0 -71
  35. struct2ui-0.6.0/tests/test_c_emitter.py +0 -144
  36. struct2ui-0.6.0/tests/test_load_report.py +0 -140
  37. {struct2ui-0.6.0 → struct2ui-0.9.0}/LICENSE +0 -0
  38. {struct2ui-0.6.0 → struct2ui-0.9.0}/pyproject.toml +0 -0
  39. {struct2ui-0.6.0 → struct2ui-0.9.0}/setup.cfg +0 -0
  40. {struct2ui-0.6.0 → struct2ui-0.9.0}/src/struct2ui/exporters/__init__.py +0 -0
  41. {struct2ui-0.6.0 → struct2ui-0.9.0}/src/struct2ui/exporters/c_parser.py +0 -0
  42. {struct2ui-0.6.0 → struct2ui-0.9.0}/src/struct2ui/exporters/json_format.py +0 -0
  43. {struct2ui-0.6.0 → struct2ui-0.9.0}/src/struct2ui/icons/c2j.png +0 -0
  44. {struct2ui-0.6.0 → struct2ui-0.9.0}/src/struct2ui/icons/elf.png +0 -0
  45. {struct2ui-0.6.0 → struct2ui-0.9.0}/src/struct2ui/icons/export_notes_24dp_000000_FILL0_wght400_GRAD0_opsz24.png +0 -0
  46. {struct2ui-0.6.0 → struct2ui-0.9.0}/src/struct2ui/icons/flowchart_24dp_000000_FILL0_wght400_GRAD0_opsz24.png +0 -0
  47. {struct2ui-0.6.0 → struct2ui-0.9.0}/src/struct2ui/icons/refresh_24dp_000000_FILL0_wght400_GRAD0_opsz24.png +0 -0
  48. {struct2ui-0.6.0 → struct2ui-0.9.0}/src/struct2ui/icons/report_24dp_000000_FILL0_wght400_GRAD0_opsz24.png +0 -0
  49. {struct2ui-0.6.0 → struct2ui-0.9.0}/src/struct2ui/icons/save_24dp_000000_FILL0_wght400_GRAD0_opsz24.png +0 -0
  50. {struct2ui-0.6.0 → struct2ui-0.9.0}/src/struct2ui/icons/save_as_24dp_000000_FILL0_wght400_GRAD0_opsz24.png +0 -0
  51. {struct2ui-0.6.0 → struct2ui-0.9.0}/src/struct2ui/icons/settings_24dp_000000_FILL0_wght400_GRAD0_opsz24.png +0 -0
  52. {struct2ui-0.6.0 → struct2ui-0.9.0}/src/struct2ui/icons/widgets_24dp_000000_FILL0_wght400_GRAD0_opsz24.png +0 -0
  53. {struct2ui-0.6.0 → struct2ui-0.9.0}/src/struct2ui.egg-info/dependency_links.txt +0 -0
  54. {struct2ui-0.6.0 → struct2ui-0.9.0}/src/struct2ui.egg-info/requires.txt +0 -0
  55. {struct2ui-0.6.0 → struct2ui-0.9.0}/src/struct2ui.egg-info/top_level.txt +0 -0
  56. {struct2ui-0.6.0 → struct2ui-0.9.0}/tests/test_bin_reader.py +0 -0
  57. {struct2ui-0.6.0 → struct2ui-0.9.0}/tests/test_c_parser.py +0 -0
  58. {struct2ui-0.6.0 → struct2ui-0.9.0}/tests/test_float_precision.py +0 -0
  59. {struct2ui-0.6.0 → struct2ui-0.9.0}/tests/test_int_checkbox.py +0 -0
  60. {struct2ui-0.6.0 → struct2ui-0.9.0}/tests/test_json_format.py +0 -0
@@ -0,0 +1,847 @@
1
+ Metadata-Version: 2.4
2
+ Name: struct2ui
3
+ Version: 0.9.0
4
+ Summary: Render C struct / JSON schema as editable PySide6 UI, export to C/JSON/bin
5
+ Author-email: Jay <huoyj0108@163.com>
6
+ License: MIT License
7
+
8
+ Copyright (c) 2026 Jay
9
+
10
+ Permission is hereby granted, free of charge, to any person obtaining a copy
11
+ of this software and associated documentation files (the "Software"), to deal
12
+ in the Software without restriction, including without limitation the rights
13
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
14
+ copies of the Software, and to permit persons to whom the Software is
15
+ furnished to do so, subject to the following conditions:
16
+
17
+ The above copyright notice and this permission notice shall be included in all
18
+ copies or substantial portions of the Software.
19
+
20
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
21
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
22
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
23
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
24
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
25
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
26
+ SOFTWARE.
27
+
28
+ Keywords: qt,pyside6,gui,c-struct,json-schema,code-generation,parameter-tuning
29
+ Classifier: Development Status :: 3 - Alpha
30
+ Classifier: Intended Audience :: Developers
31
+ Classifier: License :: OSI Approved :: MIT License
32
+ Classifier: Programming Language :: Python :: 3
33
+ Classifier: Programming Language :: Python :: 3.9
34
+ Classifier: Programming Language :: Python :: 3.10
35
+ Classifier: Programming Language :: Python :: 3.11
36
+ Classifier: Programming Language :: Python :: 3.12
37
+ Classifier: Topic :: Software Development :: Code Generators
38
+ Classifier: Topic :: Software Development :: User Interfaces
39
+ Requires-Python: >=3.9
40
+ Description-Content-Type: text/markdown
41
+ License-File: LICENSE
42
+ Requires-Dist: Qt.py>=1.3
43
+ Provides-Extra: pyside6
44
+ Requires-Dist: PySide6>=6.4; extra == "pyside6"
45
+ Provides-Extra: pyqt6
46
+ Requires-Dist: PyQt6>=6.4; extra == "pyqt6"
47
+ Provides-Extra: elf
48
+ Requires-Dist: pyelftools>=0.29; extra == "elf"
49
+ Provides-Extra: dev
50
+ Requires-Dist: pytest>=8; extra == "dev"
51
+ Requires-Dist: pyelftools>=0.29; extra == "dev"
52
+ Dynamic: license-file
53
+
54
+ # struct2ui
55
+
56
+ Render C structs / JSON schemas as an **editable PySide6 UI**, and convert freely between **C / JSON / bin**. Built for algorithm parameter tuning: describe a C interface in JSON, auto-generate a Qt form, edit it, then export back to C source, JSON, or binary.
57
+
58
+ ## Features
59
+
60
+ - **JSON → UI**: describe C structs / enums / arrays with minimal JSON and auto-render Qt widgets (int→QSpinBox, float→QDoubleSpinBox, enum→QComboBox, etc.).
61
+ - **Embeddable**: `StructEditor` is a plain `QWidget` that drops into any PySide6 / PyQt UI.
62
+ - **Multi-format export**: edited results export to C source, JSON, or binary; C source can also be parsed back into a schema.
63
+ - **Read bin back**: `import_bin` loads a raw `.bin` (e.g. read back from the chip) into the UI — the byte-for-byte inverse of the binary export.
64
+ - **Compare with a chip dump**: `compare_with_bin()` diffs the current UI parameters against a `.bin` dumped from the chip — byte-level first, then field-level with float tolerance. Differences show in the Report panel with control highlighting, Apply / Undo, and a per-file-array "Save to file..." export.
65
+ - **Validation**: keyword spell-checking (with “Did you mean X?” hints), semantic audits (`min<=max`, `step>0`), and pipeline cross-validation.
66
+ - **ELF layout check**: optionally verify each module — and the whole pipeline against its SDK container struct — against a compiled ELF's DWARF layout, catching offset/size drift and wrong stage order.
67
+ - **Pipeline note sources**: a pipeline file can pin its own Modules / ELF paths (`note` → `"Modules"` / `"ELF"`) — picking one file switches the whole setup; re-checking a Settings row hands that slot back to the UI-picked path.
68
+ - **Stage groups**: nest stages under a UI group (`"RX": {"EQ": {...}}`) for a two-level strip — one button per group, a second strip for its stages.
69
+ - **Macro-gated stages**: a `defines` table plus per-stage `ifdef` / `ifndef` selects which `#ifdef`-guarded modules the current form has; one pipeline file per macro set.
70
+ - **Field splitting**: one struct spread across adjacent stages with `fields` / `exclude` — each stage shows its own field subset, while export still writes a single complete section.
71
+ - **Qt-binding agnostic**: built on [Qt.py](https://github.com/mottosso/Qt.py) — works with PySide6 / PyQt6 / PySide2 / PyQt5.
72
+
73
+ ## Installation
74
+
75
+ ```bash
76
+ pip install struct2ui
77
+
78
+ # Pick a Qt binding (choose one)
79
+ pip install "struct2ui[pyside6]"
80
+ pip install "struct2ui[pyqt6]"
81
+
82
+ # Enable ELF layout verification (optional)
83
+ pip install "struct2ui[elf]"
84
+ ```
85
+
86
+ > The library itself only depends on `Qt.py`; you must install a Qt binding (PySide6 / PyQt6 / etc.) yourself.
87
+ > ELF verification depends on `pyelftools`, installed via the `[elf]` extra.
88
+
89
+ ## Quick Start
90
+
91
+ ```python
92
+ from Qt import QtWidgets
93
+ from struct2ui import StructEditor
94
+
95
+ app = QtWidgets.QApplication([])
96
+
97
+ editor = StructEditor()
98
+ editor.set_sources(
99
+ flow_file="abc.json", # pipeline definition file
100
+ cfg_dir="cfg_t", # modules dir: *.json holding struct/enum/typedef
101
+ )
102
+ editor.resize(480, 600)
103
+ editor.show()
104
+
105
+ app.exec_()
106
+ ```
107
+
108
+ ## JSON Schema Reference
109
+
110
+ This is the core of the library: you describe your C types in JSON and the UI is
111
+ generated from it. Files live in the **modules directory** (`cfg_dir`), one
112
+ `*.json` per logical group. Each file is a flat object whose keys are **type
113
+ names** (your structs / enums / unions), **`#define` constants** (a plain
114
+ number, see [count expressions](#count-expressions--multi-dimensional-arrays))
115
+ or the reserved key `typedefs`.
116
+
117
+ ### File layout
118
+
119
+ ```jsonc
120
+ {
121
+ // optional free-form metadata (ignored by the loader, allowed anywhere)
122
+ "version": "1.0",
123
+ "description": "audio EQ parameters",
124
+
125
+ // type aliases: map a custom C type to a primitive
126
+ "typedefs": { "gain_t": "int32_t", "freq_t": "float" },
127
+
128
+ // a struct definition
129
+ "eq_cfg_t": {
130
+ "type": "struct",
131
+ "items": [
132
+ { "name": "enabled", "type": "uint8_t", "value": 1 },
133
+ { "name": "gain", "type": "gain_t", "value": 0,
134
+ "min": -12, "max": 12, "step": 1, "unit": "dB",
135
+ "tip": "output gain", "when": { "enabled": 1 } }
136
+ ]
137
+ },
138
+
139
+ // an enum definition
140
+ "mode_t": {
141
+ "type": "enum",
142
+ "items": { "OFF": 0, "LOW": 1, "HIGH": 2 }
143
+ }
144
+ }
145
+ ```
146
+
147
+ ### Top-level blocks
148
+
149
+ | Block type | Keys | Notes |
150
+ | --- | --- | --- |
151
+ | `struct` | `type`, `items` (list of field specs), optional `flatten` | `items` is required. `"flatten": true` marks a fake struct whose fields are loose members of the pipeline's SDK struct (see [C export](#c-export)). |
152
+ | `enum` | `type`, `items` (object `{NAME: value}`) | reads back the enumerator name |
153
+ | `union` | `type`, `items` (list of branch structs) | tagged union; each branch is an inline `struct` selected by its `when` (see below; a legacy `branch` key is accepted but ignored) |
154
+ | `typedefs` | object `{alias: real_type}` | resolved before field building |
155
+
156
+ Free-form metadata keys are allowed and ignored at any level: `version`,
157
+ `description`, `author`, `comment`, `note`.
158
+
159
+ ### Field properties (inside a struct's `items`)
160
+
161
+ Each entry in `items` is a **field spec**. Only the following keys are
162
+ recognized — any other key triggers an "unknown keyword" error (with a
163
+ "Did you mean …?" hint):
164
+
165
+ | Property | Applies to | Description |
166
+ | --- | --- | --- |
167
+ | `name` | all | **Required.** C field name. |
168
+ | `type` | all | **Required.** C type or a `typedefs` alias (e.g. `int32_t`, `float`, `char`, an enum/struct name). |
169
+ | `value` | all | Default value. For arrays, a list (per element) or a scalar (applied to every element). |
170
+ | `count` | arrays | Makes the field an array. Integer, a `#define` name, an expression (`N - 1`), or a list for multi-dim (`[3, 4]`, stored flat as 12). |
171
+ | `min` / `max` | int, float | Numeric bounds. Validated `min <= max`. Drive spin-box / slider / dial ranges. Like `count`, each may be an integer, a `#define` name, or an integer expression of those (e.g. `MAX_GAIN - 1`); it is resolved to a number at load time. |
172
+ | `step` | int, float | Increment, must be `> 0`. |
173
+ | `decimals` | float | Number of fractional digits shown/stored. Non-negative integer (capped at 18). If omitted, it is derived from `step` (e.g. `step: 0.5` → 1 digit); if neither is set, defaults to 3. For `double` fields needing more precision, set `decimals` explicitly (e.g. 15-16). |
174
+ | `unit` | all | Unit suffix shown in the label, e.g. `gain (dB)`. |
175
+ | `tip` | all | Tooltip text. |
176
+ | `choices` | int, float, `char[N]` | Discrete value set rendered as a combo (see below). |
177
+ | `when` | all | Conditional enable/disable (see below). |
178
+ | `widget` | all | Override the auto-picked editor (see table below). |
179
+
180
+ ### `widget` values
181
+
182
+ When omitted, the widget is inferred from `type` (and from `min/max`,
183
+ `choices`). Override it explicitly with `widget`:
184
+
185
+ | `widget` | Valid for | Renders as |
186
+ | --- | --- | --- |
187
+ | `checkbox` | int | Check box (also auto-picked when `min:0, max:1`). |
188
+ | `toggle` | bool/int | Toggle push-button. |
189
+ | `combo` | int, float, `char[N]` | Combo box over `choices` (required, unless the type is an enum). |
190
+ | `slider` | int | Slider with min/max labels (requires `min` & `max`). |
191
+ | `dial` | int | Rotary dial popup (requires `min` & `max`). |
192
+ | `file` | array | Path label + Browse button; array values load from a text file and are emitted into the exported `.bin` / `.c`. |
193
+ | `multiline` | array | Single-line shell that pops up a multi-line editor. |
194
+ | `table` | struct array | Express grid-layout intent (one column per struct member; a union member expands the branch inferred from the pipeline rows into columns — see the union section below). |
195
+ | `tree` | struct array | Tree layout (one item per element); forces a tree even when the automatic rule below would pick a table. |
196
+
197
+ Numeric fields without an explicit `widget` become a `QSpinBox` /
198
+ `QDoubleSpinBox`; scalar arrays become a comma-separated line edit.
199
+ A flat struct array becomes a **table** automatically when it has at least 2
200
+ rows and at most 6 columns, and a tree otherwise. `widget: "table"` forces a
201
+ table for any flat struct array (the column limit does not apply) and
202
+ `widget: "tree"` forces a tree.
203
+
204
+ A `file` array's path may be relative; it resolves against the pipeline
205
+ file's directory first, then the process working directory.
206
+
207
+ ### `choices` (discrete values)
208
+
209
+ A non-enum integer / float / `char[N]` field can be constrained to a fixed set.
210
+ Two forms are accepted:
211
+
212
+ ```jsonc
213
+ "choices": [0, 1, 2, 3] // label = str(value)
214
+ "choices": [{ "Off": 0 }, { "Low": 1 }, { "High": 2 }] // explicit labels
215
+ ```
216
+
217
+ The combo **reads back the underlying value** (not the label), so C / JSON / bin
218
+ export still emits the number (or string for `char[N]`). Audits enforce: each
219
+ value within `[min, max]` when declared, and `value` (the default) must be one
220
+ of the choices.
221
+
222
+ ### `when` (conditional enable/disable)
223
+
224
+ A field can be greyed out unless other fields hold specific values. `when` is an
225
+ object mapping a **sibling field name** to a condition; all entries must
226
+ match (logical AND). A condition takes one of three forms:
227
+
228
+ ```jsonc
229
+ { "enabled": 1 } // equality
230
+ { "mode": ["LOW", "HIGH"] } // membership: value is one of the list
231
+ { "level": { ">=": 0, "<=": 100 } } // operators, AND-ed together
232
+ ```
233
+
234
+ The operators are `in`, `not in`, `=`, `!=`, `>`, `>=`, `<`, `<=`; any other
235
+ key is a load-time error. The dependency name is matched against the dotted
236
+ leaf name in scope. When a dependency is not found, the field stays enabled.
237
+
238
+ ### `union` (tagged union)
239
+
240
+ A `union` block declares overlapping branches, each an inline `struct` in
241
+ `items`. At runtime the tree **shows every branch** whose `when` matches, while
242
+ export (`.bin` / `.c`), `read_bin` and table rendering use the **first**
243
+ matching branch; the union's `.bin` / `.c` size is always the largest branch
244
+ and unmatched exports are zero-padded.
245
+
246
+ ```jsonc
247
+ { "name": "FilterCoeffs", "type": "union", "items": [
248
+ { "name": "raw", "type": "struct", "when": { "type": "IIR_BIQUARD_RAW" },
249
+ "items": [ /* 5 floats */ ] },
250
+ { "name": "design", "type": "struct", "when": { "type": { "!=": "IIR_BIQUARD_RAW" } },
251
+ "items": [ { "name": "f0", "type": "float" }, /* ... */ ] }
252
+ ] }
253
+ ```
254
+
255
+ #### Union inside a table-rendered struct array
256
+
257
+ A struct array containing a union renders as a **table** when the automatic
258
+ rule above holds and all its written rows use the same union branch. The branch
259
+ is **inferred from the pipeline data** — nothing is pinned in the modules file
260
+ (the legacy `branch` key is accepted but silently ignored):
261
+
262
+ - **Uniform rows** → the inferred branch's members expand into columns. Two
263
+ applications can therefore share one `FilterCoeffs` and still each get a
264
+ table: one pipeline writes only `raw` rows, the other only `design` rows.
265
+ - **Mixed rows** (e.g. one `RAW` row next to `PEAKINGEQ` rows) → the array
266
+ falls back to the **tree** layout, where each row keeps its own branch.
267
+ - **No rows written** → the discriminator's schema `value` picks the branch.
268
+ - **Tail rows** (the pipeline wrote fewer rows than `count`) follow the first
269
+ written row: the discriminator continues its value (rule A) and the branch
270
+ members use their defaults.
271
+
272
+ The discriminator combos in the table are filtered down to the values that
273
+ satisfy the inferred branch's `when`, so a mixed-branch row can never be
274
+ created from the UI — there are no greyed-out cells and no zero-padded exports.
275
+ For the same reason, `widget: "table"` on a union-bearing struct array is only
276
+ an *intent*: the data still decides table vs. tree, and the column-count limit
277
+ does not apply when the intent succeeds.
278
+
279
+ ### `count` expressions & multi-dimensional arrays
280
+
281
+ `count` may be an integer, a `#define` constant name, or an integer expression
282
+ of those using `+ - * / % ()` (e.g. `MAX_BAND_NUM - 1`). A constant is declared
283
+ as a plain number at the top level of a module file
284
+ (`"MAX_BAND_NUM": 8`); `min` / `max` / `step` accept the same names. A `count`
285
+ that resolves to nothing is a load-time error. A list makes a
286
+ multi-dimensional array that is **stored flat** to match the C ABI:
287
+
288
+ ```jsonc
289
+ { "name": "matrix", "type": "float", "count": [3, 4] } // 12 contiguous floats, shown as [3][4]
290
+ ```
291
+
292
+ `char[N]` is treated as a C string — whatever `widget` it carries, e.g.
293
+ `widget: "combo"` is a combo over string `choices`. Only `widget: "multiline"`
294
+ or `widget: "file"` turns it into a **byte array** edited as numbers (one
295
+ value per element); the C export then writes each element as a char
296
+ literal when it is printable ASCII and as `0xNN` otherwise:
297
+
298
+ ```jsonc
299
+ { "name": "magic", "type": "char", "count": 4, "widget": "multiline" } // .magic = { 0x10, 'A', 'B', 0x00 }
300
+ ```
301
+
302
+ Any other `widget` on `char[N]` (slider / dial / table / …) is a load-time
303
+ error: those editors fit neither a string nor a byte array.
304
+
305
+ ### Validation
306
+
307
+ Loading runs four layers of checks, surfaced in the **load report** panel:
308
+
309
+ - **Keyword spelling** — unknown keys report "Did you mean `tip`?" style hints,
310
+ at every nesting level (inline struct members, union branches).
311
+ - **Semantic audits** — `min <= max`, `step > 0`, `count > 0`, choices within
312
+ bounds, default is one of the choices. Also errors: a `count` that cannot be
313
+ resolved, an unknown `when` operator, and a `widget` that is unknown or lacks
314
+ what it needs (`slider` / `dial` without `min` & `max`, `combo` without
315
+ `choices`). Inline struct members are audited like top-level ones.
316
+ - **Pipeline cross-validation** — values in the pipeline file are checked
317
+ against the schema (range, choices, enum membership).
318
+ - **Duplicate type definitions** — the same struct / enum / union defined in
319
+ two module files is an error; the first definition found wins and the
320
+ duplicate is reported.
321
+
322
+ ## Pipeline File
323
+
324
+ While the **modules directory** (`cfg_dir`) defines your *types*, the
325
+ **pipeline file** (`flow_file`) describes one concrete *instance*: which module
326
+ stages are present, in what order, and their edited values. It is a single JSON
327
+ object with **one top-level group key** (any name you like, e.g. the product /
328
+ tuning name) whose value is the group body:
329
+
330
+ ```jsonc
331
+ {
332
+ "Speech Tuning": {
333
+ "note": {
334
+ "Modules": "cfg_t", // optional sources
335
+ "ELF": "../elf/fw.elf",
336
+ "C Struct": "SpeechConfig", // optional: C export + layout check
337
+ "C Variable": "speech_cfg_default",
338
+ "C Qualifier": "const"
339
+ },
340
+ "flow": ["RX NS", "RX DRC", "RX EQ"], // stage order, optional
341
+
342
+ "RX NS": { "type": "SpeechNs2FloatConfig", "items": { /* values */ } },
343
+ "RX DRC": { "type": "MultiCompexpConfig" }, // 'items' may be omitted
344
+ "RX EQ": { "type": "EqConfig", "items": { /* values */ } }
345
+ }
346
+ }
347
+ ```
348
+
349
+ ### Group-level keys
350
+
351
+ | Key | Required | Notes |
352
+ | --- | --- | --- |
353
+ | `flow` | no | Ordered list of stage names. The flow buttons and the export order follow it. **Omit it and the stages run in the order they appear in the JSON.** When present, every listed name must have a stage block; defined stages missing from `flow` are a warning. |
354
+ | `container` | no | **Deprecated — will be removed.** Name of the SDK struct that holds all modules. Write it as `"C Struct"` in `note` instead; until then it is still read when the note has no `"C Struct"`. |
355
+ | `defines` | no | Macro table (`name → true/false`) selecting which `#ifdef`-gated stages the current form has — see [Macro-gated stages](#macro-gated-stages-ifdef-variants). |
356
+ | `note` | no | Metadata dict. These keys are read by the tool: `"Modules"` / `"ELF"` pin the pipeline's companion sources (see [Source overrides via `note`](#source-overrides-via-note)); `"C Struct"` / `"C Variable"` / `"C Qualifier"` name the C export (see [C export](#c-export)); `"C Group Prefix"` controls member names of grouped stages (see [Stage groups](#stage-groups)). A key that looks like a misspelt one of these (`"C Varible"`) gets a "Did you mean" warning; any other key is ignored. |
357
+ | *stage name* | — | Any other key is a **stage block** (or a **stage group**, see below); its name is the label shown on the flow button. |
358
+
359
+ All keys are **lowercase and case-sensitive** — write `flow`, not `Flow`. A
360
+ mistyped key (`Flow`, `flwo`, …) is reported with a "Did you mean `flow`?" hint.
361
+ Free-form metadata keys (`version`, `description`, `author`, `comment`) are
362
+ allowed and ignored.
363
+
364
+ ### Source overrides via `note`
365
+
366
+ A pipeline file can pin its own companion sources, so picking **one file
367
+ switches the whole tuning setup** — no need to re-pick the Modules directory
368
+ and ELF by hand:
369
+
370
+ ```jsonc
371
+ "note": {
372
+ "Send Format": "Speech Tuning", // free-form fields stay ignored
373
+ "Modules": "cfg_t", // modules directory
374
+ "ELF": "../elf/best1702_ibrt.elf" // ELF for layout verification
375
+ }
376
+ ```
377
+
378
+ Both keys are optional and take absolute or **pipeline-file-relative** paths.
379
+ Selecting the pipeline applies them in Settings:
380
+
381
+ - A row whose path the note provides is **unchecked** — exactly as if the user
382
+ had — and the note's path feeds the slot. The UI-picked path is kept and
383
+ still displayed, so re-checking the row switches back to it at any time.
384
+ - From then on the checkbox is the only switch: a **checked row forces the
385
+ UI-picked path** no matter what the note says; an unchecked row takes the
386
+ note's path. One exception: values passed explicitly to the same
387
+ `set_sources()` call win over the note — a path argument (`cfg_dir=` /
388
+ `elf_file=`) checks its row, and `modules_enabled=` / `elf_enabled=` are
389
+ applied last.
390
+ - Neither side providing Modules is a load error (with a hint to enable the
391
+ Settings row or add a note path); neither side providing an ELF simply
392
+ skips layout verification.
393
+ - Reload re-reads the note from disk, so editing it takes effect without
394
+ re-picking the pipeline file — but a reload never flips a checkbox.
395
+
396
+ ### Stage block
397
+
398
+ | Key | Required | Notes |
399
+ | --- | --- | --- |
400
+ | `type` | yes | A struct / union type name defined in the modules directory. |
401
+ | `items` | no | The edited values, keyed by field name. **Omitting `items` means "all defaults"** — the stage renders from the type's declared defaults. |
402
+ | `member` | no | The name of the container member this stage is exported and checked as (defaults to the stage label, see [C export](#c-export)). |
403
+ | `ifdef` / `ifndef` | no | Macro name (or list) gating the stage on the `defines` table — see [Macro-gated stages](#macro-gated-stages-ifdef-variants). |
404
+ | `fields` / `exclude` | no | Split this stage's struct across adjacent stages, each showing a subset of its direct fields — see [Field splitting](#field-splitting-one-struct-across-stages). |
405
+
406
+ ### Stage groups
407
+
408
+ Stages can be grouped one level deep for display, e.g. TX / RX chains that
409
+ each have an EQ and a DRC. A group is a block whose children are stage blocks
410
+ (no `type` / `items` of its own); it may carry its own optional `flow`:
411
+
412
+ ```jsonc
413
+ {
414
+ "Speech Tuning": {
415
+ "note": { "Modules": "cfg_t" },
416
+ "flow": ["AEC", "TX", "RX"], // top-level order: stages and groups
417
+ "AEC": { "type": "AecConfig" }, // an ungrouped stage
418
+ "TX": {
419
+ "flow": ["EQ", "DRC"], // order inside the group, optional
420
+ "EQ": { "type": "EqConfig" },
421
+ "DRC": { "type": "MultiCompexpConfig" }
422
+ },
423
+ "RX": {
424
+ "EQ": { "type": "EqConfig" },
425
+ "DRC": { "type": "MultiCompexpConfig" }
426
+ }
427
+ }
428
+ }
429
+ ```
430
+
431
+ - **UI**: the flow strip shows top-level stages and groups (`AEC | TX | RX`);
432
+ selecting a group shows its stages in a second strip (a second column when
433
+ the strip is vertical). Clicking a group returns to the stage last opened in
434
+ it. A group button is shown even when it is the only group.
435
+ - **Labels**: a grouped stage is identified by its full label `TX/EQ` — in the
436
+ Report panel, error messages and compare results. Stage names only need to
437
+ be unique within their group.
438
+ - **.bin / import / compare**: unchanged — the image is every stage in expanded
439
+ flow order (`AEC, TX/EQ, TX/DRC, RX/EQ, RX/DRC`), exactly as if the pipeline
440
+ were flat. The container layout check also uses this expanded order.
441
+ - **.c export**: member names are `TX_EQ`, `RX_EQ`, … by default (see
442
+ [C export](#c-export)). Set `"C Group Prefix": false` in `note` to drop the
443
+ group (`EQ`); a resulting name collision (e.g. `TX/EQ` and `RX/EQ` both
444
+ become `EQ`) fails the export with an error naming both stages.
445
+ - **Save** writes the document back with its nesting intact.
446
+ - **Rules** (load errors): groups nest only one level; `/` is not allowed in
447
+ stage or group names once a pipeline uses groups; `container` is only
448
+ allowed at the top level.
449
+
450
+ ### Macro-gated stages (`#ifdef` variants)
451
+
452
+ The SDK header often guards members with compile macros — some projects build
453
+ with them on, others off. A pipeline can describe **all** forms at once and
454
+ pick one with a macro table:
455
+
456
+ ```jsonc
457
+ {
458
+ "ANC Tuning": {
459
+ "defines": { "ADAPTIVE_FF_IIR": true, "SERIES_FIR": false },
460
+ "flow": ["A", "IIR", "FIR"],
461
+ "A": { "type": "AncCommonConfig" },
462
+ "IIR": { "type": "AdaFfIirConfig", "ifdef": "ADAPTIVE_FF_IIR" },
463
+ "FIR": { "type": "FirLmsConfig",
464
+ "ifdef": "ADAPTIVE_FF_IIR", "ifndef": "SERIES_FIR" }
465
+ }
466
+ }
467
+ ```
468
+
469
+ - `defines` maps macro names to `true` / `false` — the form the firmware was
470
+ built with. A stage is present when all its `ifdef` macros are `true` and
471
+ all its `ifndef` macros are `false`; it is dropped from the whole pipeline
472
+ at once (no button, no `.bin` / `.c` output, no ELF check, no flow warning),
473
+ exactly like the member the compiler left out of that build.
474
+ - `ifdef` / `ifndef` take one macro name or a list (all must hold; the two
475
+ keys AND together). An undeclared macro name is an error, not a silent
476
+ drop; a non-bool `defines` value is an error too.
477
+ - Switching form = edit `defines` in the pipeline file and Reload. The `.bin`
478
+ layout of each form matches that build of the SDK struct (fewer members,
479
+ shifted offsets), so one pipeline file per macro set is the intended unit
480
+ of reuse.
481
+
482
+ ### Field splitting (one struct across stages)
483
+
484
+ A parameter page is a *logical* group; a struct's memory is a *physical* run
485
+ of fields. When the two disagree — `debug_en` sits at the head of the
486
+ struct, the counters it governs at the tail, and both belong on one "Debug"
487
+ page — split the struct across several **adjacent stages**, each narrowing
488
+ its view of the same type:
489
+
490
+ ```jsonc
491
+ {
492
+ "Speech Tuning": {
493
+ "note": { "Modules": "cfg_t" },
494
+ "flow": ["Main", "Debug", "Meter"],
495
+ "Main": { "type": "TuningConfig", "exclude": ["debug_en", "mc_max_cnt"] },
496
+ "Debug": { "type": "TuningConfig", "fields": ["debug_en", "mc_max_cnt"] },
497
+ "Meter": { "type": "MeterConfig" }
498
+ }
499
+ }
500
+ ```
501
+
502
+ - `fields` shows only the listed **direct** members of the stage's type;
503
+ `exclude` shows all but them. The two keys are mutually exclusive. A
504
+ single narrowed stage is fine too — the fields it hides simply export
505
+ with their defaults.
506
+ - The UI keeps each stage as its own button/page showing only its view
507
+ (nested structs/arrays inside a kept field are rendered whole).
508
+ - **Export merges the run into ONE section** at the first stage's position:
509
+ the `.bin` layout, the C member and the ELF container check all see a
510
+ single complete struct, as if one stage owned it. The members' values are
511
+ unioned; import and compare-apply write decoded values back into each
512
+ member's own view.
513
+ - **Rules** (load errors): split stages of one type must sit next to each
514
+ other in the flow — they merge into one section, and non-adjacent split
515
+ stages of the same type are flagged instead of silently exporting two
516
+ structs; views must not overlap (a field belongs to one view); a name in
517
+ `fields` / `exclude` must be a direct member of the type; `items` keys
518
+ must lie inside the stage's own view — a value outside it would be
519
+ dropped the first time the UI captures that page, so it is refused up
520
+ front.
521
+ - A field **no stage in the run shows** only warns: it still exports, with
522
+ its default value.
523
+
524
+ ### C export
525
+
526
+ The whole pipeline is exported as **one struct variable** — one instance of
527
+ the SDK struct that holds all modules:
528
+
529
+ ```c
530
+ /* Auto-generated by struct2ui. Do not edit by hand. */
531
+ #include <stdbool.h>
532
+ #include <stdint.h>
533
+
534
+ const SpeechConfig speech_cfg_default = {
535
+ .tx_eq = {
536
+ .bypass = false,
537
+ ...
538
+ },
539
+ .rx_eq = {
540
+ ...
541
+ }
542
+ };
543
+ ```
544
+
545
+ | `note` key | Notes |
546
+ | --- | --- |
547
+ | `"C Struct"` | The SDK struct type. Also enables the [container layout check](#container-layout-check). |
548
+ | `"C Variable"` | The variable name. |
549
+ | `"C Qualifier"` | Free text placed before the type, verbatim: `const`, `WEAK`, `static const`, … |
550
+
551
+ - **Member names**: a stage's `member` if it has one, else its label
552
+ (`RX/EQ` → `RX_EQ`). A name collision fails the export with an error naming
553
+ both stages.
554
+ - **Missing keys**: a missing `"C Struct"` or `"C Variable"` is left blank in
555
+ the output behind a `/* TODO: set ... in the pipeline note */` comment (the
556
+ braces stay valid C) and gets a warning in the Report.
557
+ - **Loose variables** (`"flatten": true`): SDK structs often hold plain
558
+ variables between the module structs. Describe them as a module whose struct
559
+ is marked `"flatten": true`; its fields are then emitted as container
560
+ members directly, and the fake struct disappears:
561
+
562
+ ```jsonc
563
+ // cfg_t/fir_lms_misc.json
564
+ { "ANC_FF_FIR_LMS_Misc": {
565
+ "type": "struct", "flatten": true,
566
+ "items": [
567
+ { "name": "bypass", "type": "uint32_t", "value": 0 },
568
+ { "name": "gain", "type": "float", "value": 0.0 }
569
+ ] } }
570
+ ```
571
+
572
+ ```c
573
+ WEAK ANC_FF_FIR_LMS_CFG_T fir_lms_cfg = {
574
+ .bypass = 0,
575
+ .gain = 0.0,
576
+ .iir_cfg = { ... } // the next stage
577
+ };
578
+ ```
579
+
580
+ This also solves "an array of structs sits directly in the container"
581
+ (`tx_2mic_ns4_preaf[6]`): wrap the array in a fake struct with that single
582
+ member and mark it `flatten`.
583
+ - `member` has no effect on a flatten stage; its fields keep their own
584
+ names (the Report warns).
585
+ - A flatten stage needs `"C Struct"` (or `container`): the C export fails
586
+ without one.
587
+ - .bin: the whole pipeline is laid out as one C struct. Every member
588
+ (stage) starts on its own alignment, a flatten stage's loose fields get
589
+ no tail padding, and the image is `sizeof` of the struct. The container
590
+ layout check compares the loose fields one by one; the per-module check
591
+ skips the fake struct.
592
+
593
+ ### Container layout check
594
+
595
+ When `"C Struct"` (or the deprecated `container`) names an SDK struct and an
596
+ ELF is loaded, the whole pipeline is laid out in `flow` order — as if each
597
+ stage were a member of that container — and compared member-by-member
598
+ against the struct's DWARF layout (member names, offset, size, total size).
599
+ This catches stages in the **wrong order**: if the modules are all correct
600
+ but reordered, you get a single "module order is wrong" error naming the
601
+ expected order, instead of a pile of misleading offset mismatches.
602
+
603
+ ## Embedding into an Existing UI
604
+
605
+ `StructEditor` is a regular `QWidget`; just put it into a layout:
606
+
607
+ ```python
608
+ from Qt import QtWidgets
609
+ from struct2ui import StructEditor
610
+
611
+ class MyWindow(QtWidgets.QMainWindow):
612
+ def __init__(self):
613
+ super().__init__()
614
+ editor = StructEditor()
615
+ editor.set_sources(flow_file="abc.json", cfg_dir="cfg_t")
616
+ self.setCentralWidget(editor)
617
+ ```
618
+
619
+ `StructEditor` takes no source paths at construction time and keeps no
620
+ persistent state of its own. Point it at its sources after creating it with
621
+ `set_sources()` (or let the user pick them at runtime via Settings). If you
622
+ want to remember the last-used paths across runs, store them in the host app
623
+ and call `set_sources()` again at startup.
624
+
625
+ ### Constructor Parameters
626
+
627
+ | Parameter | Description |
628
+ | --- | --- |
629
+ | `parent` | Qt parent object, defaults to `None` |
630
+ | `appearance` | Button appearance overrides, `{key: {'mode': ..., 'icon': ..., 'text': ...}}` |
631
+ | `custom_button_position` | Where `add_custom_button()` drops buttons relative to the built-ins: `'end'` (after, default) or `'start'` (before / far left) |
632
+
633
+ ### Setting Sources
634
+
635
+ Source paths are configured after construction, not passed to the constructor.
636
+ Omitting an argument leaves that slot untouched.
637
+
638
+ ```python
639
+ editor.set_sources(
640
+ flow_file="abc.json", # pipeline definition file
641
+ cfg_dir="cfg_t", # modules dir: *.json with struct/enum/typedef defs
642
+ elf_file="fw.elf", # optional ELF for .bin layout verification
643
+ )
644
+ ```
645
+
646
+ | `set_sources` argument | Description |
647
+ | --- | --- |
648
+ | `flow_file` | Path to the pipeline JSON file (pipeline definition) |
649
+ | `cfg_dir` | Modules directory holding `*.json` (struct / enum / typedef definitions); setting it checks the Modules row |
650
+ | `modules_enabled` | Override the Modules row's checkbox state, independent of whether a path is set |
651
+ | `elf_file` | Path to an ELF for `.bin` layout verification; setting it enables verification (toggle later via the Settings checkbox, which keeps the path) |
652
+ | `elf_enabled` | Override whether ELF verification runs, independent of whether a path is set |
653
+ | `reload` | Rebuild schema / flow / UI from the new sources, defaults to `True` |
654
+ | `async_load` | Run that reload on a background thread (defaults to `False`). See [Async Loading](#async-loading) |
655
+
656
+ Explicitly passed paths and checkbox states are applied after the pipeline
657
+ note's overrides, so they always win: a note can only uncheck a row that this
658
+ call left untouched. See [Source overrides via `note`](#source-overrides-via-note)
659
+ for the full priority rules.
660
+
661
+ Toolbar orientation is set with `set_flow_orientation('horizontal' | 'vertical')`.
662
+
663
+ #### Async Loading
664
+
665
+ Parsing the modules, validating the pipeline and (optionally) reading the ELF
666
+ all happen during the reload. For large module sets or ELFs this can take a
667
+ while, and by default it runs synchronously — `set_sources()` blocks until the
668
+ editor is fully built, which is what programmatic callers and tests want.
669
+
670
+ A GUI host can avoid the startup freeze by passing `async_load=True` *after*
671
+ `show()`: the window appears immediately and shows a `Loading...` placeholder
672
+ while the heavy parsing runs on a worker thread, then swaps in the real content
673
+ when it is ready. Reloads triggered while one is already running supersede the
674
+ older one.
675
+
676
+ ```python
677
+ editor.show()
678
+ editor.set_sources(
679
+ flow_file="abc.json",
680
+ cfg_dir="cfg_t",
681
+ elf_file="fw.elf",
682
+ async_load=True, # parse off the GUI thread; window stays responsive
683
+ )
684
+ ```
685
+
686
+ ## Custom Toolbar Buttons
687
+
688
+ Host applications can add their own buttons to the top path bar via
689
+ `add_custom_button()`. All custom buttons form a single group, separated from
690
+ the built-in buttons by a divider that is added automatically — you only choose
691
+ which side they sit on (once, via the `custom_button_position` constructor arg).
692
+
693
+ ```python
694
+ editor = StructEditor(custom_button_position="end")
695
+ editor.set_sources(flow_file="abc.json", cfg_dir="cfg_t")
696
+
697
+ def on_send():
698
+ print(editor.current_values())
699
+
700
+ btn = editor.add_custom_button(
701
+ "Send", # tooltip / accessible label (shown when no icon)
702
+ on_send, # callable invoked on click (no arguments)
703
+ icon="icons/send.png", # optional; falls back to text when missing
704
+ checkable=False, # optional; make the button toggleable
705
+ )
706
+ # `btn` is the created QPushButton, returned so you can tweak it further.
707
+ ```
708
+
709
+ | Parameter | Description |
710
+ | --- | --- |
711
+ | `text` | Tooltip / accessible label, also shown when no icon is given. **Required.** |
712
+ | `on_click` | Callable invoked on click, takes no arguments. **Required.** |
713
+ | `icon` | Path to an icon file; falls back to `text` when the path is missing/empty. |
714
+ | `checkable` | Make the button toggleable, defaults to `False`. |
715
+
716
+ Returns the created `QPushButton`.
717
+
718
+ ## Compare with a Chip Dump
719
+
720
+ `compare_with_bin()` checks the current UI parameters against a `.bin`
721
+ dumped live from the chip. The host application owns the chip communication
722
+ and the dump file; struct2ui only needs its path:
723
+
724
+ ```python
725
+ def on_compare():
726
+ dump = r"D:\logs\speech_cfg_dump.bin"
727
+ ad_read_chip_to_bin(dump) # host side: read chip, save bin
728
+ editor.compare_with_bin(dump) # result goes to the Report panel
729
+
730
+ btn = editor.add_custom_button("Compare", on_compare)
731
+ ```
732
+
733
+ The comparison runs two levels:
734
+
735
+ 1. **Byte level** — the pipeline is exported in memory and compared with the
736
+ dump; equal length + equal bytes → *identical*.
737
+ 2. **Field level** — equal length but different bytes: the dump is parsed
738
+ with `read_bin` and diffed leaf-by-leaf (floats compare within tolerance),
739
+ so encoding/padding-only differences report as *semantically identical*
740
+ while real differences show as a table (path, UI value, chip value).
741
+
742
+ Results land in the Report panel: the controls behind each difference are
743
+ highlighted with an amber glow, **Apply to UI** overwrites the form with the
744
+ chip values, and **Undo** restores the pre-apply snapshot (snapshot-based,
745
+ not bin-based — a bin round-trip would lose float precision and file paths).
746
+ File-backed arrays (`widget: "file"`) diff as a whole — one aggregated row
747
+ (`n/N elements differ`) whose **Save to file...** button writes the
748
+ chip-side values to a file of your choice: overwrite the file currently in
749
+ use (re-compare shows identical) or save a new one and re-point the UI at
750
+ it. Apply never overwrites files or the UI file paths. A file-backed array
751
+ with no file selected is not compared: when the bins differ and everything
752
+ else is equal, the report says **Match not confirmed** (naming the skipped
753
+ arrays) instead of claiming a match — select the file(s) and compare again.
754
+
755
+ `compare_with_bin` returns `True` when the comparison completed (identical /
756
+ semantically identical / match not confirmed / differences shown) and `False`
757
+ on failure (no pipeline loaded, unreadable dump, length mismatch, broken
758
+ file-array source) — failures are reported in the Report panel, never raised.
759
+
760
+ ## Programmatic API
761
+
762
+ Beyond the UI, `StructEditor` exposes methods to read state and drive exports
763
+ from code (e.g. wired to a custom button):
764
+
765
+ | Method | Description |
766
+ | --- | --- |
767
+ | `set_sources(flow_file=None, cfg_dir=None, modules_enabled=None, elf_file=None, elf_enabled=None, reload=True, async_load=False)` | Point the editor at its source files after construction. See [Setting Sources](#setting-sources). |
768
+ | `set_flow_orientation(orientation)` | Switch the flow-button strip between `'horizontal'` (top, default) and `'vertical'` (left). Rebuilds the strip and keeps the active stage selected. |
769
+ | `show_section(label) -> None` | Open the stage/section named `label` in the content area (the same as clicking its flow button). Paints the error panel instead when that stage has pipeline errors; clears the content when the label is unknown. |
770
+ | `current_values() -> dict` | Live editor values of the active section, keyed by field name (empty dict when no parameter section is shown). |
771
+ | `current_paths() -> dict` | Current `{'modules', 'pipeline', 'elf'}` file paths; an empty string means that slot is unset. |
772
+ | `add_custom_button(text, on_click, icon=None, checkable=False) -> QPushButton` | Add a host button to the top path bar. See [Custom Toolbar Buttons](#custom-toolbar-buttons). |
773
+ | `export_bin(path, show_dialogs=False) -> bool` | Write the current pipeline to a `.bin` at `path` — the programmatic equivalent of clicking Export → Binary. Returns `True` when there are no ELF layout errors (or ELF verification is off), `False` otherwise. |
774
+ | `import_bin(source, show_dialogs=False) -> bool` | Load a raw `.bin` image (e.g. read back from the chip) into the UI — the inverse of `export_bin`. `source` is a path or `bytes`. The image length must match the pipeline layout **exactly**; on any mismatch the image is rejected and the UI is left unchanged. On success it overwrites every stage's values and re-renders. |
775
+ | `compare_with_bin(dump_path) -> bool` | Diff the current UI parameters against a chip-dump `.bin` (byte level first, then per-field with float tolerance). Differences, Apply / Undo and the file-array "Save to file..." export all appear in the Report panel. Returns `True` when the comparison completed, `False` on failure (reported, not raised). See [Compare with a Chip Dump](#compare-with-a-chip-dump). |
776
+
777
+ Read-only state attributes hosts save/restore alongside the paths (there are
778
+ no public setters; change them via `set_sources()` / `set_flow_orientation()`
779
+ / the Settings panel): `elf_enabled` (bool), `modules_enabled` (bool),
780
+ `flow_orientation` (`'horizontal'` / `'vertical'`).
781
+
782
+ `export_bin` verifies the ELF layout first when an ELF is selected and enabled (the file is
783
+ still written, matching the UI flow). With `show_dialogs=True` it pops the same
784
+ success / ELF-mismatch / failure dialogs the UI shows; with the default
785
+ `show_dialogs=False` no dialogs appear and render/write failures are raised as
786
+ exceptions for the caller to handle.
787
+
788
+ ```python
789
+ paths = editor.current_paths() # {'modules': ..., 'pipeline': ..., 'elf': ...}
790
+ name = paths['pipeline'] # derive an output name from the pipeline
791
+ ok = editor.export_bin("out/speech.bin") # True when ELF layout is clean
792
+ ```
793
+
794
+ `import_bin` is the reverse trip: feed it a `.bin` the chip sent back and the UI
795
+ is repopulated from it. Because the image is a byte-for-byte C-ABI layout, its
796
+ length must match the pipeline layout exactly — a short or long image is
797
+ rejected wholesale so a stale/mismatched dump can never partially corrupt the
798
+ form.
799
+
800
+ ```python
801
+ ok = editor.import_bin("out/speech.bin") # True when the image was applied
802
+ ```
803
+
804
+ ## Export API
805
+
806
+ The low-level export functions can be used standalone, without any UI:
807
+
808
+ ```python
809
+ from struct2ui.schema import SchemaRegistry
810
+ from struct2ui.exporters import (
811
+ emit_c, # sections + registry -> C source string
812
+ dumps_json, # -> JSON string
813
+ emit_bin, # -> binary bytes
814
+ read_bin, # binary bytes -> values dict (inverse of emit_bin)
815
+ BinReadError, # raised by read_bin on a rejected image
816
+ merge_abi, # merge ABI info
817
+ verify_sections, # verify each section's layout against an ELF
818
+ verify_container_layout, # verify the whole pipeline container against an ELF
819
+ parse_c_source, # C source -> parse result
820
+ build_schema_dict, # parse result -> modules-file style dict
821
+ )
822
+ ```
823
+
824
+ ## Architecture
825
+
826
+ | Layer | Module | Responsibility |
827
+ | --- | --- | --- |
828
+ | Schema (pure data, no Qt) | `struct2ui.schema` | Parse `*.json` into a Field tree; spell-checking, semantic audits, pipeline cross-validation |
829
+ | UI rendering | `struct2ui.ui` | `WidgetFactory`, `TreeRenderer`, array tables, `when` conditional binding |
830
+ | Export | `struct2ui.exporters` | C / JSON / bin export, C source reverse parsing, ELF verification |
831
+ | Top-level widget | `struct2ui.StructEditor` | Action toolbar / content area; Settings panel for source paths; load report panel |
832
+
833
+ ## Development
834
+
835
+ ```bash
836
+ pip install -e ".[dev,pyside6]" --no-build-isolation # [dev] ships no Qt binding
837
+ python -m pytest
838
+ ```
839
+
840
+ Tests live under `tests/` and drive real Qt widgets headlessly on the offscreen platform.
841
+ ELF layout tests use the small firmware fixture `tests/data/test_fw.elf` (built from the adjacent `test_fw.c`) and are skipped when `pyelftools` is missing.
842
+
843
+ Examples live under `examples/`. `examples/main.py` is a demo app (custom toolbar buttons, bin import/export, chip-dump compare) wired to `examples/speech`. `examples/abc` is the guided tour — every stage's `comment` explains the feature it shows, and each has a matching `.c` file next to its JSON; `param` and `test` are further real-world pipelines. To browse one, point `StructEditor.set_sources()` at its JSON and `cfg_t` folder.
844
+
845
+ ## License
846
+
847
+ [MIT](LICENSE) © Jay