struct2ui 0.4.3__tar.gz → 0.5.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 (51) hide show
  1. {struct2ui-0.4.3/src/struct2ui.egg-info → struct2ui-0.5.0}/PKG-INFO +98 -5
  2. {struct2ui-0.4.3 → struct2ui-0.5.0}/README.md +96 -3
  3. {struct2ui-0.4.3 → struct2ui-0.5.0}/pyproject.toml +5 -2
  4. {struct2ui-0.4.3 → struct2ui-0.5.0}/src/struct2ui/__init__.py +1 -1
  5. {struct2ui-0.4.3 → struct2ui-0.5.0}/src/struct2ui/editor.py +119 -10
  6. {struct2ui-0.4.3 → struct2ui-0.5.0}/src/struct2ui/exporters/__init__.py +3 -1
  7. {struct2ui-0.4.3 → struct2ui-0.5.0}/src/struct2ui/exporters/bin_emitter.py +56 -4
  8. struct2ui-0.5.0/src/struct2ui/exporters/bin_reader.py +180 -0
  9. {struct2ui-0.4.3 → struct2ui-0.5.0}/src/struct2ui/exporters/c_emitter.py +65 -5
  10. struct2ui-0.5.0/src/struct2ui/exporters/c_parser.py +466 -0
  11. {struct2ui-0.4.3 → struct2ui-0.5.0}/src/struct2ui/exporters/elf_verifier.py +201 -2
  12. {struct2ui-0.4.3 → struct2ui-0.5.0}/src/struct2ui/exporters/json_format.py +28 -1
  13. {struct2ui-0.4.3 → struct2ui-0.5.0}/src/struct2ui/schema.py +467 -30
  14. {struct2ui-0.4.3 → struct2ui-0.5.0}/src/struct2ui/ui/renderers.py +41 -1
  15. {struct2ui-0.4.3 → struct2ui-0.5.0}/src/struct2ui/ui/tables.py +107 -18
  16. {struct2ui-0.4.3 → struct2ui-0.5.0}/src/struct2ui/ui/widgets.py +172 -23
  17. {struct2ui-0.4.3 → struct2ui-0.5.0/src/struct2ui.egg-info}/PKG-INFO +98 -5
  18. {struct2ui-0.4.3 → struct2ui-0.5.0}/src/struct2ui.egg-info/SOURCES.txt +5 -0
  19. struct2ui-0.5.0/tests/test_bin_reader.py +145 -0
  20. {struct2ui-0.4.3 → struct2ui-0.5.0}/tests/test_c_emitter.py +22 -0
  21. {struct2ui-0.4.3 → struct2ui-0.5.0}/tests/test_c_parser.py +70 -0
  22. struct2ui-0.5.0/tests/test_container_verify.py +132 -0
  23. {struct2ui-0.4.3 → struct2ui-0.5.0}/tests/test_editor.py +28 -3
  24. {struct2ui-0.4.3 → struct2ui-0.5.0}/tests/test_float_precision.py +12 -6
  25. {struct2ui-0.4.3 → struct2ui-0.5.0}/tests/test_int_checkbox.py +14 -1
  26. {struct2ui-0.4.3 → struct2ui-0.5.0}/tests/test_json_format.py +15 -0
  27. {struct2ui-0.4.3 → struct2ui-0.5.0}/tests/test_load_report.py +19 -1
  28. struct2ui-0.5.0/tests/test_macro_bounds.py +58 -0
  29. {struct2ui-0.4.3 → struct2ui-0.5.0}/tests/test_save.py +9 -5
  30. struct2ui-0.5.0/tests/test_union.py +528 -0
  31. struct2ui-0.4.3/src/struct2ui/exporters/c_parser.py +0 -204
  32. {struct2ui-0.4.3 → struct2ui-0.5.0}/LICENSE +0 -0
  33. {struct2ui-0.4.3 → struct2ui-0.5.0}/setup.cfg +0 -0
  34. {struct2ui-0.4.3 → struct2ui-0.5.0}/src/struct2ui/icons/c2j.png +0 -0
  35. {struct2ui-0.4.3 → struct2ui-0.5.0}/src/struct2ui/icons/elf.png +0 -0
  36. {struct2ui-0.4.3 → struct2ui-0.5.0}/src/struct2ui/icons/export_notes_24dp_000000_FILL0_wght400_GRAD0_opsz24.png +0 -0
  37. {struct2ui-0.4.3 → struct2ui-0.5.0}/src/struct2ui/icons/flowchart_24dp_000000_FILL0_wght400_GRAD0_opsz24.png +0 -0
  38. {struct2ui-0.4.3 → struct2ui-0.5.0}/src/struct2ui/icons/refresh_24dp_000000_FILL0_wght400_GRAD0_opsz24.png +0 -0
  39. {struct2ui-0.4.3 → struct2ui-0.5.0}/src/struct2ui/icons/report_24dp_000000_FILL0_wght400_GRAD0_opsz24.png +0 -0
  40. {struct2ui-0.4.3 → struct2ui-0.5.0}/src/struct2ui/icons/save_24dp_000000_FILL0_wght400_GRAD0_opsz24.png +0 -0
  41. {struct2ui-0.4.3 → struct2ui-0.5.0}/src/struct2ui/icons/save_as_24dp_000000_FILL0_wght400_GRAD0_opsz24.png +0 -0
  42. {struct2ui-0.4.3 → struct2ui-0.5.0}/src/struct2ui/icons/settings_24dp_000000_FILL0_wght400_GRAD0_opsz24.png +0 -0
  43. {struct2ui-0.4.3 → struct2ui-0.5.0}/src/struct2ui/icons/widgets_24dp_000000_FILL0_wght400_GRAD0_opsz24.png +0 -0
  44. {struct2ui-0.4.3 → struct2ui-0.5.0}/src/struct2ui/ui/__init__.py +0 -0
  45. {struct2ui-0.4.3 → struct2ui-0.5.0}/src/struct2ui.egg-info/dependency_links.txt +0 -0
  46. {struct2ui-0.4.3 → struct2ui-0.5.0}/src/struct2ui.egg-info/requires.txt +0 -0
  47. {struct2ui-0.4.3 → struct2ui-0.5.0}/src/struct2ui.egg-info/top_level.txt +0 -0
  48. {struct2ui-0.4.3 → struct2ui-0.5.0}/tests/test_bin_emitter.py +0 -0
  49. {struct2ui-0.4.3 → struct2ui-0.5.0}/tests/test_choices.py +0 -0
  50. {struct2ui-0.4.3 → struct2ui-0.5.0}/tests/test_elf_verifier.py +0 -0
  51. {struct2ui-0.4.3 → struct2ui-0.5.0}/tests/test_value_readback.py +0 -0
