README Source History Refs Reviews Compare Notes Search Review guide Budget compile time, gate dependencies, and prove per-frame layout (#9) 3e3df798044f2b6b31e68c3572e3846bd7d1aa9b
Oliver Jan Krylow <oliver@bugabinga.net > · 17 Jul 2026
SSH signature · not checked
Browse files Compare with HEAD
* Make dependencies a spec decision and budget compile time by caching
A worker agent that quietly adds a crate can drop a minute onto every
build and poison the incremental cache the workspace split exists to
protect, so dependency changes now require spec-owner escalation
(PROJECT-INVARIANTS §5) — prototypes stay exempt because validating a
candidate before production is their whole job. The compile budget is
split to match how the cost is actually felt: incremental rebuild of a
touched crate's reverse-dep closure is the governing dev/agent metric
and a structural guarantee of dependency siloing, while cold build and
crate count are a CI regression gate paid once. The fast tier scopes to
touched crates so that guarantee is realized, not erased by a
--workspace --all-features sweep.
Edits PROJECT-INVARIANTS §5/§11 and SPEC §2.3/§13.1/§17.1.
* Plan the per-frame layout prototype
§8 says Lua defines layout and the render loop ticks at 16ms, but never
says where resolution happens — and if it re-enters Lua every frame it
would put plugin-thread round-trips (p15: ~81us, serialized) on the 2ms
render path. p27 validates the intended design instead of assuming it:
Lua builds the tree once, Rust resolves Rects every frame with no Lua in
the loop.
Adds prototypes/PLAN.md section p27.
* Separate adding a dependency from bumping one
The prior rule treated a version bump like adding a crate, but they are
different acts: adding pulls a new concern into the architecture and
compile budget and must escalate, while bumping an already-approved
crate is security and compatibility upkeep that a dedicated dependency
agent should own. Routine bumps now ride the CI gates instead of a
per-bump escalation; only a semver-breaking, MSRV-raising, or
budget-tripping bump escalates like a new dependency, because those can
change behavior or cost.
Edits PROJECT-INVARIANTS §5 and SPEC §2.3.
* Prove per-frame layout resolves in Rust with no Lua in the loop
§8 said Lua defines layout and the render loop ticks at 16ms but never
said where resolution runs — and re-entering the plugin thread every
frame (p15: ~81us, serialized) would fight the 2ms budget. It doesn't
have to: Lua builds the tree once into an owned Send+static Rust
structure, the Lua value is dropped, and a pure resolver maps
(tree, size) to Rects every frame. A call counter stayed flat across
10k resolves at three terminal sizes; release p99 is 0.47us against the
2ms budget, and the resolved tree moves cross-thread and resolves
identically after the Lua state is gone.
Surfaced a real gap too: §8.7 has no operator to float an overlay over
a base layout, and leaves tabs/scrollable/Size::Pct rounding to the
resolver to invent.
Adds prototypes/p27-per-frame-layout.
* Pin the layout-resolution contract, keeping Lua off the render path
p27 proved the resolution model §8 had only implied: a plugin builds
the layout on change into an owned Send tree, the Lua value is dropped,
and a pure Rust resolver maps it to Rects every frame with zero Lua
re-entry — so the plugin thread's ~81us round-trips never touch the 2ms
budget (measured resolution is ~0.4us). The layout invariants become a
property-test target, and the overlay/tabs/scrollable/Size rounding
rules the prototype had to invent are now stated instead of left to the
implementer.
Edits SPEC §8.7/§17.6 and the p27 result block in prototypes/PLAN.md.
---------
Co-authored-by: Claude <noreply@anthropic.com> Changed files (6) Diff layout Auto Unified Split
docs/PROJECT-INVARIANTS.md Modified +28 / −1 text lines
254 254 Files that coding agents MUST NOT modify without explicit user approval:Files that coding agents MUST NOT modify without explicit user approval:255 255 - `docs/PROJECT-INVARIANTS.md`- `docs/PROJECT-INVARIANTS.md`256 256 - `docs/SPEC.md` (source of truth — agents read, don't edit without approval)- `docs/SPEC.md` (source of truth — agents read, don't edit without approval)257 - - `Cargo.toml` workspace root (agents read dependencies, don't add/remove)257 + - `Cargo.toml` workspace root258 + - adding or removing a crate in any `Cargo.toml` `[dependencies]` (version259 + bumps are maintenance — see the dependency rule below)258 260 - `.cargo/config.toml`- `.cargo/config.toml`259 261 - `rust-toolchain.toml`- `rust-toolchain.toml`
263 + **Adding a dependency is a spec decision; bumping one is maintenance.** A new264 + third-party crate — or removing one — changes the architecture, crate set,265 + compile budget, and siloing, so a worker agent escalates to the spec owner and266 + never introduces a crate on its own initiative. The canonical set is SPEC §2.3267 + and the change follows the spec-approval path. A **version bump** of an268 + already-approved crate is routine upkeep, not a spec decision: it may be done269 + by a dedicated dependency-maintenance agent or automation, provided it passes270 + every gate — build, tests, clippy, `cargo deny`, and the §13.1 compile-budget271 + regression gate. A bump that is semver-incompatible, raises the toolchain MSRV,272 + or trips the compile-budget gate escalates like a new dependency, because it273 + can change behavior or cost. Prototypes under `prototypes/` are exempt from all274 + of this (SPEC §18): adding a crate to validate it before production is their275 + job, and that evidence is what gets escalated.261 277 Files that coding agents MAY modify freely:Files that coding agents MAY modify freely:262 278 - `*/src/*.rs` (implementation)- `*/src/*.rs` (implementation)263 279 - `*/tests/*.rs` (tests)- `*/tests/*.rs` (tests)407 423 - `mod.rs` files contain only module declarations and re-exports.- `mod.rs` files contain only module declarations and re-exports.408 424 - Wildcard imports are forbidden outside tests.- Wildcard imports are forbidden outside tests.
426 + **Dependency siloing (incremental-build invariant).** Heavy or fast-moving427 + third-party crates attach at the leaf crate that owns the concern —428 + `reqwest`/`tokio` in `smith-ai`, `syntastica`/`ratatui` in `smith-tui`,429 + `jj-lib`/`gix` behind `smith-core`/`smith-harness` — and MUST NOT propagate up430 + into `smith`. The foundation crate is depended on by every other crate, so any431 + churn or heavy dependency there invalidates the whole workspace's incremental432 + cache; keeping it minimal is what lets an edit to one leaf crate rebuild433 + without touching the others' compiled artifacts. `smith` carries only small,434 + stable, universally-shared code (its one heavy dependency, `mlua`, is a locked435 + exception because the SDK type surface needs it).410 437 Architecture gates:Architecture gates:411 438 - `cargo run -p xtask -- arch` verifies stable Rust metadata/source invariants.- `cargo run -p xtask -- arch` verifies stable Rust metadata/source invariants.412 439 - `cargo run -p xtask -- pup` runs `cargo +nightly-2026-01-22 pup`.- `cargo run -p xtask -- pup` runs `cargo +nightly-2026-01-22 pup`.+70 / −9 text lines
219 219 flate2 = "1"flate2 = "1"
222 + This list is the canonical dependency registry. Adding or removing a crate here223 + is a spec decision (PROJECT-INVARIANTS §5): worker agents escalate to the spec224 + owner and never introduce a dependency on their own; a prototype under225 + `prototypes/` validates a candidate first, and its evidence is what the226 + decision rests on. Version bumps of an already-listed crate are maintenance,227 + not a spec decision — routine bumps ride the CI gates (build, tests,228 + `cargo deny`, the §13.1 compile budget), while a semver-breaking, MSRV-raising,229 + or budget-tripping bump escalates like a new dependency. Heavy dependencies230 + attach at the crate that owns the concern and never propagate up into `smith`231 + (PROJECT-INVARIANTS §11 dependency-siloing invariant), so a leaf-crate edit232 + never rebuilds an unrelated crate's dependency tree.222 234 Two version constraints are load-bearing (prototype-decided, p25/p26): `gix`Two version constraints are load-bearing (prototype-decided, p25/p26): `gix`223 235 is pinned to the version `jj-lib` pulls (0.85) so the two never compile ais pinned to the version `jj-lib` pulls (0.85) so the two never compile a224 236 duplicate gix tree, and `jj-lib` is pinned exact because it is pre-1.0 with aduplicate gix tree, and `jj-lib` is pinned exact because it is pre-1.0 with a929 941 - **Storage never shrinks.** The session file keeps every entry verbatim;- **Storage never shrinks.** The session file keeps every entry verbatim;930 - memory stays bounded by lazy loading (§13.1 ).942 + memory stays bounded by lazy loading (§13.2 ).931 943 - **A compaction pass appends a summary entry** to the current path,- **A compaction pass appends a summary entry** to the current path,932 944 recording the covered span (from/to `EntryId`), the summary text, and recording the covered span (from/to `EntryId`), the summary text, and933 945 before/after token estimates. before/after token estimates.1410 1422 each panel carrying `visible`, `size`, and its own layout. Panels are invisibleeach panel carrying `visible`, `size`, and its own layout. Panels are invisible1411 1423 when empty. Default layout is a Lua plugin.when empty. Default layout is a Lua plugin.
1425 + Composition rules (prototype-proven, p27):1427 + - `overlay` floats over its container area and is excluded from the flow1428 + tiling set — flow siblings still tile as if it were absent, and the overlay1429 + is positioned by the §8.6 anchor model. Overlays may cover flow content by1430 + design (modals, command palette, autocomplete).1431 + - `tabs` reserves a one-row tab bar; the active child gets the remaining area.1432 + - `scrollable` is layout-transparent — a viewport over its child, not an axis1434 + - `Size::Percent` rounds to the nearest cell.1436 + **Resolution (prototype-proven, p27).** Layout resolution never re-enters Lua1437 + on the render path. A plugin builds the layout on change (`set_center_layout`,1438 + `set_*_panel`); the harness converts that Lua tree once into an owned Rust1439 + `LayoutTree` that retains no Lua handle (`Send + 'static`, so it can be built1440 + off the render thread) and drops the Lua value. Every frame, a pure resolver1441 + maps `(LayoutTree, terminal size) → Rect per widget slot` — deterministic for1442 + equal inputs, zero Lua calls in the loop. This is what keeps §12's plugin-1443 + thread round-trips (~81µs, serialized) off the §13 2ms frame budget; measured1444 + per-frame resolution is ~0.4µs (release p99 < 0.8µs) across 80×24 to 400×100.1413 1446 ### 8.8 Theme ### 8.8 Theme 1415 1448 Themes are Lua tables validated by Rust schemas (prototype-proven, p08).Themes are Lua tables validated by Rust schemas (prototype-proven, p08).2451 2484 - Agent loop turn target < 30s excluding provider/network stalls beyond timeout.- Agent loop turn target < 30s excluding provider/network stalls beyond timeout.2452 2485 - Bench regressions fail nightly/release gates (thresholds in §17.9).- Bench regressions fail nightly/release gates (thresholds in §17.9).2454 - ### 13.1 Memory Policy 2487 + ### 13.1 Compile-Time Budget 2489 + Compile time is budgeted on two distinct axes, because they answer different2492 + - **Incremental rebuild is the governing dev/agent metric.** After a one-crate2493 + edit, the rebuild recompiles that crate and its reverse-dependency closure2494 + only — never an unrelated leaf crate or its heavy dependency tree. This is a2495 + structural guarantee of the workspace split + dependency siloing2496 + (PROJECT-INVARIANTS §11), not just a time target; the edit→check loop that2497 + dominates agent and dev work depends on it.2498 + - **Cold build and crate count are a CI-cost sub-budget.** The full transitive2499 + tree (mlua/LuaJIT, jj-lib, gix, reqwest+tokio, aws-lc/TLS, syntastica) is2500 + paid once and cached; the gate is on *regression* — a dependency change that2501 + materially grows cold build or crate count fails CI the same way a2502 + binary-size or bench regression does. Exact thresholds are set from the2503 + first real full-workspace build.2505 + A single TLS backend is shared across `reqwest` and `gix` rather than shipping2508 + ### 13.2 Memory Policy 2456 2510 Prototype-proven against the measured session corpus (p09; seePrototype-proven against the measured session corpus (p09; see2457 2511 `docs/research/SMITH-MEMORY-ALLOCATION-PROFILE.md`):`docs/research/SMITH-MEMORY-ALLOCATION-PROFILE.md`):2550 2604 ### 17.1 Fast Tier ### 17.1 Fast Tier 2606 + Every commit, scoped to the touched crates and their reverse-dependency2607 + closure (`-p <crate>`), so the §13.1 incremental guarantee is realized rather2608 + than erased by a full-workspace `--all-features` sweep:2555 2611 cargo fmt --checkcargo fmt --check2556 - cargo clippy -- workspace --all-targets --all-features -- - D warnings2612 + cargo clippy -p < touched... > --all-targets -- -D warnings2557 2613 cargo run -p xtask -- archcargo run -p xtask -- arch2558 - cargo +nightly-2026-01-22 pup2559 - cargo nextest run --profile fast2614 + cargo +nightly-2026-01-22 pup - p < touched... > 2615 + cargo nextest run --profile fast - p < touched... > 2616 + cargo test --doc - p < touched... > 2619 + The full `--workspace --all-features` clippy/build/test sweep runs in the2620 + medium tier (§17.2), not per-commit. Blocks push.2650 2707 - valid Lua config parsing,- valid Lua config parsing,2651 2708 - token estimator monotonicity,- token estimator monotonicity,2652 2709 - event-to-session-entry conversion,- event-to-session-entry conversion,2653 - - trace filtering preserves order. 2710 + - trace filtering preserves order, 2711 + - layout resolution (§8.7): every child Rect within its parent's bounds; flow2712 + siblings tile their axis without overlap; `expanded` is the exact remainder;2713 + `split` honors `split_ratio` (± one cell) and tiles exactly; resolution is2714 + deterministic for equal `(tree, size)`.2655 2716 Commit `proptest-regressions/`.Commit `proptest-regressions/`.prototypes/PLAN.md Modified +77 / −0 text lines
1859 1859 issues: P1 kstring pin; P2 §9.13 embed default, jj-lib API-stability caveat,issues: P1 kstring pin; P2 §9.13 embed default, jj-lib API-stability caveat,1860 1860 gix 0.83→0.85 alignment.gix 0.83→0.85 alignment.
1862 + ## Campaign 5 — TUI layout resolution 1864 + ## P27 — `p27-per-frame-layout` 1868 + - §8.7: "Rust provides primitives; Lua defines layout."1869 + - §8.5: the render loop ticks at 16ms; §13: TUI frame draw < 2ms.1870 + - §12/p15: Lua runs on one dedicated plugin thread; calls into it are ~81µs1871 + round-trips that serialize.1875 + If layout resolution calls INTO Lua every frame, it puts plugin-thread1876 + round-trips on the render hot path — fighting both the 2ms budget and the §121877 + thread model. The intended-but-unstated design must be validated: Lua builds1878 + the layout tree ONCE (or on change) into owned Rust data, and Rust resolves it1879 + to ratatui `Rect`s every frame with ZERO Lua in the loop.1881 + ### Minimal artifact 1884 + p27-per-frame-layout/1885 + Cargo.toml (mlua luajit vendored, ratatui — prototype-exempt deps)1889 + A Lua plugin defines a layout via the §8.7 primitives; the harness converts it1890 + once into an owned Rust `LayoutTree`; a resolver maps `(tree, terminal size) →1891 + Rect per widget slot`, called every frame.1896 + cd prototypes/p27-per-frame-layout1897 + cargo run -- build-once1898 + cargo run -- resolve-frame1899 + cargo run -- properties1900 + cargo run -- invalidation1906 + - the Lua-defined layout becomes owned Rust data; resolution runs with the Lua1907 + state uninvoked (a call counter proves zero Lua calls per frame), and works1908 + even after the tree is detached from Lua,1909 + - per-frame resolution time measured at 80x24, 200x50, 400x100 for a realistic1910 + default tree (border panels + column of status/messages/input/hints +1911 + overlay) — reported, and far under 2ms,1912 + - layout properties hold: children within parent bounds, siblings do not1913 + overlap, `expanded` fills the remainder, `split_ratio` honored, resolution1914 + deterministic for equal `(tree, size)` — the §17 property-test target,1915 + - the tree is rebuilt only on explicit mutation (`set_center_layout` /1916 + `set_*_panel`); between mutations no Lua re-entry occurs.1920 + State the §8 layout-resolution contract: Lua builds the layout tree on change1921 + into owned Rust data; Rust resolves `Rect`s every frame as a pure,1922 + deterministic function of `(tree, size)` with no Lua in the render loop; name1923 + the layout property invariants as a §17 property-test target.1927 + Status: complete. Proved: the two-phase zero-Lua-in-loop pipeline holds — a1928 + Lua-call counter stayed flat across 10k resolves at 80×24/200×50/400×100; the1929 + owned `LayoutTree` is `Send + 'static` (compile-asserted) and resolves1930 + identically after `drop(lua)` on another thread; release per-frame resolution1931 + median ~0.4µs / p99 < 0.8µs vs the 2ms budget; property invariants hold over1932 + 192 (tree,size) pairs. **Disproved nothing** (the "must re-enter Lua / can't1933 + hit 2ms" counter-hypothesis is refuted). Surfaced a real gap: §8.7 had no1934 + overlay-over-base composition operator, nor rules for tabs/scrollable/Size::Pct1935 + — the prototype's resolutions are now the §8.7 composition rules. Folded into1936 + §8.7 and §17.6. Spec issues: P1 resolution contract, P2 property target, P21862 1939 ## Reporting Template ## Reporting Template 1864 1941 Each completed prototype updates this plan with a result block in theEach completed prototype updates this plan with a result block in theprototypes/p27-per-frame-layout/Cargo.lock Added new file mode 100644+817 / −0 text lines
6 + name = "allocator-api2" 8 + source = "registry+https://github.com/rust-lang/crates.io-index" 9 + checksum = "683d7910e743518b0e34f1186f92494becacb047c7b6bf616c96772180fef923" 14 + source = "registry+https://github.com/rust-lang/crates.io-index" 15 + checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" 20 + source = "registry+https://github.com/rust-lang/crates.io-index" 21 + checksum = "b588b76d00fde79687d7646a9b5bdf3cc0f655e0bbd080335a95d7e96f3587da" 26 + source = "registry+https://github.com/rust-lang/crates.io-index" 27 + checksum = "1f7dc094d718f2e1c1559ad110e27eeaae14a5465d3d56dd6dbd793079fbd530" 36 + source = "registry+https://github.com/rust-lang/crates.io-index" 37 + checksum = "df8670b8c7b9dae1793364eafadf7239c40d669904660c5960d74cfd80b46a53" 42 + source = "registry+https://github.com/rust-lang/crates.io-index" 43 + checksum = "dec551ab6e7578819132c713a93c022a05d60159dc86e7a7050223577484c55a" 51 + source = "registry+https://github.com/rust-lang/crates.io-index" 52 + checksum = "e17dd265a7d0f31ef544e1b20e03add05d3b45b491b633b10d67145d2acc1a38" 61 + source = "registry+https://github.com/rust-lang/crates.io-index" 62 + checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801" 67 + source = "registry+https://github.com/rust-lang/crates.io-index" 68 + checksum = "7fd622ebbb56a5b2ccb651b32b911cdeb2a9b4b11776b2473bf26a26a286244e" 81 + source = "registry+https://github.com/rust-lang/crates.io-index" 82 + checksum = "829d955a0bb380ef178a640b91779e3987da38c9aea133b20614cfed8cdea9c6" 95 + name = "crossterm_winapi" 97 + source = "registry+https://github.com/rust-lang/crates.io-index" 98 + checksum = "acdd7c62a3665c7f6830a51635d9ac9b23ed385797f70a83bb8bafe9c572ab2b" 106 + source = "registry+https://github.com/rust-lang/crates.io-index" 107 + checksum = "25ae13da2f202d56bd7f91c25fba009e7717a1e4a1cc98a76d844b65ae912e9d" 114 + name = "darling_core" 116 + source = "registry+https://github.com/rust-lang/crates.io-index" 117 + checksum = "9865a50f7c335f53564bb694ef660825eb8610e0a53d3e11bf1b0d3df31e03b0" 127 + name = "darling_macro" 129 + source = "registry+https://github.com/rust-lang/crates.io-index" 130 + checksum = "ac3984ec7bd6cfa798e62b4a642426a5be0e68f9401cfc2a01e3fa9ea2fcdb8d" 140 + source = "registry+https://github.com/rust-lang/crates.io-index" 141 + checksum = "91622ff5e7162018101f2fea40d6ebf4a78bbe5a49736a2020649edf9693679e" 146 + source = "registry+https://github.com/rust-lang/crates.io-index" 147 + checksum = "c7f84e12ccf0a7ddc17a6c41c93326024c42920d7ee630d04950e6926645c0fe" 152 + source = "registry+https://github.com/rust-lang/crates.io-index" 153 + checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f" 156 + name = "erased-serde" 158 + source = "registry+https://github.com/rust-lang/crates.io-index" 159 + checksum = "d2add8a07dd6a8d93ff627029c51de145e12686fbc36ecb298ac22e74cf02dec" 169 + source = "registry+https://github.com/rust-lang/crates.io-index" 170 + checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" 173 + "windows-sys 0.61.2" ,177 + name = "find-msvc-tools" 179 + source = "registry+https://github.com/rust-lang/crates.io-index" 180 + checksum = "5baebc0774151f905a1a2cc41989300b1e6fbb29aff0ceffa1064fdd3088d582" 185 + source = "registry+https://github.com/rust-lang/crates.io-index" 186 + checksum = "d9c4f5dac5e15c24eb999c26181a6ca40b39fe946cbe4c263c7209467bc83af2" 191 + source = "registry+https://github.com/rust-lang/crates.io-index" 192 + checksum = "9229cfe53dfd69f0609a49f65461bd93001ea1ef889cd5529dd176593f5338a1" 202 + source = "registry+https://github.com/rust-lang/crates.io-index" 203 + checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" 208 + source = "registry+https://github.com/rust-lang/crates.io-index" 209 + checksum = "b9e0384b61958566e926dc50660321d12159025e767c18e043daf26b70104c39" 214 + source = "registry+https://github.com/rust-lang/crates.io-index" 215 + checksum = "79cf5c93f93228cf8efb3ba362535fb11199ac548a09ce117c9b1adc3030d706" 223 + source = "registry+https://github.com/rust-lang/crates.io-index" 224 + checksum = "5eb2d60ef19920a3a9193c3e371f726ec1dafc045dac788d0fb3704272458971" 236 + source = "registry+https://github.com/rust-lang/crates.io-index" 237 + checksum = "413ee7dfc52ee1a4949ceeb7dbc8a33f2d6c088194d9f922fb8318faf1f01186" 245 + source = "registry+https://github.com/rust-lang/crates.io-index" 246 + checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" 251 + source = "registry+https://github.com/rust-lang/crates.io-index" 252 + checksum = "68ab91017fe16c622486840e4c83c9a37afeff978bd239b5293d61ece587de66" 255 + name = "linux-raw-sys" 257 + source = "registry+https://github.com/rust-lang/crates.io-index" 258 + checksum = "d26c52dbd32dccf2d10cac7725f8eae5296885fb5703b261f7d0a0739ec807ab" 261 + name = "linux-raw-sys" 263 + source = "registry+https://github.com/rust-lang/crates.io-index" 264 + checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53" 269 + source = "registry+https://github.com/rust-lang/crates.io-index" 270 + checksum = "224399e74b87b5f3557511d98dff8b14089b3dadafcab6bb93eab67d3aace965" 278 + source = "registry+https://github.com/rust-lang/crates.io-index" 279 + checksum = "0ceec5bc11778974d1bcb055b18002eba7f4b3518b6a0081b3af5f21666da9ad" 284 + source = "registry+https://github.com/rust-lang/crates.io-index" 285 + checksum = "234cf4f4a04dc1f57e24b96cc0cd600cf2af460d4161ac5ecdd0af8e1f3b2a38" 293 + source = "registry+https://github.com/rust-lang/crates.io-index" 294 + checksum = "1edaf29e3517b49b8b746701e5648ccb5785cde1c119062cbabbc5d5cd115e42" 301 + version = "210.5.12+a4f56a4" 302 + source = "registry+https://github.com/rust-lang/crates.io-index" 303 + checksum = "b3a8e7962a5368d5f264d045a5a255e90f9aa3fc1941ae15a8d2940d42cac671" 312 + source = "registry+https://github.com/rust-lang/crates.io-index" 313 + checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" 318 + source = "registry+https://github.com/rust-lang/crates.io-index" 319 + checksum = "30d65c71f1ce40ab09135ce117d742b9f8a19ff91a41a8b57ed50bc2de59c427" 324 + "windows-sys 0.61.2" ,330 + source = "registry+https://github.com/rust-lang/crates.io-index" 331 + checksum = "c1f5f8fbebc7db5f671671134b9321c4b9aa9adeafccfd9a8c020ae45c6a35d0" 348 + source = "registry+https://github.com/rust-lang/crates.io-index" 349 + checksum = "380c1f7e2099cafcf40e51d3a9f20a346977587aa4d012eae1f043149a728a93" 361 + source = "registry+https://github.com/rust-lang/crates.io-index" 362 + checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" 368 + name = "ordered-float" 370 + source = "registry+https://github.com/rust-lang/crates.io-index" 371 + checksum = "68f19d67e5a2795c94e73e0bb1cc1a7edeb2e28efd39e2e1c9b7a40c1108b11c" 377 + name = "p27-per-frame-layout" 387 + source = "registry+https://github.com/rust-lang/crates.io-index" 388 + checksum = "93857453250e3077bd71ff98b6a65ea6621a19bb0f559a85248955ac12c45a1a" 395 + name = "parking_lot_core" 397 + source = "registry+https://github.com/rust-lang/crates.io-index" 398 + checksum = "2621685985a2ebf1c516881c026032ac7deafcda1a2c9b7850dc81e3dfcb64c1" 410 + source = "registry+https://github.com/rust-lang/crates.io-index" 411 + checksum = "57c0d7b74b563b49d38dae00a0c37d4d6de9b432382b2892f0574ddcae73fd0a" 416 + source = "registry+https://github.com/rust-lang/crates.io-index" 417 + checksum = "19f132c84eca552bf34cab8ec81f1c1dcc229b811638f9d283dceabe58c5569e" 422 + source = "registry+https://github.com/rust-lang/crates.io-index" 423 + checksum = "8fd00f0bb2e90d81d1044c2b32617f68fcb9fa3bb7640c23e9c748e53fb30934" 431 + source = "registry+https://github.com/rust-lang/crates.io-index" 432 + checksum = "dfbc457d0c7a0759a614551b11a6409e5951f6c7537be1f1b7682b9ae9230368" 440 + source = "registry+https://github.com/rust-lang/crates.io-index" 441 + checksum = "eabd94c2f37801c20583fc49dd5cd6b0ba68c716787c2dd6ed18571e1e63117b" 453 + "unicode-segmentation" ,455 + "unicode-width 0.2.0" ,459 + name = "redox_syscall" 461 + source = "registry+https://github.com/rust-lang/crates.io-index" 462 + checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d" 470 + source = "registry+https://github.com/rust-lang/crates.io-index" 471 + checksum = "6b1e7f9a428571be2dc5bc0505c13fb6bf936822b894ec87abf8a08a4e51742d" 476 + source = "registry+https://github.com/rust-lang/crates.io-index" 477 + checksum = "fdb5bc1ae2baa591800df16c9ca78619bf65c0488b41b96ccec5d11220d8c154" 482 + "linux-raw-sys 0.4.15" ,483 + "windows-sys 0.59.0" ,489 + source = "registry+https://github.com/rust-lang/crates.io-index" 490 + checksum = "b6fe4565b9518b83ef4f91bb47ce29620ca828bd32cb7e408f0062e9930ba190" 495 + "linux-raw-sys 0.12.1" ,496 + "windows-sys 0.61.2" ,502 + source = "registry+https://github.com/rust-lang/crates.io-index" 503 + checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f" 508 + source = "registry+https://github.com/rust-lang/crates.io-index" 509 + checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f" 514 + source = "registry+https://github.com/rust-lang/crates.io-index" 515 + checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" 520 + source = "registry+https://github.com/rust-lang/crates.io-index" 521 + checksum = "9a8e94ea7f378bd32cbbd37198a4a91436180c5bb472411e48b5ec2e2124ae9e" 529 + source = "registry+https://github.com/rust-lang/crates.io-index" 530 + checksum = "f3a1a3341211875ef120e117ea7fd5228530ae7e7036a779fdc9117be6b3282c" 539 + source = "registry+https://github.com/rust-lang/crates.io-index" 540 + checksum = "41d385c7d4ca58e59fc732af25c3983b67ac852c1a25000afe1175de458b67ad" 546 + name = "serde_derive" 548 + source = "registry+https://github.com/rust-lang/crates.io-index" 549 + checksum = "d540f220d3187173da220f885ab66608367b6574e925011a9353e4badda91d79" 559 + source = "registry+https://github.com/rust-lang/crates.io-index" 560 + checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" 565 + source = "registry+https://github.com/rust-lang/crates.io-index" 566 + checksum = "d881a16cf4426aa584979d30bd82cb33429027e42122b169753d6ef1085ed6e2" 569 + "signal-hook-registry" ,573 + name = "signal-hook-mio" 575 + source = "registry+https://github.com/rust-lang/crates.io-index" 576 + checksum = "b75a19a7a740b25bc7944bdee6172368f988763b744e3d4dfe753f6b4ece40cc" 584 + name = "signal-hook-registry" 586 + source = "registry+https://github.com/rust-lang/crates.io-index" 587 + checksum = "c4db69cba1110affc0e9f7bcd48bbf87b3f4fc7c61fc9155afd4c469eb3d6c1b" 596 + source = "registry+https://github.com/rust-lang/crates.io-index" 597 + checksum = "8ed6a63f02c8539c91a8685a86f4099661ba3da017932f6ebbea6de3f0fa7c90" 600 + name = "static_assertions" 602 + source = "registry+https://github.com/rust-lang/crates.io-index" 603 + checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f" 608 + source = "registry+https://github.com/rust-lang/crates.io-index" 609 + checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f" 614 + source = "registry+https://github.com/rust-lang/crates.io-index" 615 + checksum = "8fec0f0aef304996cf250b31b5a10dee7980c85da9d759361292b8bca5a18f06" 621 + name = "strum_macros" 623 + source = "registry+https://github.com/rust-lang/crates.io-index" 624 + checksum = "4c6bee85a5a24955dc440386795aa378cd9cf82acd5f764469152d2270e581be" 636 + source = "registry+https://github.com/rust-lang/crates.io-index" 637 + checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297" 647 + source = "registry+https://github.com/rust-lang/crates.io-index" 648 + checksum = "bc7d623258602320d5c55d1bc22793b57daff0ec7efc270ea7d55ce1d5f5471c" 651 + name = "unicode-ident" 653 + source = "registry+https://github.com/rust-lang/crates.io-index" 654 + checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75" 657 + name = "unicode-segmentation" 659 + source = "registry+https://github.com/rust-lang/crates.io-index" 660 + checksum = "c6f5d3c3b1bf09027a88a6bc961fc00497d651009560b5463668dc81b0fa87a8" 663 + name = "unicode-truncate" 665 + source = "registry+https://github.com/rust-lang/crates.io-index" 666 + checksum = "b3644627a5af5fa321c95b9b235a72fd24cd29c648c2c379431e6628655627bf" 669 + "unicode-segmentation" ,670 + "unicode-width 0.1.14" ,674 + name = "unicode-width" 676 + source = "registry+https://github.com/rust-lang/crates.io-index" 677 + checksum = "7dd6e30e90baa6f72411720665d41d89b9a3d039dc45b8faea1ddd07f617f6af" 680 + name = "unicode-width" 682 + source = "registry+https://github.com/rust-lang/crates.io-index" 683 + checksum = "1fc81956842c57dac11422a97c3b8195a1ff727f06e85c84ed2e8aa277c9a0fd" 687 + version = "0.11.1+wasi-snapshot-preview1" 688 + source = "registry+https://github.com/rust-lang/crates.io-index" 689 + checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" 694 + source = "registry+https://github.com/rust-lang/crates.io-index" 695 + checksum = "24d643ce3fd3e5b54854602a080f34fb10ab75e0b813ee32d00ca2b44fa74762" 706 + source = "registry+https://github.com/rust-lang/crates.io-index" 707 + checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419" 709 + "winapi-i686-pc-windows-gnu" ,710 + "winapi-x86_64-pc-windows-gnu" ,714 + name = "winapi-i686-pc-windows-gnu" 716 + source = "registry+https://github.com/rust-lang/crates.io-index" 717 + checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" 720 + name = "winapi-x86_64-pc-windows-gnu" 722 + source = "registry+https://github.com/rust-lang/crates.io-index" 723 + checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" 726 + name = "windows-link" 728 + source = "registry+https://github.com/rust-lang/crates.io-index" 729 + checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" 734 + source = "registry+https://github.com/rust-lang/crates.io-index" 735 + checksum = "1e38bc4d79ed67fd075bcc251a1c39b32a1776bbe92e5bef1f0bf1f8c531853b" 743 + source = "registry+https://github.com/rust-lang/crates.io-index" 744 + checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" 750 + name = "windows-targets" 752 + source = "registry+https://github.com/rust-lang/crates.io-index" 753 + checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" 755 + "windows_aarch64_gnullvm" ,756 + "windows_aarch64_msvc" ,758 + "windows_i686_gnullvm" ,759 + "windows_i686_msvc" ,760 + "windows_x86_64_gnu" ,761 + "windows_x86_64_gnullvm" ,762 + "windows_x86_64_msvc" ,766 + name = "windows_aarch64_gnullvm" 768 + source = "registry+https://github.com/rust-lang/crates.io-index" 769 + checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" 772 + name = "windows_aarch64_msvc" 774 + source = "registry+https://github.com/rust-lang/crates.io-index" 775 + checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" 778 + name = "windows_i686_gnu" 780 + source = "registry+https://github.com/rust-lang/crates.io-index" 781 + checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" 784 + name = "windows_i686_gnullvm" 786 + source = "registry+https://github.com/rust-lang/crates.io-index" 787 + checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" 790 + name = "windows_i686_msvc" 792 + source = "registry+https://github.com/rust-lang/crates.io-index" 793 + checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" 796 + name = "windows_x86_64_gnu" 798 + source = "registry+https://github.com/rust-lang/crates.io-index" 799 + checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" 802 + name = "windows_x86_64_gnullvm" 804 + source = "registry+https://github.com/rust-lang/crates.io-index" 805 + checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" 808 + name = "windows_x86_64_msvc" 810 + source = "registry+https://github.com/rust-lang/crates.io-index" 811 + checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" 816 + source = "registry+https://github.com/rust-lang/crates.io-index" 817 + checksum = "d135d17ab770252ad95e9a872d365cf3090e3be864a34ab46f48555993efc904" prototypes/p27-per-frame-layout/Cargo.toml Added new file mode 100644+9 / −0 text lines
2 + name = "p27-per-frame-layout" 8 + mlua = { version = "0.10" , features = ["luajit" , "vendored" , "serialize" ] }prototypes/p27-per-frame-layout/src/main.rs Added new file mode 100644+1096 / −0 text lines
26 + use std::sync::atomic::{AtomicU64, Ordering};28 + use std::time::{Duration, Instant};30 + use mlua::{Error as LuaError, Lua, Result as LuaResult, Table, Value};31 + use ratatui::backend::TestBackend;32 + use ratatui::buffer::Buffer;33 + use ratatui::layout::{Constraint, Direction, Layout, Rect};34 + use ratatui::widgets::{Block, Paragraph};35 + use ratatui::Terminal;42 + #[derive(Debug, Clone, PartialEq, Eq)]43 + struct SlotId (String);46 + #[derive(Debug, Clone, Copy, PartialEq)]53 + #[derive(Debug, Clone, Copy, PartialEq)]62 + #[derive(Debug, Clone, Copy, PartialEq)]70 + #[derive(Debug, Clone, Copy, PartialEq)]83 + #[derive(Debug, Clone, Copy, PartialEq)]90 + #[derive(Debug, Clone)]94 + layout: Box <LayoutTree>,100 + #[derive(Debug, Clone)]102 + Column(Vec <LayoutTree>),103 + Row(Vec <LayoutTree>),105 + width: Option <Size>,106 + height: Option <Size>,107 + border: BorderStyle,108 + child: Box <LayoutTree>,110 + Expanded(Box <LayoutTree>),116 + child: Box <LayoutTree>,124 + child: Box <LayoutTree>,126 + Spacer(Option <Size>),129 + children: Vec <LayoutTree>,139 + center: Box <LayoutTree>,140 + north: Option <Panel>,141 + east: Option <Panel>,142 + south: Option <Panel>,143 + west: Option <Panel>,151 + const fn _assert_send <T: Send + 'static >() {}152 + const _ : () = _assert_send::<LayoutTree>();154 + fn is_overlay (t: & LayoutTree) -> bool {155 + matches! (t, LayoutTree::Overlay { .. })166 + fn install_layout_api (lua: & Lua, counter: Arc<AtomicU64>) -> LuaResult<()> {167 + let smith = lua.create_table ()? ;168 + let tui = lua.create_table ()? ;169 + let layout = lua.create_table ()? ;172 + for kind in ["column" , "row" , "box" , "expanded" , "scrollable" , "overlay" , "tabs" , "split" , "border" ] {173 + let c = counter.clone ();174 + let f = lua.create_function (move |_ , t: Table| {175 + c.fetch_add (1 , Ordering::Relaxed);176 + t.set ("kind" , kind)? ;179 + layout.set (kind, f)? ;184 + let c = counter.clone ();185 + let f = lua.create_function (move | lua, id: String | {186 + c.fetch_add (1 , Ordering::Relaxed);187 + let t = lua.create_table ()? ;188 + t.set ("kind" , "slot" )? ;192 + layout.set ("slot" , f)? ;197 + let c = counter.clone ();198 + let f = lua.create_function (move | lua, size: Value| {199 + c.fetch_add (1 , Ordering::Relaxed);200 + let t = lua.create_table ()? ;201 + t.set ("kind" , "spacer" )? ;202 + if ! matches! (size, Value::Nil) {203 + t.set ("size" , size)? ;207 + layout.set ("spacer" , f)? ;210 + tui.set ("layout" , layout)? ;211 + smith.set ("tui" , tui)? ;212 + lua.globals ().set ("smith" , smith)? ;219 + fn build_tree (lua: & Lua, script: &str ) -> LuaResult<LayoutTree> {220 + let root: Value = lua.load (script).set_name ("layout" ).eval ()? ;221 + let tree = convert (root)? ;230 + fn rt (msg: impl Into <String >) -> LuaError {231 + LuaError::runtime(msg.into ())234 + fn convert (v: Value) -> LuaResult<LayoutTree> {236 + Value::Table(t) => t,237 + other => return Err (rt (format! ("layout node must be a table, got {}" , other.type_name ()))),239 + let kind: String = t240 + .get::<Option <String >>("kind" )? 241 + .ok_or_else (|| rt ("layout node missing 'kind'" ))? ;243 + match kind.as_str () {244 + "column" => Ok (LayoutTree::Column(convert_children (& t)? )),245 + "row" => Ok (LayoutTree::Row(convert_children (& t)? )),246 + "box" => Ok (LayoutTree::Box {247 + width: opt_size (& t, "width" )? ,248 + height: opt_size (& t, "height" )? ,249 + border: parse_border (t.get::<Option <String >>("border" )? .as_deref ())? ,250 + child: Box ::new(convert (t.get::<Value>(1 )? )? ),252 + "expanded" => Ok (LayoutTree::Expanded(Box ::new(convert (t.get::<Value>(1 )? )? ))),253 + "scrollable" => Ok (LayoutTree::Scrollable {254 + dir: parse_scroll (t.get::<Option <String >>("dir" )? .as_deref ())? ,255 + child: Box ::new(convert (t.get::<Value>(1 )? )? ),257 + "overlay" => Ok (LayoutTree::Overlay {258 + anchor: parse_anchor (t.get::<Option <String >>("anchor" )? .as_deref ())? ,259 + width: req_size (& t, "width" )? ,260 + max_height: req_size (& t, "max_height" )? ,261 + offset_x: t.get::<Option <i64 >>("offset_x" )? .unwrap_or (0 ) as i16 ,262 + offset_y: t.get::<Option <i64 >>("offset_y" )? .unwrap_or (0 ) as i16 ,263 + child: Box ::new(convert (t.get::<Value>(1 )? )? ),265 + "spacer" => Ok (LayoutTree::Spacer(opt_size (& t, "size" )? )),267 + let active = t.get::<Option <i64 >>("active" )? .unwrap_or (0 ).max (0 ) as usize ;268 + Ok (LayoutTree::Tabs {270 + children: convert_children (& t)? ,273 + "split" => Ok (LayoutTree::Split {274 + axis: parse_axis (t.get::<Option <String >>("dir" )? .as_deref ())? ,275 + ratio: t.get::<Option <f64 >>("ratio" )? .unwrap_or (0.5 ) as f32 ,276 + a: Box ::new(convert (t.get::<Value>(1 )? )? ),277 + b: Box ::new(convert (t.get::<Value>(2 )? )? ),279 + "border" => Ok (LayoutTree::Border {280 + center: Box ::new(convert (t.get::<Value>("center" )? )? ),281 + north: opt_panel (& t, "north" )? ,282 + east: opt_panel (& t, "east" )? ,283 + south: opt_panel (& t, "south" )? ,284 + west: opt_panel (& t, "west" )? ,286 + "slot" => Ok (LayoutTree::WidgetSlot(SlotId(287 + t.get::<Option <String >>("id" )? 288 + .ok_or_else (|| rt ("slot missing 'id'" ))? ,290 + other => Err (rt (format! ("unknown layout kind: {other}" ))),294 + fn convert_children (t: & Table) -> LuaResult<Vec <LayoutTree>> {295 + let n = t.raw_len ();296 + let mut out = Vec ::with_capacity(n as usize );298 + out.push (convert (t.get::<Value>(i)? )? );303 + fn parse_size_value (v: Value) -> LuaResult<Size> {305 + Value::Integer(n) => Ok (Size::Abs(n.max (0 ) as u16 )),306 + Value::Number(n) => Ok (Size::Abs(n.max (0.0 ) as u16 )),307 + Value::Table(t) => {308 + if let Some (p) = t.get::<Option <i64 >>("pct" )? {309 + Ok (Size::Pct(p.clamp (0 , 100 ) as u16 ))310 + } else if let Some (a) = t.get::<Option <i64 >>("abs" )? {311 + Ok (Size::Abs(a.max (0 ) as u16 ))313 + Err (rt ("size table needs `pct` or `abs`" ))316 + other => Err (rt (format! ("bad size value: {}" , other.type_name ()))),320 + fn opt_size (t: & Table, key: &str ) -> LuaResult<Option <Size>> {321 + match t.get::<Value>(key)? {322 + Value::Nil => Ok (None ),323 + v => Ok (Some (parse_size_value (v)? )),327 + fn req_size (t: & Table, key: &str ) -> LuaResult<Size> {328 + opt_size (t, key)? .ok_or_else (|| rt (format! ("missing required size `{key}`" )))331 + fn opt_panel (t: & Table, key: &str ) -> LuaResult<Option <Panel>> {332 + match t.get::<Value>(key)? {333 + Value::Nil => Ok (None ),334 + Value::Table(p) => Ok (Some (Panel {335 + visible: p.get::<Option <bool >>("visible" )? .unwrap_or (true ),336 + size: req_size (& p, "size" )? ,337 + layout: Box ::new(convert (p.get::<Value>("layout" )? )? ),339 + other => Err (rt (format! ("panel `{key}` must be a table, got {}" , other.type_name ()))),343 + fn parse_border (s: Option <&str >) -> LuaResult<BorderStyle> {345 + None | Some ("none" ) => BorderStyle::None,346 + Some ("single" ) => BorderStyle::Single,347 + Some ("double" ) => BorderStyle::Double,348 + Some ("rounded" ) => BorderStyle::Rounded,349 + Some ("thick" ) => BorderStyle::Thick,350 + Some (other) => return Err (rt (format! ("unknown border style: {other}" ))),354 + fn parse_scroll (s: Option <&str >) -> LuaResult<ScrollDir> {356 + None | Some ("vertical" ) => ScrollDir::Vertical,357 + Some ("horizontal" ) => ScrollDir::Horizontal,358 + Some ("both" ) => ScrollDir::Both,359 + Some (other) => return Err (rt (format! ("unknown scroll dir: {other}" ))),363 + fn parse_axis (s: Option <&str >) -> LuaResult<Axis> {365 + None | Some ("horizontal" ) => Axis::Horizontal,366 + Some ("vertical" ) => Axis::Vertical,367 + Some (other) => return Err (rt (format! ("unknown split dir: {other}" ))),371 + fn parse_anchor (s: Option <&str >) -> LuaResult<Anchor> {372 + let norm = s.unwrap_or ("center" ).replace ('_' , "-" );373 + Ok (match norm.as_str () {374 + "center" => Anchor::Center,375 + "top-left" => Anchor::TopLeft,376 + "top-center" | "top" => Anchor::TopCenter,377 + "top-right" => Anchor::TopRight,378 + "right-center" | "right" => Anchor::RightCenter,379 + "bottom-right" => Anchor::BottomRight,380 + "bottom-center" | "bottom" => Anchor::BottomCenter,381 + "bottom-left" => Anchor::BottomLeft,382 + "left-center" | "left" => Anchor::LeftCenter,383 + other => return Err (rt (format! ("unknown anchor: {other}" ))),397 + fn resolve (tree: & LayoutTree, area: Rect) -> Vec <(SlotId, Rect)> {398 + let mut out = Vec ::new();399 + resolve_node (tree, area, &mut out);403 + fn resolve_node (t: & LayoutTree, area: Rect, out: &mut Vec <(SlotId, Rect)>) {405 + LayoutTree::WidgetSlot(id) => out.push ((id.clone (), area)),406 + LayoutTree::Spacer(_ ) => {} 407 + LayoutTree::Column(children) => resolve_flow (children, area, Direction::Vertical, out),408 + LayoutTree::Row(children) => resolve_flow (children, area, Direction::Horizontal, out),409 + LayoutTree::Expanded(child) => resolve_node (child, area, out),410 + LayoutTree::Scrollable { child, .. } => resolve_node (child, area, out),417 + let w = width.map_or (area.width, |s| size_cells (s, area.width)).min (area.width);418 + let h = height.map_or (area.height, |s| size_cells (s, area.height)).min (area.height);419 + let box_rect = Rect { x: area.x, y: area.y, width: w, height: h };420 + let inner = if * border == BorderStyle::None {424 + x: box_rect.x.saturating_add (1 ),425 + y: box_rect.y.saturating_add (1 ),426 + width: box_rect.width.saturating_sub (2 ),427 + height: box_rect.height.saturating_sub (2 ),430 + resolve_node (child, inner, out);432 + LayoutTree::Overlay {440 + let rect = overlay_rect (area, * anchor, * width, * max_height, * offset_x, * offset_y);441 + resolve_node (child, rect, out);443 + LayoutTree::Tabs { active, children } => {445 + let content = Rect {447 + y: area.y.saturating_add (1 ),449 + height: area.height.saturating_sub (1 ),451 + if let Some (child) = children.get (* active) {452 + resolve_node (child, content, out);455 + LayoutTree::Split { axis, ratio, a, b } => {456 + let (ra, rb) = split_rect (area, * axis, * ratio);457 + resolve_node (a, ra, out);458 + resolve_node (b, rb, out);460 + LayoutTree::Border {466 + } => resolve_border (center, north, east, south, west, area, out),472 + fn resolve_flow (children: & [LayoutTree], area: Rect, dir: Direction, out: &mut Vec <(SlotId, Rect)>) {473 + let vertical = matches! (dir, Direction::Vertical);474 + let total = if vertical { area.height } else { area.width };476 + let flow: Vec <& LayoutTree> = children.iter ().filter (|c| ! is_overlay (c)).collect ();477 + let floats: Vec <& LayoutTree> = children.iter ().filter (|c| is_overlay (c)).collect ();479 + if ! flow.is_empty () {480 + let constraints: Vec <Constraint> = flow.iter ().map (|c| axis_constraint (c, total, vertical)).collect ();481 + let rects = Layout::default().direction (dir).constraints (constraints).split (area);482 + for (c, r) in flow.iter ().zip (rects.iter ()) {483 + resolve_node (c, * r, out);487 + resolve_node (f, area, out);494 + fn axis_constraint (child: & LayoutTree, total: u16 , vertical: bool ) -> Constraint {496 + LayoutTree::Box { width, height, .. } => {497 + let s = if vertical { * height } else { * width };499 + Some (sz) => Constraint::Length(size_cells (sz, total)),500 + None => Constraint::Fill(1 ),503 + LayoutTree::Spacer(Some (sz)) => Constraint::Length(size_cells (* sz, total)),504 + LayoutTree::Spacer(None ) => Constraint::Fill(1 ),505 + LayoutTree::Expanded(_ ) => Constraint::Fill(1 ),506 + _ => Constraint::Fill(1 ),511 + center: & LayoutTree,512 + north: & Option <Panel>,513 + east: & Option <Panel>,514 + south: & Option <Panel>,515 + west: & Option <Panel>,517 + out: &mut Vec <(SlotId, Rect)>,521 + if let Some (p) = north.as_ref ().filter (|p| p.visible) {522 + let h = size_cells (p.size, area.height).min (mid.height);523 + let r = Rect { x: mid.x, y: mid.y, width: mid.width, height: h };524 + resolve_node (& p.layout, r, out);528 + if let Some (p) = south.as_ref ().filter (|p| p.visible) {529 + let h = size_cells (p.size, area.height).min (mid.height);530 + let r = Rect { x: mid.x, y: mid.y + (mid.height - h), width: mid.width, height: h };531 + resolve_node (& p.layout, r, out);534 + if let Some (p) = west.as_ref ().filter (|p| p.visible) {535 + let w = size_cells (p.size, area.width).min (mid.width);536 + let r = Rect { x: mid.x, y: mid.y, width: w, height: mid.height };537 + resolve_node (& p.layout, r, out);541 + if let Some (p) = east.as_ref ().filter (|p| p.visible) {542 + let w = size_cells (p.size, area.width).min (mid.width);543 + let r = Rect { x: mid.x + (mid.width - w), y: mid.y, width: w, height: mid.height };544 + resolve_node (& p.layout, r, out);547 + resolve_node (center, mid, out);552 + fn split_rect (area: Rect, axis: Axis, ratio: f32 ) -> (Rect, Rect) {553 + let r = ratio.clamp (0.0 , 1.0 );555 + Axis::Horizontal => {556 + let wa = ((area.width as f32 ) * r).round ().clamp (0.0 , area.width as f32 ) as u16 ;557 + let a = Rect { x: area.x, y: area.y, width: wa, height: area.height };558 + let b = Rect { x: area.x + wa, y: area.y, width: area.width - wa, height: area.height };562 + let ha = ((area.height as f32 ) * r).round ().clamp (0.0 , area.height as f32 ) as u16 ;563 + let a = Rect { x: area.x, y: area.y, width: area.width, height: ha };564 + let b = Rect { x: area.x, y: area.y + ha, width: area.width, height: area.height - ha };570 + fn overlay_rect (area: Rect, anchor: Anchor, width: Size, max_height: Size, ox: i16 , oy: i16 ) -> Rect {571 + let w = size_cells (width, area.width).min (area.width);572 + let h = size_cells (max_height, area.height).min (area.height);573 + let (bx, by) = match anchor {574 + Anchor::Center => (mid (area.width, w), mid (area.height, h)),575 + Anchor::TopLeft => (0 , 0 ),576 + Anchor::TopCenter => (mid (area.width, w), 0 ),577 + Anchor::TopRight => (area.width - w, 0 ),578 + Anchor::RightCenter => (area.width - w, mid (area.height, h)),579 + Anchor::BottomRight => (area.width - w, area.height - h),580 + Anchor::BottomCenter => (mid (area.width, w), area.height - h),581 + Anchor::BottomLeft => (0 , area.height - h),582 + Anchor::LeftCenter => (0 , mid (area.height, h)),585 + let max_x = area.width.saturating_sub (w);586 + let max_y = area.height.saturating_sub (h);587 + let x = clamp_off (bx, ox, max_x);588 + let y = clamp_off (by, oy, max_y);589 + Rect { x: area.x + x, y: area.y + y, width: w, height: h }592 + fn mid (total: u16 , part: u16 ) -> u16 {593 + total.saturating_sub (part) / 2 596 + fn clamp_off (base: u16 , off: i16 , max: u16 ) -> u16 {597 + let v = base as i32 + off as i32 ;598 + v.clamp (0 , max as i32 ) as u16 601 + fn size_cells (size: Size, total: u16 ) -> u16 {603 + Size::Abs(n) => n.min (total),604 + Size::Pct(p) => ((total as u32 * p as u32 ) / 100 ) as u16 ,616 + const DEFAULT_LAYOUT : &str = r #" 617 + local L = smith.tui.layout 619 + local center = L.column{ 620 + L.box{ L.slot("status-bar"), height = 1 }, 621 + L.expanded{ L.slot("message-list") }, 622 + L.box{ L.slot("input"), height = 3, border = "rounded" }, 623 + L.box{ L.slot("hint-bar"), height = 1 }, 626 + local base = L.border{ 631 + layout = L.scrollable{ L.slot("file-tree"), dir = "vertical" }, 638 + L.box{ L.slot("command-palette"), border = "double" }, 640 + width = { pct = 60 }, 641 + max_height = { pct = 50 }, 648 + const MUTATED_LAYOUT : &str = r #" 649 + local L = smith.tui.layout 652 + L.box{ L.slot("status-bar"), height = 1 }, 654 + L.expanded{ L.slot("message-list") }, 655 + L.scrollable{ L.slot("detail-pane") }, 659 + L.box{ L.slot("input"), height = 3 }, 668 + fn check (cond: bool , msg: &str ) -> Result <(), String > {670 + println! ("PASS: {msg}" );673 + Err (format! ("FAIL: {msg}" ))677 + fn us (d: Duration) -> f64 {678 + d.as_secs_f64 () * 1_000_000.0 681 + fn build_mode () -> &'static str {682 + if cfg! (debug_assertions) {689 + fn contains (parent: Rect, child: Rect) -> bool {691 + || child.height == 0 692 + || (child.x >= parent.x693 + && child.y >= parent.y694 + && child.x + child.width <= parent.x + parent.width695 + && child.y + child.height <= parent.y + parent.height)698 + fn intersects (a: Rect, b: Rect) -> bool {699 + if a.width == 0 || a.height == 0 || b.width == 0 || b.height == 0 {702 + a.x < b.x + b.width && b.x < a.x + a.width && a.y < b.y + b.height && b.y < a.y + a.height707 + fn render_to_testbackend (slots: & [(SlotId, Rect)], w: u16 , h: u16 ) -> Buffer {708 + let backend = TestBackend::new(w, h);709 + let mut term = Terminal::new(backend).expect ("test backend" );711 + for (slot, rect) in slots {712 + if rect.width == 0 || rect.height == 0 {715 + let block = Block::bordered().title (slot.0. clone ());716 + f.render_widget (Paragraph::new(slot.0. clone ()).block (block), * rect);720 + term.backend ().buffer ().clone ()723 + fn nonblank_cells (buf: & Buffer, w: u16 , h: u16 ) -> usize {727 + if buf[(x, y)].symbol () != " " {739 + fn build_once () -> Result <(), String > {740 + let counter = Arc::new(AtomicU64::new(0 ));741 + let lua = Lua::new();742 + install_layout_api (& lua, counter.clone ()).map_err (|e| e.to_string ())? ;744 + check (counter.load (Ordering::Relaxed) == 0 , "Lua-call counter starts at 0" )? ;746 + let tree = build_tree (& lua, DEFAULT_LAYOUT ).map_err (|e| e.to_string ())? ;747 + let after_build = counter.load (Ordering::Relaxed);748 + check (after_build > 0 , & format! ("building the tree fired {after_build} Lua primitive calls" ))? ;750 + let area = Rect::new(0 , 0 , 120 , 40 );751 + let slots = resolve (& tree, area);752 + let ids: Vec <&str > = slots.iter ().map (|(s, _)| s.0. as_str ()).collect ();754 + ids.contains (& "status-bar" )755 + && ids.contains (& "message-list" )756 + && ids.contains (& "input" )757 + && ids.contains (& "hint-bar" )758 + && ids.contains (& "file-tree" )759 + && ids.contains (& "command-palette" ),760 + & format! ("realistic tree resolves all six slots: {ids:?}" ),764 + let frozen = counter.load (Ordering::Relaxed);766 + let _ = resolve (& tree, area);769 + counter.load (Ordering::Relaxed) == frozen,770 + & format! ("counter frozen at {frozen} across 5000 resolves (zero Lua calls)" ),777 + let expected = slots.clone ();779 + let handle = std::thread::spawn(move || resolve (& moved, Rect::new(0 , 0 , 120 , 40 )));780 + let after_drop = handle.join ().map_err (|_| "resolve thread panicked" .to_string ())? ;782 + after_drop == expected,783 + "identical Rects after dropping Lua and resolving on another thread (Send, no Lua handle)" ,786 + counter.load (Ordering::Relaxed) == frozen,787 + "counter still frozen after Lua state dropped" ,790 + println! ("build-once: {} slots, {after_build} build-time Lua calls, 0 resolve-time Lua calls" , slots.len ());798 + fn resolve_frame () -> Result <(), String > {799 + let counter = Arc::new(AtomicU64::new(0 ));800 + let lua = Lua::new();801 + install_layout_api (& lua, counter.clone ()).map_err (|e| e.to_string ())? ;802 + let tree = build_tree (& lua, DEFAULT_LAYOUT ).map_err (|e| e.to_string ())? ;804 + const N: usize = 10_000 ;805 + const CEIL_US : f64 = 2000.0 ; 807 + for & (w, h) in & [(80 u16 , 24 u16 ), (200 , 50 ), (400 , 100 )] {808 + let area = Rect::new(0 , 0 , w, h);809 + let before = counter.load (Ordering::Relaxed);813 + let _ = resolve (& tree, area);816 + let mut times = Vec ::with_capacity(N);818 + let t0 = Instant::now();819 + let slots = resolve (& tree, area);820 + times.push (t0.elapsed ());821 + std::hint::black_box(& slots);824 + let median = us (times[N / 2 ]);825 + let p99 = us (times[(N * 99 ) / 100 ]);826 + let delta = counter.load (Ordering::Relaxed) - before;828 + check (delta == 0 , & format! ("{w}x{h}: Lua-call delta over {N} resolves == 0" ))? ;832 + "{w}x{h}: median {median:.3}us / p99 {p99:.3}us per resolve (<< 2000us budget, {} build)" ,838 + let slots = resolve (& tree, area);839 + let buf = render_to_testbackend (& slots, w, h);840 + let painted = nonblank_cells (& buf, w, h);843 + & format! ("{w}x{h}: rendered {} slots into TestBackend, {painted} non-blank cells" , slots.len ()),854 + fn properties () -> Result <(), String > {856 + let counter = Arc::new(AtomicU64::new(0 ));857 + let lua = Lua::new();858 + install_layout_api (& lua, counter.clone ()).map_err (|e| e.to_string ())? ;859 + let tree = build_tree (& lua, DEFAULT_LAYOUT ).map_err (|e| e.to_string ())? ;861 + let area = Rect::new(0 , 0 , 80 , 24 );862 + let slots = resolve (& tree, area);863 + let find = |id: &str | slots.iter ().find (|(s, _)| s.0 == id).map (|(_, r)| * r).unwrap ();865 + let status = find ("status-bar" );866 + let msgs = find ("message-list" );867 + let input = find ("input" ); 868 + let hint = find ("hint-bar" );869 + let tree_rect = find ("file-tree" );872 + check (tree_rect.x == 0 && tree_rect.width == 24 , "west file-tree panel is 24 cells wide at x=0" )? ;873 + check (status.x == 24 , "center column starts right of the 24-wide west panel" )? ;877 + check (status.y == 0 && status.height == 1 , "status bar: y=0 h=1" )? ;878 + check (hint.y == 23 && hint.height == 1 , "hint bar pinned to last row (y=23 h=1)" )? ;881 + msgs.height == 24 - 1 - 3 - 1 ,882 + & format! ("expanded message-list takes exact remainder: {} == 19" , msgs.height),884 + check (msgs.y == status.y + status.height, "message-list sits directly below status bar" )? ;886 + check (input.y == 21 && input.height == 1 , "input inner rect inside rounded box (y=21 h=1)" )? ;887 + check (! intersects (status, msgs) && ! intersects (msgs, hint), "center flow siblings do not overlap" )? ;890 + let split_tree = LayoutTree::Split {891 + axis: Axis::Horizontal,893 + a: Box ::new(LayoutTree::WidgetSlot(SlotId("a" .into ()))),894 + b: Box ::new(LayoutTree::WidgetSlot(SlotId("b" .into ()))),896 + let sa = Rect::new(0 , 0 , 100 , 10 );897 + let sr = resolve (& split_tree, sa);898 + let ra = sr.iter ().find (|(s, _)| s.0 == "a" ).unwrap ().1 ;899 + let rb = sr.iter ().find (|(s, _)| s.0 == "b" ).unwrap ().1 ;900 + check (ra.width == 30 , & format! ("split ratio 0.3 of 100 -> left width {} == 30" , ra.width))? ;901 + check (ra.width + rb.width == 100 && rb.x == 30 , "split tiles the axis exactly, no gap/overlap" )? ;904 + let sizes = [(80 u16 , 24 u16 ), (137 , 41 ), (200 , 50 )];905 + let mut checked = 0 usize ;906 + for seed in 0 .. 64 u64 {907 + let mut rng = Lcg(seed.wrapping_mul (0x9E3779B97F4A7C15 ).wrapping_add (1 ));908 + let mut next_id = 0 u32 ;909 + let rtree = gen_tree (&mut rng, 4 , &mut next_id);910 + for & (w, h) in & sizes {911 + let area = Rect::new(0 , 0 , w, h);912 + let r1 = resolve (& rtree, area);913 + let r2 = resolve (& rtree, area);915 + return Err (format! ("FAIL: non-deterministic resolve for seed {seed} at {w}x{h}" ));917 + for (_ , rect) in & r1 {918 + if ! contains (area, * rect) {919 + return Err (format! ("FAIL: slot escapes root bounds (seed {seed}, {w}x{h}): {rect:?}" ));923 + for i in 0 .. r1.len () {924 + for j in (i + 1 ).. r1.len () {925 + if intersects (r1[i].1 , r1[j].1 ) {927 + "FAIL: overlapping slots (seed {seed}, {w}x{h}): {:?} vs {:?}" ,937 + checked == 64 * sizes.len (),938 + & format! ("{checked} (tree,size) pairs: children within parent, siblings disjoint, resolve deterministic" ),941 + println! ("properties: §17 property-test target = {{within-parent, siblings-tile-no-overlap, expanded=remainder, split-ratio±rounding, deterministic}}" );948 + fn next_u64 (&mut self) -> u64 {949 + self.0 = self.0. wrapping_mul (6364136223846793005 ).wrapping_add (1442695040888963407 );952 + fn below (&mut self, n: usize ) -> usize {953 + ((self.next_u64 () >> 33 ) as usize ) % n958 + fn gen_tree (rng: &mut Lcg, depth: u32 , next_id: &mut u32 ) -> LayoutTree {959 + if depth == 0 || rng.below (3 ) == 0 {962 + return LayoutTree::WidgetSlot(SlotId(format! ("s{id}" )));964 + match rng.below (5 ) {966 + let k = 2 + rng.below (3 );967 + let children = (0 .. k)970 + if rng.below (2 ) == 0 {973 + height: Some (Size::Abs(1 + rng.below (4 ) as u16 )),974 + border: BorderStyle::None,975 + child: Box ::new(gen_tree (rng, depth - 1 , next_id)),978 + LayoutTree::Expanded(Box ::new(gen_tree (rng, depth - 1 , next_id)))982 + LayoutTree::Column(children)985 + let k = 2 + rng.below (3 );986 + let children = (0 .. k).map (|_| LayoutTree::Expanded(Box ::new(gen_tree (rng, depth - 1 , next_id)))).collect ();987 + LayoutTree::Row(children)989 + 2 => LayoutTree::Split {990 + axis: if rng.below (2 ) == 0 { Axis::Horizontal } else { Axis::Vertical },991 + ratio: (1 + rng.below (9 )) as f32 / 10.0 ,992 + a: Box ::new(gen_tree (rng, depth - 1 , next_id)),993 + b: Box ::new(gen_tree (rng, depth - 1 , next_id)),995 + 3 => LayoutTree::Box {998 + border: if rng.below (2 ) == 0 { BorderStyle::Single } else { BorderStyle::None },999 + child: Box ::new(gen_tree (rng, depth - 1 , next_id)),1001 + _ => LayoutTree::Scrollable {1002 + dir: ScrollDir::Vertical,1003 + child: Box ::new(gen_tree (rng, depth - 1 , next_id)),1012 + fn invalidation () -> Result <(), String > {1013 + let counter = Arc::new(AtomicU64::new(0 ));1014 + let lua = Lua::new();1015 + install_layout_api (& lua, counter.clone ()).map_err (|e| e.to_string ())? ;1018 + let tree_a = build_tree (& lua, DEFAULT_LAYOUT ).map_err (|e| e.to_string ())? ;1019 + let after_a = counter.load (Ordering::Relaxed);1020 + check (after_a > 0 , & format! ("build A fired {after_a} Lua calls" ))? ;1022 + let area = Rect::new(0 , 0 , 100 , 30 );1023 + let slots_a = resolve (& tree_a, area);1027 + let _ = resolve (& tree_a, area);1030 + counter.load (Ordering::Relaxed) == after_a,1031 + & format! ("counter frozen at {after_a} across 3000 resolves of tree A" ),1035 + let tree_b = build_tree (& lua, MUTATED_LAYOUT ).map_err (|e| e.to_string ())? ;1036 + let after_b = counter.load (Ordering::Relaxed);1037 + check (after_b > after_a, & format! ("mutation (set_center_layout) rebuilds: {after_a} -> {after_b} Lua calls" ))? ;1039 + let slots_b = resolve (& tree_b, area);1040 + let ids_a: Vec <&str > = slots_a.iter ().map (|(s, _)| s.0. as_str ()).collect ();1041 + let ids_b: Vec <&str > = slots_b.iter ().map (|(s, _)| s.0. as_str ()).collect ();1043 + ids_b.contains (& "detail-pane" ) && ! ids_a.contains (& "detail-pane" ),1044 + "new tree exposes the mutated slot set (detail-pane appears only after mutation)" ,1049 + let _ = resolve (& tree_b, area);1052 + counter.load (Ordering::Relaxed) == after_b,1053 + & format! ("counter frozen at {after_b} across 3000 resolves of tree B" ),1056 + println! ("invalidation: tree rebuilds ONLY on explicit mutation; between mutations 0 Lua calls per frame" );1064 + fn run (scenario: &str ) -> Result <(), String > {1066 + "build-once" => build_once (),1067 + "resolve-frame" => resolve_frame (),1068 + "properties" => properties (),1069 + "invalidation" => invalidation (),1071 + println! ("== build-once ==" );1073 + println! ("== resolve-frame ==" );1075 + println! ("== properties ==" );1077 + println! ("== invalidation ==" );1081 + other => Err (format! (1082 + "unknown scenario '{other}'; use build-once|resolve-frame|properties|invalidation|all" 1088 + let scenario = std::env::args().nth (1 ).unwrap_or_else (|| "all" .into ());1089 + match run (& scenario) {1090 + Ok (()) => println! ("PASS: p27 scenario '{scenario}' complete ({} build)" , build_mode ()),1093 + std::process::exit(1 );