@@ -1,8 +1,8 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: struct2ui
3
- Version: 0.4.3
3
+ Version: 0.5.0
4
4
  Summary: Render C struct / JSON schema as editable PySide6 UI, export to C/JSON/bin
5
- Author: Jay
5
+ Author-email: Jay <huoyj0108@163.com>
6
6
  License: MIT License
7
7
 
8
8
  Copyright (c) 2026 Jay
@@ -60,7 +60,9 @@ Render C structs / JSON schemas as an **editable PySide6 UI**, and convert freel
60
60
  - **JSON → UI**: describe C structs / enums / arrays with minimal JSON and auto-render Qt widgets (int→QSpinBox, float→QDoubleSpinBox, enum→QComboBox, etc.).
61
61
  - **Embeddable**: `StructEditor` is a plain `QWidget` that drops into any PySide6 / PyQt UI.
62
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.
63
64
  - **Validation**: keyword spell-checking (with “Did you mean X?” hints), semantic audits (`min<=max`, `step>0`), and pipeline cross-validation.
65
+ - **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.
64
66
  - **Qt-binding agnostic**: built on [Qt.py](https://github.com/mottosso/Qt.py) — works with PySide6 / PyQt6 / PySide2 / PyQt5.
65
67
 
66
68
  ## Installation
@@ -141,6 +143,7 @@ generated from it. Files live in the **modules directory** (`cfg_dir`), one
141
143
  | --- | --- | --- |
142
144
  | `struct` | `type`, `items` (list of field specs) | `items` is required |
143
145
  | `enum` | `type`, `items` (object `{NAME: value}`) | reads back the enumerator name |
146
+ | `union` | `type`, `items` (list of branch structs), `branch` (optional) | tagged union; each branch is an inline `struct` selected by its `when` (see below) |
144
147
  | `typedefs` | object `{alias: real_type}` | resolved before field building |
145
148
 
146
149
  Free-form metadata keys are allowed and ignored at any level: `version`,
@@ -158,9 +161,9 @@ recognized — any other key triggers an "unknown keyword" error (with a
158
161
  | `type` | all | **Required.** C type or a `typedefs` alias (e.g. `int32_t`, `float`, `char`, an enum/struct name). |
159
162
  | `value` | all | Default value. For arrays, a list (per element) or a scalar (applied to every element). |
160
163
  | `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). |
161
- | `min` / `max` | int, float | Numeric bounds. Validated `min <= max`. Drive spin-box / slider / dial ranges. |
164
+ | `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. |
162
165
  | `step` | int, float | Increment, must be `> 0`. |
163
- | `decimals` | float | Number of fractional digits shown/stored. Non-negative integer; defaults to digits implied by `step`. |
166
+ | `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). |
164
167
  | `unit` | all | Unit suffix shown in the label, e.g. `gain (dB)`. |
165
168
  | `tip` | all | Tooltip text. |
166
169
  | `choices` | int, float, `char[N]` | Discrete value set rendered as a combo (see below). |
@@ -181,7 +184,7 @@ When omitted, the widget is inferred from `type` (and from `min/max`,
181
184
  | `dial` | int | Rotary dial popup (requires `min` & `max`). |
182
185
  | `file` | array | Path label + Browse button; loads array values from a text file. |
183
186
  | `multiline` | array | Single-line shell that pops up a multi-line editor. |
184
- | `table` | struct array | Force grid layout (one column per struct member). |
187
+ | `table` | struct array | Force grid layout (one column per struct member; a union member pinned via `branch` expands its branch members into columns). |
185
188
 
186
189
  Numeric fields without an explicit `widget` become a `QSpinBox` /
187
190
  `QDoubleSpinBox`; scalar arrays become a comma-separated line edit.
@@ -214,6 +217,33 @@ match (logical AND):
214
217
  The dependency name is matched against the dotted leaf name in scope. When a
215
218
  dependency is not found, the field stays enabled.
216
219
 
220
+ ### `union` (tagged union) & `branch`
221
+
222
+ A `union` block declares overlapping branches, each an inline `struct` in
223
+ `items`. At runtime the branch whose `when` matches is the one shown / exported
224
+ (first match wins); the union's `.bin` / `.c` size is always the largest branch
225
+ and unmatched exports are zero-padded.
226
+
227
+ ```jsonc
228
+ { "name": "FilterCoeffs", "type": "union", "items": [
229
+ { "name": "raw", "type": "struct", "when": { "type": "IIR_BIQUARD_RAW" },
230
+ "items": [ /* 5 floats */ ] },
231
+ { "name": "design", "type": "struct", "when": { "type": { "!=": "IIR_BIQUARD_RAW" } },
232
+ "items": [ { "name": "f0", "type": "float" }, /* ... */ ] }
233
+ ] }
234
+ ```
235
+
236
+ Set `branch` on the union to **pin it to a single branch**: only that branch is
237
+ a candidate (the others are never shown and their `when` is ignored); the pinned
238
+ branch is still gated by its own `when`. Pinning to a flat (all-leaf) branch lets
239
+ a struct array carrying the union render as a **table** — the branch members
240
+ become columns, and a row whose discriminator makes the branch `when` false has
241
+ those cells disabled (value kept, still exported zero-padded).
242
+
243
+ ```jsonc
244
+ { "name": "coeffs", "type": "FilterCoeffs", "branch": "design" }
245
+ ```
246
+
217
247
  ### `count` expressions & multi-dimensional arrays
218
248
 
219
249
  `count` may be an integer, a `#define` constant name, or an integer expression
@@ -236,6 +266,57 @@ Loading runs three layers of checks, surfaced in the **load report** panel:
236
266
  - **Pipeline cross-validation** — values in the pipeline file are checked
237
267
  against the schema (range, choices, enum membership).
238
268
 
269
+ ## Pipeline File
270
+
271
+ While the **modules directory** (`cfg_dir`) defines your *types*, the
272
+ **pipeline file** (`flow_file`) describes one concrete *instance*: which module
273
+ stages are present, in what order, and their edited values. It is a single JSON
274
+ object with **one top-level group key** (any name you like, e.g. the product /
275
+ tuning name) whose value is the group body:
276
+
277
+ ```jsonc
278
+ {
279
+ "Speech Tuning": {
280
+ "flow": ["RX NS", "RX DRC", "RX EQ"], // stage order, required
281
+ "container": "SpeechConfig", // optional, enables layout check
282
+
283
+ "RX NS": { "type": "SpeechNs2FloatConfig", "items": { /* values */ } },
284
+ "RX DRC": { "type": "MultiCompexpConfig" }, // 'items' may be omitted
285
+ "RX EQ": { "type": "EqConfig", "items": { /* values */ } }
286
+ }
287
+ }
288
+ ```
289
+
290
+ ### Group-level keys
291
+
292
+ | Key | Required | Notes |
293
+ | --- | --- | --- |
294
+ | `flow` | yes | Ordered list of stage names. The flow buttons and the export order follow it. Every listed name must have a stage block; defined stages missing from `flow` are a warning. |
295
+ | `container` | no | Name of the SDK struct that holds all modules (see [Container layout check](#container-layout-check)). Omit to disable that check. |
296
+ | *stage name* | — | Any other key is a **stage block**; its name is the label shown on the flow button. |
297
+
298
+ All keys are **lowercase and case-sensitive** — write `flow`, not `Flow`. A
299
+ mistyped key (`Flow`, `flwo`, …) is reported with a "Did you mean `flow`?" hint.
300
+ Free-form metadata keys (`version`, `description`, `author`, `comment`, `note`)
301
+ are allowed and ignored.
302
+
303
+ ### Stage block
304
+
305
+ | Key | Required | Notes |
306
+ | --- | --- | --- |
307
+ | `type` | yes | A struct / union type name defined in the modules directory. |
308
+ | `items` | no | The edited values, keyed by field name. **Omitting `items` means "all defaults"** — the stage renders from the type's declared defaults. |
309
+ | `member` | no | For the container layout check: the member name inside `container` this stage maps to (defaults to the stage label). |
310
+
311
+ ### Container layout check
312
+
313
+ When `container` names an SDK struct and an ELF is loaded, the whole pipeline is
314
+ laid out in `flow` order — as if each stage were a member of that container —
315
+ and compared member-by-member against the struct's DWARF layout (offset, size,
316
+ total size). This catches stages in the **wrong order**: if the modules are all
317
+ correct but reordered, you get a single "module order is wrong" error naming the
318
+ expected order, instead of a pile of misleading offset mismatches.
319
+
239
320
  ## Embedding into an Existing UI
240
321
 
241
322
  `StructEditor` is a regular `QWidget`; just put it into a layout:
@@ -359,6 +440,7 @@ from code (e.g. wired to a custom button):
359
440
  | `current_paths() -> dict` | Current `{'modules', 'pipeline', 'elf'}` file paths; an empty string means that slot is unset. |
360
441
  | `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). |
361
442
  | `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. |
443
+ | `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. |
362
444
 
363
445
  `export_bin` verifies the ELF layout first when an ELF is selected and enabled (the file is
364
446
  still written, matching the UI flow). With `show_dialogs=True` it pops the same
@@ -372,6 +454,16 @@ name = paths['pipeline'] # derive an output name from the pipel
372
454
  ok = editor.export_bin("out/speech.bin") # True when ELF layout is clean
373
455
  ```
374
456
 
457
+ `import_bin` is the reverse trip: feed it a `.bin` the chip sent back and the UI
458
+ is repopulated from it. Because the image is a byte-for-byte C-ABI layout, its
459
+ length must match the pipeline layout exactly — a short or long image is
460
+ rejected wholesale so a stale/mismatched dump can never partially corrupt the
461
+ form.
462
+
463
+ ```python
464
+ ok = editor.import_bin("out/speech.bin") # True when the image was applied
465
+ ```
466
+
375
467
  ## Export API
376
468
 
377
469
  The low-level export functions can be used standalone, without any UI:
@@ -382,6 +474,7 @@ from struct2ui.exporters import (
382
474
  emit_c, # sections + registry -> C source string
383
475
  dumps_json, # -> JSON string
384
476
  emit_bin, # -> binary bytes
477
+ read_bin, # binary bytes -> values dict (inverse of emit_bin)
385
478
  merge_abi, # merge ABI info
386
479
  verify_sections, # verify .bin layout against an ELF
387
480
  parse_c_source, # C source -> parse result
@@ -7,7 +7,9 @@ Render C structs / JSON schemas as an **editable PySide6 UI**, and convert freel
7
7
  - **JSON → UI**: describe C structs / enums / arrays with minimal JSON and auto-render Qt widgets (int→QSpinBox, float→QDoubleSpinBox, enum→QComboBox, etc.).
8
8
  - **Embeddable**: `StructEditor` is a plain `QWidget` that drops into any PySide6 / PyQt UI.
9
9
  - **Multi-format export**: edited results export to C source, JSON, or binary; C source can also be parsed back into a schema.
10
+ - **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.
10
11
  - **Validation**: keyword spell-checking (with “Did you mean X?” hints), semantic audits (`min<=max`, `step>0`), and pipeline cross-validation.
12
+ - **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.
11
13
  - **Qt-binding agnostic**: built on [Qt.py](https://github.com/mottosso/Qt.py) — works with PySide6 / PyQt6 / PySide2 / PyQt5.
12
14
 
13
15
  ## Installation
@@ -88,6 +90,7 @@ generated from it. Files live in the **modules directory** (`cfg_dir`), one
88
90
  | --- | --- | --- |
89
91
  | `struct` | `type`, `items` (list of field specs) | `items` is required |
90
92
  | `enum` | `type`, `items` (object `{NAME: value}`) | reads back the enumerator name |
93
+ | `union` | `type`, `items` (list of branch structs), `branch` (optional) | tagged union; each branch is an inline `struct` selected by its `when` (see below) |
91
94
  | `typedefs` | object `{alias: real_type}` | resolved before field building |
92
95
 
93
96
  Free-form metadata keys are allowed and ignored at any level: `version`,
@@ -105,9 +108,9 @@ recognized — any other key triggers an "unknown keyword" error (with a
105
108
  | `type` | all | **Required.** C type or a `typedefs` alias (e.g. `int32_t`, `float`, `char`, an enum/struct name). |
106
109
  | `value` | all | Default value. For arrays, a list (per element) or a scalar (applied to every element). |
107
110
  | `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). |
108
- | `min` / `max` | int, float | Numeric bounds. Validated `min <= max`. Drive spin-box / slider / dial ranges. |
111
+ | `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. |
109
112
  | `step` | int, float | Increment, must be `> 0`. |
110
- | `decimals` | float | Number of fractional digits shown/stored. Non-negative integer; defaults to digits implied by `step`. |
113
+ | `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). |
111
114
  | `unit` | all | Unit suffix shown in the label, e.g. `gain (dB)`. |
112
115
  | `tip` | all | Tooltip text. |
113
116
  | `choices` | int, float, `char[N]` | Discrete value set rendered as a combo (see below). |
@@ -128,7 +131,7 @@ When omitted, the widget is inferred from `type` (and from `min/max`,
128
131
  | `dial` | int | Rotary dial popup (requires `min` & `max`). |
129
132
  | `file` | array | Path label + Browse button; loads array values from a text file. |
130
133
  | `multiline` | array | Single-line shell that pops up a multi-line editor. |
131
- | `table` | struct array | Force grid layout (one column per struct member). |
134
+ | `table` | struct array | Force grid layout (one column per struct member; a union member pinned via `branch` expands its branch members into columns). |
132
135
 
133
136
  Numeric fields without an explicit `widget` become a `QSpinBox` /
134
137
  `QDoubleSpinBox`; scalar arrays become a comma-separated line edit.
@@ -161,6 +164,33 @@ match (logical AND):
161
164
  The dependency name is matched against the dotted leaf name in scope. When a
162
165
  dependency is not found, the field stays enabled.
163
166
 
167
+ ### `union` (tagged union) & `branch`
168
+
169
+ A `union` block declares overlapping branches, each an inline `struct` in
170
+ `items`. At runtime the branch whose `when` matches is the one shown / exported
171
+ (first match wins); the union's `.bin` / `.c` size is always the largest branch
172
+ and unmatched exports are zero-padded.
173
+
174
+ ```jsonc
175
+ { "name": "FilterCoeffs", "type": "union", "items": [
176
+ { "name": "raw", "type": "struct", "when": { "type": "IIR_BIQUARD_RAW" },
177
+ "items": [ /* 5 floats */ ] },
178
+ { "name": "design", "type": "struct", "when": { "type": { "!=": "IIR_BIQUARD_RAW" } },
179
+ "items": [ { "name": "f0", "type": "float" }, /* ... */ ] }
180
+ ] }
181
+ ```
182
+
183
+ Set `branch` on the union to **pin it to a single branch**: only that branch is
184
+ a candidate (the others are never shown and their `when` is ignored); the pinned
185
+ branch is still gated by its own `when`. Pinning to a flat (all-leaf) branch lets
186
+ a struct array carrying the union render as a **table** — the branch members
187
+ become columns, and a row whose discriminator makes the branch `when` false has
188
+ those cells disabled (value kept, still exported zero-padded).
189
+
190
+ ```jsonc
191
+ { "name": "coeffs", "type": "FilterCoeffs", "branch": "design" }
192
+ ```
193
+
164
194
  ### `count` expressions & multi-dimensional arrays
165
195
 
166
196
  `count` may be an integer, a `#define` constant name, or an integer expression
@@ -183,6 +213,57 @@ Loading runs three layers of checks, surfaced in the **load report** panel:
183
213
  - **Pipeline cross-validation** — values in the pipeline file are checked
184
214
  against the schema (range, choices, enum membership).
185
215
 
216
+ ## Pipeline File
217
+
218
+ While the **modules directory** (`cfg_dir`) defines your *types*, the
219
+ **pipeline file** (`flow_file`) describes one concrete *instance*: which module
220
+ stages are present, in what order, and their edited values. It is a single JSON
221
+ object with **one top-level group key** (any name you like, e.g. the product /
222
+ tuning name) whose value is the group body:
223
+
224
+ ```jsonc
225
+ {
226
+ "Speech Tuning": {
227
+ "flow": ["RX NS", "RX DRC", "RX EQ"], // stage order, required
228
+ "container": "SpeechConfig", // optional, enables layout check
229
+
230
+ "RX NS": { "type": "SpeechNs2FloatConfig", "items": { /* values */ } },
231
+ "RX DRC": { "type": "MultiCompexpConfig" }, // 'items' may be omitted
232
+ "RX EQ": { "type": "EqConfig", "items": { /* values */ } }
233
+ }
234
+ }
235
+ ```
236
+
237
+ ### Group-level keys
238
+
239
+ | Key | Required | Notes |
240
+ | --- | --- | --- |
241
+ | `flow` | yes | Ordered list of stage names. The flow buttons and the export order follow it. Every listed name must have a stage block; defined stages missing from `flow` are a warning. |
242
+ | `container` | no | Name of the SDK struct that holds all modules (see [Container layout check](#container-layout-check)). Omit to disable that check. |
243
+ | *stage name* | — | Any other key is a **stage block**; its name is the label shown on the flow button. |
244
+
245
+ All keys are **lowercase and case-sensitive** — write `flow`, not `Flow`. A
246
+ mistyped key (`Flow`, `flwo`, …) is reported with a "Did you mean `flow`?" hint.
247
+ Free-form metadata keys (`version`, `description`, `author`, `comment`, `note`)
248
+ are allowed and ignored.
249
+
250
+ ### Stage block
251
+
252
+ | Key | Required | Notes |
253
+ | --- | --- | --- |
254
+ | `type` | yes | A struct / union type name defined in the modules directory. |
255
+ | `items` | no | The edited values, keyed by field name. **Omitting `items` means "all defaults"** — the stage renders from the type's declared defaults. |
256
+ | `member` | no | For the container layout check: the member name inside `container` this stage maps to (defaults to the stage label). |
257
+
258
+ ### Container layout check
259
+
260
+ When `container` names an SDK struct and an ELF is loaded, the whole pipeline is
261
+ laid out in `flow` order — as if each stage were a member of that container —
262
+ and compared member-by-member against the struct's DWARF layout (offset, size,
263
+ total size). This catches stages in the **wrong order**: if the modules are all
264
+ correct but reordered, you get a single "module order is wrong" error naming the
265
+ expected order, instead of a pile of misleading offset mismatches.
266
+
186
267
  ## Embedding into an Existing UI
187
268
 
188
269
  `StructEditor` is a regular `QWidget`; just put it into a layout:
@@ -306,6 +387,7 @@ from code (e.g. wired to a custom button):
306
387
  | `current_paths() -> dict` | Current `{'modules', 'pipeline', 'elf'}` file paths; an empty string means that slot is unset. |
307
388
  | `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). |
308
389
  | `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. |
390
+ | `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. |
309
391
 
310
392
  `export_bin` verifies the ELF layout first when an ELF is selected and enabled (the file is
311
393
  still written, matching the UI flow). With `show_dialogs=True` it pops the same
@@ -319,6 +401,16 @@ name = paths['pipeline'] # derive an output name from the pipel
319
401
  ok = editor.export_bin("out/speech.bin") # True when ELF layout is clean
320
402
  ```
321
403
 
404
+ `import_bin` is the reverse trip: feed it a `.bin` the chip sent back and the UI
405
+ is repopulated from it. Because the image is a byte-for-byte C-ABI layout, its
406
+ length must match the pipeline layout exactly — a short or long image is
407
+ rejected wholesale so a stale/mismatched dump can never partially corrupt the
408
+ form.
409
+
410
+ ```python
411
+ ok = editor.import_bin("out/speech.bin") # True when the image was applied
412
+ ```
413
+
322
414
  ## Export API
323
415
 
324
416
  The low-level export functions can be used standalone, without any UI:
@@ -329,6 +421,7 @@ from struct2ui.exporters import (
329
421
  emit_c, # sections + registry -> C source string
330
422
  dumps_json, # -> JSON string
331
423
  emit_bin, # -> binary bytes
424
+ read_bin, # binary bytes -> values dict (inverse of emit_bin)
332
425
  merge_abi, # merge ABI info
333
426
  verify_sections, # verify .bin layout against an ELF
334
427
  parse_c_source, # C source -> parse result
@@ -4,13 +4,13 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "struct2ui"
7
- version = "0.4.3"
7
+ dynamic = ["version"]
8
8
  description = "Render C struct / JSON schema as editable PySide6 UI, export to C/JSON/bin"
9
9
  readme = "README.md"
10
10
  requires-python = ">=3.9"
11
11
  license = {file = "LICENSE"}
12
12
  authors = [
13
- {name = "Jay"},
13
+ {name = "Jay", email = "huoyj0108@163.com"},
14
14
  ]
15
15
  keywords = ["qt", "pyside6", "gui", "c-struct", "json-schema", "code-generation", "parameter-tuning"]
16
16
  classifiers = [
@@ -40,3 +40,6 @@ where = ["src"]
40
40
 
41
41
  [tool.setuptools.package-data]
42
42
  struct2ui = ["icons/*.png"]
43
+
44
+ [tool.setuptools.dynamic]
45
+ version = {attr = "struct2ui.__version__"}
@@ -1,4 +1,4 @@
1
1
  from .editor import StructEditor
2
2
 
3
- __version__ = "0.4.3"
3
+ __version__ = "0.5.0"
4
4
  __all__ = ["StructEditor"]
@@ -23,10 +23,61 @@ from .schema import (
23
23
  from .ui import pick_renderer, collect_view_values
24
24
  from .exporters import (
25
25
  emit_c, dumps_json, emit_bin, merge_abi, verify_sections,
26
+ verify_container_layout, read_bin, BinReadError,
26
27
  parse_c_source, build_schema_dict,
27
28
  )
28
29
 
29
30
 
31
+ def _container_stages(flow, section_specs, raw_data):
32
+ """Extract the pipeline container type and ordered (label, type, member)
33
+ stage tuples for whole-container ELF verification.
34
+
35
+ The container is declared per group as a `container` string (the SDK
36
+ struct that holds all modules, e.g. "SpeechConfig"). Returns ('', []) when
37
+ no container is declared, which disables the check.
38
+ """
39
+ container = ''
40
+ if isinstance(raw_data, dict) and raw_data:
41
+ group = raw_data.get(next(iter(raw_data.keys())))
42
+ if isinstance(group, dict):
43
+ c = group.get('container')
44
+ if isinstance(c, str):
45
+ container = c
46
+ if not container:
47
+ return '', []
48
+ stages = []
49
+ for label in flow:
50
+ spec = section_specs.get(label)
51
+ if not isinstance(spec, dict):
52
+ continue
53
+ type_name = spec.get('type') or ''
54
+ if not type_name:
55
+ continue
56
+ member = spec.get('member')
57
+ stages.append((label, type_name,
58
+ member if isinstance(member, str) else None))
59
+ return container, stages
60
+
61
+
62
+ def _norm_path(path: str) -> str:
63
+ """Normalize a source path to a single consistent, OS-native form.
64
+
65
+ Paths reach the editor from two sources with different styles: defaults
66
+ handed in via set_sources() (os.path.join -> backslashes, drive case as
67
+ typed) and Qt file dialogs (forward slashes, upper-case drive on Windows).
68
+ os.path.normpath unifies the separators per platform (backslash on Windows,
69
+ forward slash on POSIX). On Windows we also upper-case the drive letter so
70
+ the two sources match exactly; POSIX paths have no drive and are untouched.
71
+ """
72
+ if not path:
73
+ return path
74
+ norm = os.path.normpath(path)
75
+ drive, rest = os.path.splitdrive(norm)
76
+ if drive: # Windows drive like 'c:' -> 'C:'; no-op on POSIX (drive == '')
77
+ norm = drive.upper() + rest
78
+ return norm
79
+
80
+
30
81
  class _OverflowBar(QtWidgets.QWidget):
31
82
  """Single-row button bar that collapses buttons into a menu when narrow.
32
83
 
@@ -324,10 +375,10 @@ class _LoadWorker(QtCore.QRunnable):
324
375
  group = data.get(group_key, {})
325
376
  if not isinstance(group, dict):
326
377
  return '', [], {}, {}
327
- flow = list(group.get('Flow', []) or [])
378
+ flow = list(group.get('flow', []) or [])
328
379
  section_specs = {
329
380
  label: spec for label, spec in group.items()
330
- if label != 'Flow' and isinstance(spec, dict)
381
+ if label != 'flow' and isinstance(spec, dict)
331
382
  }
332
383
  return group_key, flow, section_specs, data
333
384
 
@@ -361,7 +412,12 @@ class _LoadWorker(QtCore.QRunnable):
361
412
  if not sections:
362
413
  return None
363
414
  abi = merge_abi(raw_data.get('abi'))
364
- return verify_sections(sections, registry, self._elf_path, abi)
415
+ report = verify_sections(sections, registry, self._elf_path, abi)
416
+ container, stages = _container_stages(flow, section_specs, raw_data)
417
+ if container:
418
+ report.extend(verify_container_layout(
419
+ container, stages, registry, self._elf_path, abi))
420
+ return report
365
421
 
366
422
 
367
423
  class StructEditor(QtWidgets.QWidget):
@@ -728,6 +784,54 @@ class StructEditor(QtWidgets.QWidget):
728
784
 
729
785
  return elf_ok
730
786
 
787
+ def import_bin(self, source, show_dialogs: bool = False) -> bool:
788
+ """Load a raw .bin image (e.g. read back from the chip) into the UI.
789
+
790
+ The image must be a byte-for-byte C-ABI layout of the whole pipeline
791
+ (the inverse of export_bin). Its length must match the pipeline layout
792
+ exactly; on any mismatch the image is rejected and the UI is left
793
+ unchanged.
794
+
795
+ source : a .bin file path (str) or the raw bytes.
796
+ show_dialogs : when True, success/failure pop a QMessageBox like the
797
+ Export flow; when False errors are raised instead.
798
+
799
+ Returns True when the image was decoded and applied, False otherwise.
800
+ """
801
+ try:
802
+ if self.registry is None or not self._flow:
803
+ raise BinReadError(
804
+ 'no pipeline is loaded; load a Flow before importing a bin')
805
+ data = source if isinstance(source, (bytes, bytearray)) else \
806
+ open(source, 'rb').read()
807
+ sections = [(label, type_name)
808
+ for label, type_name, _ in self._flow_sections()]
809
+ abi = merge_abi(self._raw_data.get('abi'))
810
+ values = read_bin(bytes(data), sections, self.registry, abi)
811
+ except Exception as exc:
812
+ if show_dialogs:
813
+ QtWidgets.QMessageBox.critical(
814
+ self, 'Import failed', f'Could not import bin:\n{exc}')
815
+ return False
816
+ raise
817
+
818
+ # Apply: overwrite each stage's items, then re-render. Clear the active
819
+ # label first so the pending _capture_active_section() does not write
820
+ # stale widget values back over what we just imported.
821
+ for label, section_values in values.items():
822
+ spec = self._section_specs.get(label)
823
+ if isinstance(spec, dict):
824
+ spec['items'] = section_values
825
+ active = self._active_label or (self._flow[0] if self._flow else '')
826
+ self._active_label = ''
827
+ if active:
828
+ self._on_button_clicked(active)
829
+
830
+ if show_dialogs:
831
+ QtWidgets.QMessageBox.information(
832
+ self, 'Imported', 'Imported parameters from bin.')
833
+ return True
834
+
731
835
  def set_sources(self, cfg_dir: str = None, flow_file: str = None,
732
836
  elf_file: str = None, elf_enabled: bool = None,
733
837
  reload: bool = True, async_load: bool = False) -> None:
@@ -747,11 +851,11 @@ class StructEditor(QtWidgets.QWidget):
747
851
  "Loading..." placeholder until the data is ready.
748
852
  """
749
853
  if cfg_dir is not None:
750
- self.struct_dir = cfg_dir
854
+ self.struct_dir = _norm_path(cfg_dir)
751
855
  if flow_file is not None:
752
- self.pipeline_path = flow_file
856
+ self.pipeline_path = _norm_path(flow_file)
753
857
  if elf_file is not None:
754
- self.elf_path = elf_file
858
+ self.elf_path = _norm_path(elf_file)
755
859
  if elf_enabled is None:
756
860
  self.elf_enabled = bool(elf_file)
757
861
  if elf_enabled is not None:
@@ -806,7 +910,7 @@ class StructEditor(QtWidgets.QWidget):
806
910
  chosen = QtWidgets.QFileDialog.getExistingDirectory(
807
911
  self, 'Select modules directory', start)
808
912
  if chosen:
809
- self.struct_dir = chosen
913
+ self.struct_dir = _norm_path(chosen)
810
914
  self._refresh_path_tooltips()
811
915
 
812
916
  def _pick_flow_file(self) -> None:
@@ -814,7 +918,7 @@ class StructEditor(QtWidgets.QWidget):
814
918
  chosen, _ = QtWidgets.QFileDialog.getOpenFileName(
815
919
  self, 'Select pipeline JSON', start, 'JSON files (*.json)')
816
920
  if chosen:
817
- self.pipeline_path = chosen
921
+ self.pipeline_path = _norm_path(chosen)
818
922
  self._refresh_path_tooltips()
819
923
 
820
924
  def _pick_elf_file(self) -> None:
@@ -826,7 +930,7 @@ class StructEditor(QtWidgets.QWidget):
826
930
  'ELF files (*.elf *.axf *.out);;All files (*)')
827
931
  if not chosen:
828
932
  return
829
- self.elf_path = chosen
933
+ self.elf_path = _norm_path(chosen)
830
934
  self._refresh_elf_tooltip()
831
935
 
832
936
  def _set_elf_enabled(self, on: bool) -> None:
@@ -979,6 +1083,11 @@ class StructEditor(QtWidgets.QWidget):
979
1083
  abi = merge_abi(self._raw_data.get('abi'))
980
1084
  self._elf_report = verify_sections(
981
1085
  sections, self.registry, self.elf_path, abi)
1086
+ container, stages = _container_stages(
1087
+ self._flow, self._section_specs, self._raw_data)
1088
+ if container:
1089
+ self._elf_report.extend(verify_container_layout(
1090
+ container, stages, self.registry, self.elf_path, abi))
982
1091
  print(self._elf_report.format(), end='')
983
1092
 
984
1093
  # ---- buttons --------------------------------------------------------- #
@@ -1136,7 +1245,7 @@ class StructEditor(QtWidgets.QWidget):
1136
1245
  return
1137
1246
  # Saving As redirects subsequent Save/Reload to the new file.
1138
1247
  if path != self.pipeline_path:
1139
- self.pipeline_path = path
1248
+ self.pipeline_path = _norm_path(path)
1140
1249
  self._refresh_path_tooltips()
1141
1250
  QtWidgets.QMessageBox.information(
1142
1251
  self, 'Saved', f'Pipeline saved to:\n{path}')
@@ -7,9 +7,11 @@ Public API (stable; safe to import from outside):
7
7
  from .c_emitter import emit_c
8
8
  from .json_format import dumps as dumps_json
9
9
  from .bin_emitter import emit_bin, merge_abi
10
- from .elf_verifier import verify_sections
10
+ from .bin_reader import read_bin, BinReadError
11
+ from .elf_verifier import verify_sections, verify_container_layout
11
12
  from .c_parser import parse_c_source, build_schema_dict
12
13
 
13
14
 
14
15
  __all__ = ['emit_c', 'dumps_json', 'emit_bin', 'merge_abi', 'verify_sections',
16
+ 'verify_container_layout', 'read_bin', 'BinReadError',
15
17
  'parse_c_source', 'build_schema_dict']